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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ce9b755d89a4db853ce4dd62b33cc76509f16df
| 1,259
|
cpp
|
C++
|
Chapters/Chapter13/GoldenEgg/Source/GoldenEgg/SpellForceField.cpp
|
PacktPublishing/Learning-Cpp-by-Creating-Games-with-Unreal-Engine-4-Second-Edition
|
751edc780ba4c87d0a62acd53eacd9f562e06736
|
[
"MIT"
] | null | null | null |
Chapters/Chapter13/GoldenEgg/Source/GoldenEgg/SpellForceField.cpp
|
PacktPublishing/Learning-Cpp-by-Creating-Games-with-Unreal-Engine-4-Second-Edition
|
751edc780ba4c87d0a62acd53eacd9f562e06736
|
[
"MIT"
] | null | null | null |
Chapters/Chapter13/GoldenEgg/Source/GoldenEgg/SpellForceField.cpp
|
PacktPublishing/Learning-Cpp-by-Creating-Games-with-Unreal-Engine-4-Second-Edition
|
751edc780ba4c87d0a62acd53eacd9f562e06736
|
[
"MIT"
] | null | null | null |
#include "GoldenEgg.h"
#include "SpellForceField.h"
#include "Monster.h"
ASpellForceField::ASpellForceField(const class FObjectInitializer& PCIP) : Super(PCIP)
{
ProxSphere = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("ProxSphere"));
ProxSphere->AttachTo( Particles );
Force = 1000;
}
void ASpellForceField::Tick( float DeltaSeconds )
{
// push everything inside the sphere radially
Super::Tick( DeltaSeconds );
// search the proxbox for all actors in the volume.
TArray<AActor*> actors;
ProxSphere->GetOverlappingActors( actors );
// damage each actor the sphere overlaps
for( int c = 0; c < actors.Num(); c++ )
{
// don't damage the spell caster
if( actors[ c ] != Caster )
{
// Only apply the damage if the box is overlapping the actors ROOT component.
// This way damage doesn't get applied for simply overlapping the SightSphere.
AMonster *monster = Cast<AMonster>( actors[c] );
if( monster && ProxSphere->IsOverlappingComponent( monster->GetCapsuleComponent() ) )
{
FVector toMonster = monster->GetActorLocation() - GetActorLocation();
toMonster.Normalize();
monster->Knockback += toMonster*500;
}
}
}
TimeAlive += DeltaSeconds;
if( TimeAlive > Duration )
{
Destroy();
}
}
| 27.369565
| 88
| 0.706116
|
PacktPublishing
|
5ce9e43f9f473d28a1e6d492cfba214cec9951a4
| 424
|
hpp
|
C++
|
src/wifi.hpp
|
ixsiid/espidf-utility
|
06959c10883c9302345e34c23027f75491ec2159
|
[
"MIT"
] | null | null | null |
src/wifi.hpp
|
ixsiid/espidf-utility
|
06959c10883c9302345e34c23027f75491ec2159
|
[
"MIT"
] | null | null | null |
src/wifi.hpp
|
ixsiid/espidf-utility
|
06959c10883c9302345e34c23027f75491ec2159
|
[
"MIT"
] | null | null | null |
#ifndef __UTILITY_WIFI_H
#define __UTILITY_WIFI_H
#include <lwip/inet.h>
class WiFi {
private:
WiFi();
static bool initialized;
static ip4_addr_t ip;
static ip4_addr_t gateway;
static ip4_addr_t subnetmask;
static bool connected;
public:
static bool Connect(const char* ssid, const char* password);
static bool Disconnect(bool release = false);
static ip4_addr_t *getIp();
};
#endif // __UTILITY_WIFI_H
| 19.272727
| 61
| 0.75
|
ixsiid
|
5cee282eefe7faf54143a5c8da6d24341b0e2de5
| 4,436
|
cpp
|
C++
|
src_smartcontract/lang/sc_expression/ConstructorArray.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_smartcontract/lang/sc_expression/ConstructorArray.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_smartcontract/lang/sc_expression/ConstructorArray.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* ConstructorArray.cpp
*
* Created on: 2020/02/12
* Author: iizuka
*/
#include "lang/sc_expression/ConstructorArray.h"
#include "engine/sc_analyze/AnalyzeContext.h"
#include "engine/sc_analyze/AnalyzedType.h"
#include "engine/sc_analyze/AnalyzedThisClassStackPopper.h"
#include "engine/sc_analyze/ValidationError.h"
#include "instance/AbstractVmInstance.h"
#include "vm/VirtualMachine.h"
#include "base_io/ByteBuffer.h"
#include "lang/sc_expression/VariableIdentifier.h"
#include "lang/sc_expression_literal/NumberLiteral.h"
#include "instance/instance_array/VmArrayInstanceUtils.h"
#include "instance/instance_ref/PrimitiveReference.h"
#include "base/StackRelease.h"
namespace alinous {
ConstructorArray::ConstructorArray() : AbstractExpression(CodeElement::EXP_CONSTRUCTORARRAY) {
this->valId = nullptr;
this->atype = nullptr;
}
ConstructorArray::~ConstructorArray() {
delete this->valId;
this->dims.deleteElements();
delete this->atype;
}
int ConstructorArray::binarySize() const {
checkNotNull(this->valId);
int total = sizeof(uint16_t);
total += this->valId->binarySize();
int maxLoop = this->dims.size();
total += sizeof(int32_t);
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
total += exp->binarySize();
}
return total;
}
void ConstructorArray::toBinary(ByteBuffer* out) {
checkNotNull(this->valId);
out->putShort(CodeElement::EXP_CONSTRUCTORARRAY);
this->valId->toBinary(out);
int maxLoop = this->dims.size();
out->putInt(maxLoop);
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->toBinary(out);
}
}
void ConstructorArray::fromBinary(ByteBuffer* in) {
CodeElement* element = createFromBinary(in);
checkKind(element, CodeElement::EXP_VARIABLE_ID);
this->valId = dynamic_cast<VariableIdentifier*>(element);
int maxLoop = in->getInt();
for(int i = 0; i != maxLoop; ++i){
element = createFromBinary(in);
checkIsExp(element);
AbstractExpression* exp = dynamic_cast<AbstractExpression*>(element);
this->dims.addElement(exp);
}
}
void ConstructorArray::preAnalyze(AnalyzeContext* actx) {
this->valId->setParent(this);
this->valId->preAnalyze(actx);
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->setParent(this);
exp->preAnalyze(actx);
}
}
void ConstructorArray::analyzeTypeRef(AnalyzeContext* actx) {
this->valId->analyzeTypeRef(actx);
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->analyzeTypeRef(actx);
}
}
void ConstructorArray::analyze(AnalyzeContext* actx) {
{
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->analyze(actx);
// check array index type
AnalyzedType type = exp->getType(actx);
bool res = VmArrayInstanceUtils::isArrayIndex(type);
if(!res){
actx->addValidationError(ValidationError::CODE_ARRAY_INDEX_MUST_BE_NUMERIC, this, L"Array index must be numeric value.", {});
}
}
}
this->atype = new AnalyzedType(*actx->getTmpArrayType());
int dim = this->dims.size();
this->atype->setDim(dim);
}
AnalyzedType ConstructorArray::getType(AnalyzeContext* actx) {
return *this->atype;
}
void ConstructorArray::init(VirtualMachine* vm) {
this->valId->init(vm);
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->init(vm);
}
}
AbstractVmInstance* ConstructorArray::interpret(VirtualMachine* vm) {
int dim = this->atype->getDim();
int* arrayDim = new int[dim];
StackArrayRelease<int> __releaseArrayDim(arrayDim);
for(int i = 0; i != dim; ++i){
AbstractExpression* idxExp = this->dims.get(i);
AbstractVmInstance* idxInst = idxExp->interpret(vm);
PrimitiveReference* primitive = dynamic_cast<PrimitiveReference*>(idxInst);
int d = primitive->getIntValue();
arrayDim[i] = d;
}
vm->setLastElement(this);
return VmArrayInstanceUtils::buildArrayInstance(vm, arrayDim, dim, this->atype);
}
void ConstructorArray::setValId(VariableIdentifier* valId) noexcept {
this->valId = valId;
}
void ConstructorArray::addDim(AbstractExpression* dim) noexcept {
this->dims.addElement(dim);
}
const UnicodeString* ConstructorArray::getName() const noexcept {
return this->valId->getName();
}
} /* namespace alinous */
| 24.240437
| 129
| 0.714833
|
alinous-core
|
5cf4de84e9ae80dd20b510e889854a9125e9131b
| 17,124
|
cpp
|
C++
|
codec/encoder/core/src/svc_mode_decision.cpp
|
zhuling13/openh264
|
47a2e65327e0081bac87529ed26cfbc377ed4ddc
|
[
"BSD-2-Clause"
] | null | null | null |
codec/encoder/core/src/svc_mode_decision.cpp
|
zhuling13/openh264
|
47a2e65327e0081bac87529ed26cfbc377ed4ddc
|
[
"BSD-2-Clause"
] | null | null | null |
codec/encoder/core/src/svc_mode_decision.cpp
|
zhuling13/openh264
|
47a2e65327e0081bac87529ed26cfbc377ed4ddc
|
[
"BSD-2-Clause"
] | null | null | null |
/*!
* \copy
* Copyright (c) 2009-2013, Cisco Systems
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* \file svc_mode_decision.c
*
* \brief Algorithmetic MD for:
* - multi-spatial Enhancement Layer MD;
* - Scrolling PSkip Decision for screen content
*
* \date 2009.7.29
*
**************************************************************************************
*/
#include "mv_pred.h"
#include "ls_defines.h"
#include "svc_base_layer_md.h"
#include "svc_mode_decision.h"
namespace WelsSVCEnc {
//
// md in enhancement layer
///
inline bool IsMbStatic (int32_t* pBlockType, EStaticBlockIdc eType) {
return (pBlockType != NULL &&
eType == pBlockType[0] &&
eType == pBlockType[1] &&
eType == pBlockType[2] &&
eType == pBlockType[3]);
}
inline bool IsMbCollocatedStatic (int32_t* pBlockType) {
return IsMbStatic (pBlockType, COLLOCATED_STATIC);
}
inline bool IsMbScrolledStatic (int32_t* pBlockType) {
return IsMbStatic (pBlockType, SCROLLED_STATIC);
}
inline int32_t CalUVSadCost (SWelsFuncPtrList* pFunc, uint8_t* pEncOri, int32_t iStrideUV, uint8_t* pRefOri,
int32_t iRefLineSize) {
return pFunc->sSampleDealingFuncs.pfSampleSad[BLOCK_8x8] (pEncOri, iStrideUV, pRefOri, iRefLineSize);
}
inline bool CheckBorder (int32_t iMbX, int32_t iMbY, int32_t iScrollMvX, int32_t iScrollMvY, int32_t iMbWidth,
int32_t iMbHeight) {
return ((iMbX << 4) + iScrollMvX < 0 ||
(iMbX << 4) + iScrollMvX > (iMbWidth - 1) << 4 ||
(iMbY << 4) + iScrollMvY < 0 ||
(iMbY << 4) + iScrollMvY > (iMbHeight - 1) << 4
); //border check for safety
}
void WelsMdSpatialelInterMbIlfmdNoilp (sWelsEncCtx* pEncCtx, SWelsMD* pWelsMd, SSlice* pSlice,
SMB* pCurMb, const Mb_Type kuiRefMbType) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
SMbCache* pMbCache = &pSlice->sMbCacheInfo;
const uint32_t kuiNeighborAvail = pCurMb->uiNeighborAvail;
const int32_t kiMbWidth = pCurDqLayer->iMbWidth;
const SMB* kpTopMb = pCurMb - kiMbWidth;
const bool kbMbLeftAvailPskip = ((kuiNeighborAvail & LEFT_MB_POS) ? IS_SKIP ((pCurMb - 1)->uiMbType) : false);
const bool kbMbTopAvailPskip = ((kuiNeighborAvail & TOP_MB_POS) ? IS_SKIP (kpTopMb->uiMbType) : false);
const bool kbMbTopLeftAvailPskip = ((kuiNeighborAvail & TOPLEFT_MB_POS) ? IS_SKIP ((kpTopMb - 1)->uiMbType) : false);
const bool kbMbTopRightAvailPskip = ((kuiNeighborAvail & TOPRIGHT_MB_POS) ? IS_SKIP ((
kpTopMb + 1)->uiMbType) : false);
bool bTrySkip = kbMbLeftAvailPskip | kbMbTopAvailPskip | kbMbTopLeftAvailPskip | kbMbTopRightAvailPskip;
bool bKeepSkip = kbMbLeftAvailPskip & kbMbTopAvailPskip & kbMbTopRightAvailPskip;
bool bSkip = false;
if (pEncCtx->pFuncList->pfInterMdBackgroundDecision (pEncCtx, pWelsMd, pSlice, pCurMb, pMbCache, &bKeepSkip)) {
return;
}
//step 1: try SKIP
bSkip = WelsMdInterJudgePskip (pEncCtx, pWelsMd, pSlice, pCurMb, pMbCache, bTrySkip);
if (bSkip && bKeepSkip) {
WelsMdInterDecidedPskip (pEncCtx, pSlice, pCurMb, pMbCache);
return;
}
if (! IS_SVC_INTRA (kuiRefMbType)) {
if (!bSkip) {
PredictSad (pMbCache->sMvComponents.iRefIndexCache, pMbCache->iSadCost, 0, &pWelsMd->iSadPredMb);
//step 2: P_16x16
pWelsMd->iCostLuma = WelsMdP16x16 (pEncCtx->pFuncList, pCurDqLayer, pWelsMd, pSlice, pCurMb);
pCurMb->uiMbType = MB_TYPE_16x16;
}
WelsMdInterSecondaryModesEnc (pEncCtx, pWelsMd, pSlice, pCurMb, pMbCache, bSkip);
} else { //BLMODE == SVC_INTRA
//initial prediction memory for I_16x16
const int32_t kiCostI16x16 = WelsMdI16x16 (pEncCtx->pFuncList, pEncCtx->pCurDqLayer, pMbCache, pWelsMd->iLambda);
if (bSkip && (pWelsMd->iCostLuma <= kiCostI16x16)) {
WelsMdInterDecidedPskip (pEncCtx, pSlice, pCurMb, pMbCache);
} else {
pWelsMd->iCostLuma = kiCostI16x16;
pCurMb->uiMbType = MB_TYPE_INTRA16x16;
WelsMdIntraSecondaryModesEnc (pEncCtx, pWelsMd, pCurMb, pMbCache);
}
}
}
void WelsMdInterMbEnhancelayer (void* pEnc, void* pMd, SSlice* pSlice, SMB* pCurMb, SMbCache* pMbCache) {
sWelsEncCtx* pEncCtx = (sWelsEncCtx*)pEnc;
SDqLayer* pCurLayer = pEncCtx->pCurDqLayer;
SWelsMD* pWelsMd = (SWelsMD*)pMd;
const SMB* kpInterLayerRefMb = GetRefMb (pCurLayer, pCurMb);
const Mb_Type kuiInterLayerRefMbType = kpInterLayerRefMb->uiMbType;
SetMvBaseEnhancelayer (pWelsMd, pCurMb,
kpInterLayerRefMb); // initial sMvBase here only when pRef mb type is inter, if not sMvBase will be not used!
//step (3): do the MD process
WelsMdSpatialelInterMbIlfmdNoilp (pEncCtx, pWelsMd, pSlice, pCurMb, kuiInterLayerRefMbType); //MD process
}
///////////////////////
// do initiation for noILP (needed by ILFMD)
////////////////////////
SMB* GetRefMb (SDqLayer* pCurLayer, SMB* pCurMb) {
const SDqLayer* kpRefLayer = pCurLayer->pRefLayer;
const int32_t kiRefMbIdx = (pCurMb->iMbY >> 1) * kpRefLayer->iMbWidth + (pCurMb->iMbX >>
1); //because current lower layer is half size on both vertical and horizontal
return (&kpRefLayer->sMbDataP[kiRefMbIdx]);
}
void SetMvBaseEnhancelayer (SWelsMD* pMd, SMB* pCurMb, const SMB* kpRefMb) {
const Mb_Type kuiRefMbType = kpRefMb->uiMbType;
if (! IS_SVC_INTRA (kuiRefMbType)) {
SMVUnitXY sMv;
int32_t iRefMbPartIdx = ((pCurMb->iMbY & 0x01) << 1) + (pCurMb->iMbX & 0x01); //may be need modified
int32_t iScan4RefPartIdx = g_kuiMbCountScan4Idx[ (iRefMbPartIdx << 2)];
sMv.iMvX = kpRefMb->sMv[iScan4RefPartIdx].iMvX << 1;
sMv.iMvY = kpRefMb->sMv[iScan4RefPartIdx].iMvY << 1;
pMd->sMe.sMe16x16.sMvBase = sMv;
pMd->sMe.sMe8x8[0].sMvBase =
pMd->sMe.sMe8x8[1].sMvBase =
pMd->sMe.sMe8x8[2].sMvBase =
pMd->sMe.sMe8x8[3].sMvBase = sMv;
pMd->sMe.sMe16x8[0].sMvBase =
pMd->sMe.sMe16x8[1].sMvBase =
pMd->sMe.sMe8x16[0].sMvBase =
pMd->sMe.sMe8x16[1].sMvBase = sMv;
}
}
bool JudgeStaticSkip (sWelsEncCtx* pEncCtx, SMB* pCurMb, SMbCache* pMbCache, SWelsMD* pWelsMd) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
const int32_t kiMbX = pCurMb->iMbX;
const int32_t kiMbY = pCurMb->iMbY;
bool bTryStaticSkip = IsMbCollocatedStatic (pWelsMd->iBlock8x8StaticIdc);
if (bTryStaticSkip) {
int32_t iStrideUV, iOffsetUV;
SWelsFuncPtrList* pFunc = pEncCtx->pFuncList;
SPicture* pRefOri = pCurDqLayer->pRefOri;
if (pRefOri != NULL) {
iStrideUV = pCurDqLayer->iEncStride[1];
iOffsetUV = (kiMbX + kiMbY * iStrideUV) << 3;
int32_t iSadCostCb = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[1], iStrideUV, pRefOri->pData[1] + iOffsetUV,
pRefOri->iLineSize[1]);
if (iSadCostCb == 0) {
int32_t iSadCostCr = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[2], iStrideUV, pRefOri->pData[2] + iOffsetUV,
pRefOri->iLineSize[1]);
bTryStaticSkip = (0 == iSadCostCr);
} else bTryStaticSkip = false;
}
}
return bTryStaticSkip;
}
bool JudgeScrollSkip (sWelsEncCtx* pEncCtx, SMB* pCurMb, SMbCache* pMbCache, SWelsMD* pWelsMd) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
const int32_t kiMbX = pCurMb->iMbX;
const int32_t kiMbY = pCurMb->iMbY;
const int32_t kiMbWidth = pCurDqLayer->iMbWidth;
const int32_t kiMbHeight = pCurDqLayer->iMbHeight;
// const int32_t block_width = mb_width << 1;
SVAAFrameInfoExt_t* pVaaExt = static_cast<SVAAFrameInfoExt_t*> (pEncCtx->pVaa);
bool bTryScrollSkip = false;
if (pVaaExt->sScrollDetectInfo.bScrollDetectFlag)
bTryScrollSkip = IsMbCollocatedStatic (pWelsMd->iBlock8x8StaticIdc);
else return 0;
if (bTryScrollSkip) {
int32_t iStrideUV, iOffsetUV;
SWelsFuncPtrList* pFunc = pEncCtx->pFuncList;
SPicture* pRefOri = pCurDqLayer->pRefOri;
if (pRefOri != NULL) {
int32_t iScrollMvX = pVaaExt->sScrollDetectInfo.iScrollMvX;
int32_t iScrollMvY = pVaaExt->sScrollDetectInfo.iScrollMvY;
if (CheckBorder (kiMbX, kiMbY, iScrollMvX, iScrollMvY, kiMbWidth, kiMbHeight)) {
bTryScrollSkip = false;
} else {
iStrideUV = pCurDqLayer->iEncStride[1];
iOffsetUV = (kiMbX << 3) + (iScrollMvX >> 1) + ((kiMbX << 3) + (iScrollMvY >> 1)) * iStrideUV;
int32_t iSadCostCb = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[1], iStrideUV, pRefOri->pData[1] + iOffsetUV,
pRefOri->iLineSize[1]);
if (iSadCostCb == 0) {
int32_t iSadCostCr = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[2], iStrideUV, pRefOri->pData[2] + iOffsetUV,
pRefOri->iLineSize[1]);
bTryScrollSkip = (0 == iSadCostCr);
} else bTryScrollSkip = false;
}
}
}
return bTryScrollSkip;
}
void SvcMdSCDMbEnc (sWelsEncCtx* pEncCtx, SWelsMD* pWelsMd, SMB* pCurMb, SMbCache* pMbCache, SSlice* pSlice,
bool bQpSimilarFlag,
bool bMbSkipFlag, SMVUnitXY sCurMbMv[], ESkipModes eSkipMode) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
SWelsFuncPtrList* pFunc = pEncCtx->pFuncList;
SMVUnitXY sMvp = { 0};
ST16 (&sMvp.iMvX, sCurMbMv[eSkipMode].iMvX);
ST16 (&sMvp.iMvY, sCurMbMv[eSkipMode].iMvY);
uint8_t* pRefLuma = pMbCache->SPicData.pRefMb[0];
uint8_t* pRefCb = pMbCache->SPicData.pRefMb[1];
uint8_t* pRefCr = pMbCache->SPicData.pRefMb[2];
int32_t iLineSizeY = pCurDqLayer->pRefPic->iLineSize[0];
int32_t iLineSizeUV = pCurDqLayer->pRefPic->iLineSize[1];
uint8_t* pDstLuma = pMbCache->pSkipMb;
uint8_t* pDstCb = pMbCache->pSkipMb + 256;
uint8_t* pDstCr = pMbCache->pSkipMb + 256 + 64;
const int32_t iOffsetY = (sCurMbMv[eSkipMode].iMvX >> 2) + (sCurMbMv[eSkipMode].iMvY >> 2) * iLineSizeY;
const int32_t iOffsetUV = (sCurMbMv[eSkipMode].iMvX >> 3) + (sCurMbMv[eSkipMode].iMvY >> 3) * iLineSizeUV;
if (!bQpSimilarFlag || !bMbSkipFlag) {
pDstLuma = pMbCache->pMemPredLuma;
pDstCb = pMbCache->pMemPredChroma;
pDstCr = pMbCache->pMemPredChroma + 64;
}
//MC
pFunc->sMcFuncs.pfLumaQuarpelMc[0] (pRefLuma + iOffsetY, iLineSizeY, pDstLuma, 16, 16);
pFunc->sMcFuncs.pfChromaMc (pRefCb + iOffsetUV, iLineSizeUV, pDstCb, 8, sMvp, 8, 8);
pFunc->sMcFuncs.pfChromaMc (pRefCr + iOffsetUV, iLineSizeUV, pDstCr, 8, sMvp, 8, 8);
pCurMb->uiCbp = 0;
pWelsMd->iCostLuma = 0;
pCurMb->pSadCost[0] = pFunc->sSampleDealingFuncs.pfSampleSad[BLOCK_16x16] (pMbCache->SPicData.pEncMb[0],
pCurDqLayer->iEncStride[0], pRefLuma + iOffsetY, iLineSizeY);
pWelsMd->iCostSkipMb = pCurMb->pSadCost[0];
ST16 (& (pCurMb->sP16x16Mv.iMvX), sCurMbMv[eSkipMode].iMvX);
ST16 (& (pCurMb->sP16x16Mv.iMvY), sCurMbMv[eSkipMode].iMvY);
ST16 (& (pCurDqLayer->pDecPic->sMvList[pCurMb->iMbXY].iMvX), sCurMbMv[eSkipMode].iMvX);
ST16 (& (pCurDqLayer->pDecPic->sMvList[pCurMb->iMbXY].iMvY), sCurMbMv[eSkipMode].iMvY);
if (bQpSimilarFlag && bMbSkipFlag) {
//update motion info to current MB
ST32 (pCurMb->pRefIndex, 0);
pFunc->pfUpdateMbMv (pCurMb->sMv, sMvp);
pCurMb->uiMbType = MB_TYPE_SKIP;
WelsRecPskip (pCurDqLayer, pEncCtx->pFuncList, pCurMb, pMbCache);
WelsMdInterUpdatePskip (pCurDqLayer, pSlice, pCurMb, pMbCache);
return;
}
pCurMb->uiMbType = MB_TYPE_16x16;
pWelsMd->sMe.sMe16x16.sMv.iMvX = sCurMbMv[eSkipMode].iMvX;
pWelsMd->sMe.sMe16x16.sMv.iMvY = sCurMbMv[eSkipMode].iMvY;
PredMv (&pMbCache->sMvComponents, 0, 4, 0, &pWelsMd->sMe.sMe16x16.sMvp);
pMbCache->sMbMvp[0] = pWelsMd->sMe.sMe16x16.sMvp;
UpdateP16x16MotionInfo (pMbCache, pCurMb, 0, &pWelsMd->sMe.sMe16x16.sMv);
if (pWelsMd->bMdUsingSad)
pWelsMd->iCostLuma = pCurMb->pSadCost[0];
else
pWelsMd->iCostLuma = pFunc->sSampleDealingFuncs.pfSampleSad[BLOCK_16x16] (pMbCache->SPicData.pEncMb[0],
pCurDqLayer->iEncStride[0], pRefLuma, iLineSizeY);
WelsInterMbEncode (pEncCtx, pSlice, pCurMb);
WelsPMbChromaEncode (pEncCtx, pSlice, pCurMb);
pFunc->pfCopy16x16Aligned (pMbCache->SPicData.pCsMb[0], pCurDqLayer->iCsStride[0], pMbCache->pMemPredLuma, 16);
pFunc->pfCopy8x8Aligned (pMbCache->SPicData.pCsMb[1], pCurDqLayer->iCsStride[1], pMbCache->pMemPredChroma, 8);
pFunc->pfCopy8x8Aligned (pMbCache->SPicData.pCsMb[2], pCurDqLayer->iCsStride[1], pMbCache->pMemPredChroma + 64, 8);
}
bool MdInterSCDPskipProcess (sWelsEncCtx* pEncCtx, SWelsMD* pWelsMd, SSlice* pSlice, SMB* pCurMb, SMbCache* pMbCache,
ESkipModes eSkipMode) {
SVAAFrameInfoExt_t* pVaaExt = static_cast<SVAAFrameInfoExt_t*> (pEncCtx->pVaa);
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
const int32_t kiRefMbQp = pCurDqLayer->pRefPic->pRefMbQp[pCurMb->iMbXY];
const int32_t kiCurMbQp = pCurMb->uiLumaQp;// unsigned -> signed
pJudgeSkipFun pJudeSkip[2] = {JudgeStaticSkip, JudgeScrollSkip};
bool bSkipFlag = pJudeSkip[eSkipMode] (pEncCtx, pCurMb, pMbCache, pWelsMd);
if (bSkipFlag) {
bool bQpSimilarFlag = (kiRefMbQp - kiCurMbQp <= DELTA_QP_SCD_THD || kiRefMbQp <= 26);
SMVUnitXY sVaaPredSkipMv = { 0 }, sCurMbMv[2] = {0, 0, 0, 0};
PredSkipMv (pMbCache, &sVaaPredSkipMv);
if (eSkipMode == SCROLLED) {
sCurMbMv[1].iMvX = static_cast<int16_t> (pVaaExt->sScrollDetectInfo.iScrollMvX << 2);
sCurMbMv[1].iMvY = static_cast<int16_t> (pVaaExt->sScrollDetectInfo.iScrollMvY << 2);
}
bool bMbSkipFlag = (LD32 (&sVaaPredSkipMv) == LD32 (&sCurMbMv[eSkipMode])) ;
SvcMdSCDMbEnc (pEncCtx, pWelsMd, pCurMb, pMbCache, pSlice, bQpSimilarFlag, bMbSkipFlag, sCurMbMv, eSkipMode);
return true;
}
return false;
}
void SetBlockStaticIdcToMd (void* pVaa, void* pMd, SMB* pCurMb, void* pDqLay) {
SVAAFrameInfoExt_t* pVaaExt = static_cast<SVAAFrameInfoExt_t*> (pVaa);
SWelsMD* pWelsMd = static_cast<SWelsMD*> (pMd);
SDqLayer* pDqLayer = static_cast<SDqLayer*> (pDqLay);
const int32_t kiMbX = pCurMb->iMbX;
const int32_t kiMbY = pCurMb->iMbY;
const int32_t kiMbWidth = pDqLayer->iMbWidth;
const int32_t kiWidth = kiMbWidth << 1;
const int32_t kiBlockIndexUp = (kiMbY << 1) * kiWidth + (kiMbX << 1);
const int32_t kiBlockIndexLow = ((kiMbY << 1) + 1) * kiWidth + (kiMbX << 1);
//fill_blockstaticidc with pVaaExt->pVaaBestBlockStaticIdc
pWelsMd->iBlock8x8StaticIdc[0] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexUp];
pWelsMd->iBlock8x8StaticIdc[1] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexUp + 1];
pWelsMd->iBlock8x8StaticIdc[2] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexLow];
pWelsMd->iBlock8x8StaticIdc[3] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexLow + 1];
}
///////////////////////
// Scene Change Detection (SCD) PSkip Decision for screen content
////////////////////////
bool WelsMdInterJudgeSCDPskip (void* pCtx, void* pMd, SSlice* slice, SMB* pCurMb, SMbCache* pMbCache) {
sWelsEncCtx* pEncCtx = (sWelsEncCtx*)pCtx;
SWelsMD* pWelsMd = (SWelsMD*)pMd;
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
SetBlockStaticIdcToMd (pEncCtx->pVaa, pWelsMd, pCurMb, pCurDqLayer);
//try static Pskip;
//try scrolled Pskip
//TBD
return false;
}
bool WelsMdInterJudgeSCDPskipFalse (void* pEncCtx, void* pWelsMd, SSlice* slice, SMB* pCurMb, SMbCache* pMbCache) {
return false;
}
void WelsInitSCDPskipFunc (SWelsFuncPtrList* pFuncList, const bool bScrollingDetection) {
if (bScrollingDetection) {
pFuncList->pfSCDPSkipDecision = WelsMdInterJudgeSCDPskip;
} else {
pFuncList->pfSCDPSkipDecision = WelsMdInterJudgeSCDPskipFalse;
}
}
} // namespace WelsSVCEnc
| 41.362319
| 134
| 0.683076
|
zhuling13
|
9dc660aa4e41a0a15474be534d00deb672134692
| 5,962
|
cpp
|
C++
|
xlw/InterfaceGenerator/ParserData.cpp
|
jbriand/xlw
|
82b98a12f3c99876e54baa33ff2cb6786df141f7
|
[
"BSD-3-Clause"
] | 34
|
2020-08-10T16:06:50.000Z
|
2022-03-02T18:58:03.000Z
|
xlw/InterfaceGenerator/ParserData.cpp
|
jbriand/xlw
|
82b98a12f3c99876e54baa33ff2cb6786df141f7
|
[
"BSD-3-Clause"
] | 18
|
2020-08-02T23:31:28.000Z
|
2022-03-29T11:55:06.000Z
|
xlw/InterfaceGenerator/ParserData.cpp
|
jbriand/xlw
|
82b98a12f3c99876e54baa33ff2cb6786df141f7
|
[
"BSD-3-Clause"
] | 11
|
2020-07-27T20:44:10.000Z
|
2022-02-02T20:58:59.000Z
|
/*
Copyright (C) 2006 Mark Joshi
Copyright (C) 2007, 2008 Eric Ehlers
Copyright (C) 2011 Narinder Claire
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - https://xlw.github.io/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email xlw-users@lists.sf.net
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#ifdef _MSC_VER
#if _MSC_VER < 1250
#pragma warning(disable:4786)
#endif
#endif
#include "ParserData.h"
#include <vector>
FunctionArgumentType::FunctionArgumentType(std::string NameIdentifier_,
const std::vector<std::string>& ConversionChain_,
const std::string& EXCELKey_)
:
NameIdentifier(NameIdentifier_),
ConversionChain(ConversionChain_),
EXCELKey(EXCELKey_)
{}
const std::string& FunctionArgumentType::GetNameIdentifier() const
{
return NameIdentifier;
}
const std::vector<std::string>& FunctionArgumentType::GetConversionChain() const
{
return ConversionChain;
}
FunctionArgumentType FunctionArgument::GetTheType() const
{
return TheType;
}
const std::string& FunctionArgumentType::GetEXCELKey() const
{
return EXCELKey;
}
std::string FunctionArgument::GetArgumentName() const
{
return ArgumentName;
}
std::string FunctionArgument::GetArgumentDescription() const
{
return ArgumentDescription;
}
FunctionArgument::FunctionArgument(const FunctionArgumentType& TheType_,
std::string ArgumentName_,
std::string ArgumentDescription_)
:
TheType(TheType_),
ArgumentName(ArgumentName_),
ArgumentDescription(ArgumentDescription_)
{
}
std::string FunctionDescription::GetFunctionName() const
{
return FunctionName;
}
std::string FunctionDescription::GetDisplayName() const
{
return DisplayName;
}
void FunctionDescription::setFunctionName(const std::string &newName)
{
FunctionName = newName;
}
std::string FunctionDescription::GetFunctionDescription() const
{
return FunctionHelpDescription;
}
const FunctionArgument& FunctionDescription::GetArgument(
unsigned long ArgumentNumber) const
{
return Arguments.at(ArgumentNumber);
}
unsigned long FunctionDescription::NumberOfArguments() const
{
return static_cast<unsigned long>(Arguments.size());
}
FunctionDescription::FunctionDescription(std::string FunctionName_,
std::string FunctionHelpDescription_,
std::string ReturnType_,
const std::string& ExcelKey_,
const std::vector<FunctionArgument>& Arguments_,
bool Volatile_,
bool Time_,
bool Threadsafe_,
std::string helpID_,
bool Asynchronous_,
bool MacroSheet_,
bool ClusterSafe_)
:
FunctionName(FunctionName_),
DisplayName(FunctionName_),
FunctionHelpDescription(FunctionHelpDescription_),
ReturnType(ReturnType_),
ExcelKey(ExcelKey_),
helpID(helpID_),
Arguments(Arguments_),
Volatile(Volatile_),
Time(Time_),
Threadsafe(Threadsafe_),
Asynchronous(Asynchronous_),
MacroSheet(MacroSheet_),
ClusterSafe(ClusterSafe_)
{
}
std::string FunctionDescription::GetExcelKey() const
{
return ExcelKey;
}
std::string FunctionDescription::GetReturnType() const
{
return ReturnType;
}
bool FunctionDescription::GetVolatile() const
{
return Volatile;
}
bool FunctionDescription::DoTime() const
{
return Time;
}
bool FunctionDescription::GetThreadsafe() const
{
return Threadsafe;
}
std::string FunctionDescription::GetHelpID() const
{
return helpID;
}
bool FunctionDescription::GetAsynchronous() const
{
return Asynchronous;
}
bool FunctionDescription::GetMacroSheet() const
{
return MacroSheet;
}
bool FunctionDescription::GetClusterSafe() const
{
return ClusterSafe;
}
#include<iostream>
void FunctionDescription::Transit(const std::vector<FunctionDescription> &source,
std::vector<FunctionDescription> & destination)
{
if(source.size()!=destination.size())
{
throw("number of managed functions and native wrappers not the same");
}
for(size_t i(0); i <destination.size(); ++i)
{
destination[i].Asynchronous = source[i].Asynchronous;
destination[i].ClusterSafe = source[i].ClusterSafe ;
destination[i].DisplayName = source[i].DisplayName ;
destination[i].FunctionHelpDescription = source[i].FunctionHelpDescription ;
destination[i].helpID = source[i].helpID ;
destination[i].MacroSheet = source[i].MacroSheet ;
destination[i].Threadsafe = source[i].Threadsafe ;
destination[i].Time = source[i].Time ;
destination[i].Volatile = source[i].Volatile ;
if(destination[i].FunctionName != source[i].FunctionName)
{
std::cout << destination[i].FunctionName << " : " << source[i].FunctionName << "\n";
throw("unmanaged wrappers must be in same order as manged function");
}
}
}
| 28.526316
| 87
| 0.626468
|
jbriand
|
9dc6aa79772b5cec8310264f1cedb43cc91d9598
| 5,042
|
hpp
|
C++
|
include/codegen/include/Zenject/ConventionBindInfo.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/Zenject/ConventionBindInfo.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/Zenject/ConventionBindInfo.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:42 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: Dictionary`2<TKey, TValue>
template<typename TKey, typename TValue>
class Dictionary_2;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<TResult, T>
template<typename TResult, typename T>
class Func_2;
// Forward declaring type: Type
class Type;
// Forward declaring type: Func`2<TResult, T>
template<typename TResult, typename T>
class Func_2;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: Assembly
class Assembly;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.ConventionBindInfo
class ConventionBindInfo : public ::Il2CppObject {
public:
// Nested type: Zenject::ConventionBindInfo::$$c__DisplayClass6_0
class $$c__DisplayClass6_0;
// Nested type: Zenject::ConventionBindInfo::$$c__DisplayClass7_0
class $$c__DisplayClass7_0;
// private readonly System.Collections.Generic.List`1<System.Func`2<System.Type,System.Boolean>> _typeFilters
// Offset: 0x10
System::Collections::Generic::List_1<System::Func_2<System::Type*, bool>*>* typeFilters;
// private readonly System.Collections.Generic.List`1<System.Func`2<System.Reflection.Assembly,System.Boolean>> _assemblyFilters
// Offset: 0x18
System::Collections::Generic::List_1<System::Func_2<System::Reflection::Assembly*, bool>*>* assemblyFilters;
// Get static field: static private readonly System.Collections.Generic.Dictionary`2<System.Reflection.Assembly,System.Type[]> _assemblyTypeCache
static System::Collections::Generic::Dictionary_2<System::Reflection::Assembly*, ::Array<System::Type*>*>* _get__assemblyTypeCache();
// Set static field: static private readonly System.Collections.Generic.Dictionary`2<System.Reflection.Assembly,System.Type[]> _assemblyTypeCache
static void _set__assemblyTypeCache(System::Collections::Generic::Dictionary_2<System::Reflection::Assembly*, ::Array<System::Type*>*>* value);
// public System.Void AddAssemblyFilter(System.Func`2<System.Reflection.Assembly,System.Boolean> predicate)
// Offset: 0xD572D0
void AddAssemblyFilter(System::Func_2<System::Reflection::Assembly*, bool>* predicate);
// public System.Void AddTypeFilter(System.Func`2<System.Type,System.Boolean> predicate)
// Offset: 0xD57444
void AddTypeFilter(System::Func_2<System::Type*, bool>* predicate);
// private System.Collections.Generic.IEnumerable`1<System.Reflection.Assembly> GetAllAssemblies()
// Offset: 0xD574AC
System::Collections::Generic::IEnumerable_1<System::Reflection::Assembly*>* GetAllAssemblies();
// private System.Boolean ShouldIncludeAssembly(System.Reflection.Assembly assembly)
// Offset: 0xD574D0
bool ShouldIncludeAssembly(System::Reflection::Assembly* assembly);
// private System.Boolean ShouldIncludeType(System.Type type)
// Offset: 0xD575A4
bool ShouldIncludeType(System::Type* type);
// private System.Type[] GetTypes(System.Reflection.Assembly assembly)
// Offset: 0xD57678
::Array<System::Type*>* GetTypes(System::Reflection::Assembly* assembly);
// public System.Collections.Generic.List`1<System.Type> ResolveTypes()
// Offset: 0xD54BC0
System::Collections::Generic::List_1<System::Type*>* ResolveTypes();
// static private System.Void .cctor()
// Offset: 0xD57778
static void _cctor();
// private System.Collections.Generic.IEnumerable`1<System.Type> <ResolveTypes>b__9_0(System.Reflection.Assembly assembly)
// Offset: 0xD577F0
System::Collections::Generic::IEnumerable_1<System::Type*>* $ResolveTypes$b__9_0(System::Reflection::Assembly* assembly);
// public System.Void .ctor()
// Offset: 0xD54ADC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static ConventionBindInfo* New_ctor();
}; // Zenject.ConventionBindInfo
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::ConventionBindInfo*, "Zenject", "ConventionBindInfo");
#pragma pack(pop)
| 46.256881
| 149
| 0.735026
|
Futuremappermydud
|
9dc97e63f1312f8a4b80091897bc140aa30d23e8
| 2,742
|
cpp
|
C++
|
fifa_gp/predict.cpp
|
vittorioorlandi/STA663_FIFA_GP
|
cb5532f8104fa630b8ea6930f414e3228349ae52
|
[
"MIT"
] | null | null | null |
fifa_gp/predict.cpp
|
vittorioorlandi/STA663_FIFA_GP
|
cb5532f8104fa630b8ea6930f414e3228349ae52
|
[
"MIT"
] | null | null | null |
fifa_gp/predict.cpp
|
vittorioorlandi/STA663_FIFA_GP
|
cb5532f8104fa630b8ea6930f414e3228349ae52
|
[
"MIT"
] | null | null | null |
#include <random>
#include <Eigen/Dense>
#include "HODLR_Tree.hpp"
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <squaredeMat.hpp> //squared exponential kernel
#include <squaredeP1Mat.hpp>
using std::normal_distribution;
namespace py = pybind11;
Eigen::MatrixXd predict(Eigen::MatrixXd X, Eigen::MatrixXd Y, Eigen::MatrixXd Xtest, Eigen::VectorXd sig_samps, Eigen::VectorXd rho_samps, Eigen::VectorXd tau_samps, double multiplier, int M, double tol, int nsamps) {
/*
Sample a draw of the GP function f*|f, sig, rho, tau, x*.
Assume a squared exponential Gaussian Process based on
observed function f at new test points x*.
Temporarily assumes fit method was called with regression = true.
*/
// Create the standard normal generator
normal_distribution<double> norm(0, 1);
std::mt19937 rng;
auto r_std_normal = bind(norm, rng);
int Ntest = Xtest.rows();
int N = X.rows();
int D = X.cols();
// HODLR details
int n_levels = log(N / M) / log(2);
bool is_sym = true;
bool is_pd = true;
double tau;
double rho;
double sig;
double sigsq;
double tmpSSR;
// Allocate space for output
Eigen::MatrixXd fstarsamp(nsamps, Ntest);
Eigen::VectorXd KobsNew(N);
for (int s = 0; s < nsamps; s++) {
sig = sig_samps(s);
tau = tau_samps(s);
rho = rho_samps(s);
sigsq = pow(sig, 2.0);
// HODLR approximation
SQRExponentialP1_Kernel* L = new SQRExponentialP1_Kernel(X, N, sig, rho, tau);
HODLR_Tree* T = new HODLR_Tree(n_levels, tol, L); // With noise (i.e. Sigma + I/tau)
T->assembleTree(is_sym, is_pd);
T->factorize();
for (int i = 0; i < Ntest; i++) {
Eigen::RowVectorXd Xtest_i = Xtest.row(i);
// Get covariance between X and Xtest
for (int j = 0; j < N; j++) {
Eigen::RowVectorXd tmp = X.row(j) - Xtest_i;
tmpSSR = 0.0;
for (int d = 0; d < D; d++) {
tmpSSR = tmpSSR + pow(tmp(d), 2.0);
}
KobsNew(j) = sigsq * exp(- tmpSSR * rho);
}
// Get variance at Xtest
double kNewNew = sigsq + 1e-8;
// Get posterior mean and variance of f* at point xtest(i)
double sdstar = pow(kNewNew - (multiplier * KobsNew.transpose() * T->solve(tau * KobsNew))(0, 0), 0.5);
double mustar = (multiplier * KobsNew.transpose() * T->solve(tau * Y))(0, 0);
auto normal_samp = r_std_normal();
fstarsamp(s, i) = sdstar * normal_samp + mustar;
}
}
return fstarsamp;
}
void predict_module(py::module &m) {
m.def("predict_f", &predict, "predicted samples of f at new X");
}
| 29.804348
| 217
| 0.598833
|
vittorioorlandi
|
9dcad50264e88cff26db3972553fda33ead5bcca
| 4,101
|
hpp
|
C++
|
bridge/cxx/include/bhxx/array_create.hpp
|
bh107/bohrium
|
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
|
[
"Apache-2.0"
] | 236
|
2015-03-31T15:39:30.000Z
|
2022-03-24T01:43:14.000Z
|
bridge/cxx/include/bhxx/array_create.hpp
|
bh107/bohrium
|
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
|
[
"Apache-2.0"
] | 324
|
2015-05-27T10:35:38.000Z
|
2021-12-10T07:34:10.000Z
|
bridge/cxx/include/bhxx/array_create.hpp
|
bh107/bohrium
|
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
|
[
"Apache-2.0"
] | 41
|
2015-05-26T12:38:42.000Z
|
2022-01-10T15:16:37.000Z
|
/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstdint>
#include <bhxx/BhArray.hpp>
#include <bhxx/array_operations.hpp>
namespace bhxx {
/** Return a new empty array
*
* @tparam T The data type of the new array
* @param shape The shape of the new array
* @return The new array
*/
template<typename T>
BhArray <T> empty(Shape shape) {
return BhArray<T>{std::move(shape)};
}
/** Return a new empty array that has the same shape as `ary`
*
* @tparam OutType The data type of the returned new array
* @tparam InType The data type of the input array
* @param ary The array to take the shape from
* @return The new array
*/
template<typename OutType, typename InType>
BhArray <OutType> empty_like(const bhxx::BhArray<InType> &ary) {
return BhArray<OutType>{ary.shape()};
}
/** Return a new array filled with `value`
*
* @tparam T The data type of the new array
* @param shape The shape of the new array
* @param value The value to fill the new array with
* @return The new array
*/
template<typename T>
BhArray <T> full(Shape shape, T value) {
BhArray<T> ret{std::move(shape)};
ret = value;
return ret;
}
/** Return a new array filled with zeros
*
* @tparam T The data type of the new array
* @param shape The shape of the new array
* @return The new array
*/
template<typename T>
BhArray <T> zeros(Shape shape) {
return full(std::move(shape), T{0});
}
/** Return a new array filled with ones
*
* @tparam T The data type of the new array
* @param shape The shape of the new array
* @return The new array
*/
template<typename T>
BhArray <T> ones(Shape shape) {
return full(std::move(shape), T{1});
}
/** Return evenly spaced values within a given interval.
*
* @tparam T Data type of the returned array
* @param start Start of interval. The interval includes this value.
* @param stop End of interval. The interval does not include this value.
* @param step Spacing between values. For any output out, this is the distance between
* two adjacent values, out[i+1] - out[i].
* @return New 1D array
*/
template<typename T>
BhArray <T> arange(int64_t start, int64_t stop, int64_t step);
/** Return evenly spaced values within a given interval using steps of 1.
*
* @tparam T Data type of the returned array
* @param start Start of interval. The interval includes this value.
* @param stop End of interval. The interval does not include this value.
* @return New 1D array
*/
template<typename T>
BhArray <T> arange(int64_t start, int64_t stop) {
return arange<T>(start, stop, 1);
}
/** Return evenly spaced values from 0 to `stop` using steps of 1.
*
* @tparam T Data type of the returned array
* @param stop End of interval. The interval does not include this value.
* @return New 1D array
*/
template<typename T>
BhArray <T> arange(int64_t stop) {
return arange<T>(0, stop, 1);
}
/** Element-wise `static_cast`.
*
* @tparam OutType The data type of the returned array
* @tparam InType The data type of the input array
* @param ary Input array to cast
* @return New array
*/
template<typename OutType, typename InType>
BhArray <OutType> cast(const bhxx::BhArray<InType> &ary) {
BhArray<OutType> ret = empty_like<OutType>(ary);
bhxx::identity(ret, ary);
return ret;
}
} // namespace bhxx
| 29.503597
| 89
| 0.692758
|
bh107
|
9dd070c48e471b1ca04cc3c26cba796e857afa25
| 426
|
cpp
|
C++
|
src/ElfLoader/Core/Exceptions/ProcessorBinaryShutdownException.cpp
|
nathanmentley/-elf-loader
|
9f484fa61592e3af6835858961bf6290436fb418
|
[
"MIT"
] | null | null | null |
src/ElfLoader/Core/Exceptions/ProcessorBinaryShutdownException.cpp
|
nathanmentley/-elf-loader
|
9f484fa61592e3af6835858961bf6290436fb418
|
[
"MIT"
] | null | null | null |
src/ElfLoader/Core/Exceptions/ProcessorBinaryShutdownException.cpp
|
nathanmentley/-elf-loader
|
9f484fa61592e3af6835858961bf6290436fb418
|
[
"MIT"
] | null | null | null |
//
// ProcessorBinaryShutdownException.cpp
// elf-loader
//
// Created by Nathan Mentley on 4/29/20.
// Copyright © 2020 Nathan Mentley. All rights reserved.
//
#include <ElfLoader/Core/Exceptions/ProcessorBinaryShutdownException.h>
Core::Exceptions::ProcessorBinaryShutdownException::ProcessorBinaryShutdownException(
const char* _message
): ProcessorException(_message, "ProcessorBinaryShutdownException", code) {}
| 32.769231
| 85
| 0.788732
|
nathanmentley
|
9dd2e4bb8318b8f7298242866853681f7f10c2f7
| 8,950
|
cpp
|
C++
|
src/qt/qtbase/tests/auto/dbus/qdbusservicewatcher/tst_qdbusservicewatcher.cpp
|
zwollerob/PhantomJS_AMR6VL
|
71c126e98a8c32950158d04d0bd75823cd008b99
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/auto/dbus/qdbusservicewatcher/tst_qdbusservicewatcher.cpp
|
zwollerob/PhantomJS_AMR6VL
|
71c126e98a8c32950158d04d0bd75823cd008b99
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/auto/dbus/qdbusservicewatcher/tst_qdbusservicewatcher.cpp
|
zwollerob/PhantomJS_AMR6VL
|
71c126e98a8c32950158d04d0bd75823cd008b99
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtDBus/QDBusServiceWatcher>
#include <QtDBus>
#include <QtTest>
class tst_QDBusServiceWatcher: public QObject
{
Q_OBJECT
QString serviceName;
int testCounter;
public:
tst_QDBusServiceWatcher();
private slots:
void initTestCase();
void init();
void watchForCreation();
void watchForDisappearance();
void watchForOwnerChange();
void modeChange();
};
tst_QDBusServiceWatcher::tst_QDBusServiceWatcher()
: testCounter(0)
{
}
void tst_QDBusServiceWatcher::initTestCase()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
}
void tst_QDBusServiceWatcher::init()
{
// change the service name from test to test
serviceName = "com.example.TestService" + QString::number(testCounter++);
}
void tst_QDBusServiceWatcher::watchForCreation()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForRegistration);
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceRegistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
spyR.clear();
spyU.clear();
spyO.clear();
// unregister it:
con.unregisterService(serviceName);
// and register again
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
}
void tst_QDBusServiceWatcher::watchForDisappearance()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForUnregistration);
watcher.setObjectName("watcher for disappearance");
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceUnregistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
// unregister it:
con.unregisterService(serviceName);
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 0);
QCOMPARE(spyU.count(), 1);
QCOMPARE(spyU.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.at(0).at(1).toString(), con.baseService());
QVERIFY(spyO.at(0).at(2).toString().isEmpty());
}
void tst_QDBusServiceWatcher::watchForOwnerChange()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForOwnerChange);
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceRegistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
spyR.clear();
spyU.clear();
spyO.clear();
// unregister it:
con.unregisterService(serviceName);
// and register again
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 1);
QCOMPARE(spyU.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.count(), 2);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.at(0).at(1).toString(), con.baseService());
QVERIFY(spyO.at(0).at(2).toString().isEmpty());
QCOMPARE(spyO.at(1).at(0).toString(), serviceName);
QVERIFY(spyO.at(1).at(1).toString().isEmpty());
QCOMPARE(spyO.at(1).at(2).toString(), con.baseService());
}
void tst_QDBusServiceWatcher::modeChange()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForRegistration);
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceRegistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
spyR.clear();
spyU.clear();
spyO.clear();
watcher.setWatchMode(QDBusServiceWatcher::WatchForUnregistration);
// unregister it:
con.unregisterService(serviceName);
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceUnregistered(QString)), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 0);
QCOMPARE(spyU.count(), 1);
QCOMPARE(spyU.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.at(0).at(1).toString(), con.baseService());
QVERIFY(spyO.at(0).at(2).toString().isEmpty());
}
QTEST_MAIN(tst_QDBusServiceWatcher)
#include "tst_qdbusservicewatcher.moc"
| 33.395522
| 105
| 0.694637
|
zwollerob
|
9dd2fbd09ba6dcd244a3d62627615d9dee4ca6ac
| 16,202
|
cpp
|
C++
|
src/core/commands.cpp
|
sellesoft/deshi
|
0bcd13bce29278f89fe6fe7b6658df349c104ee2
|
[
"Unlicense"
] | null | null | null |
src/core/commands.cpp
|
sellesoft/deshi
|
0bcd13bce29278f89fe6fe7b6658df349c104ee2
|
[
"Unlicense"
] | null | null | null |
src/core/commands.cpp
|
sellesoft/deshi
|
0bcd13bce29278f89fe6fe7b6658df349c104ee2
|
[
"Unlicense"
] | null | null | null |
/*Index:
@vars
@add
@run
@init
*/
#include "memory.h"
#define DESHI_CMD_START(name, desc) \
deshi__last_cmd_desc = str8_lit(desc); \
auto deshi__cmd__##name = [](str8* args, u32 arg_count) -> void
#define DESHI_CMD_END_NO_ARGS(name) \
; \
cmd_add(deshi__cmd__##name, str8_lit(#name), deshi__last_cmd_desc, 0, 0)
#define DESHI_CMD_END(name, ...) \
; \
local Type deshi__cmd__##name##args[] = {__VA_ARGS__}; \
cmd_add(deshi__cmd__##name, str8_lit(#name), deshi__last_cmd_desc, deshi__cmd__##name##args, ArrayCount(deshi__cmd__##name##args))
//TODO remove the need for this by having functions take in str8
#define temp_str8_cstr(s) (const char*)str8_copy(s, deshi_temp_allocator).str
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@vars
local array<Command> deshi__cmd_commands(deshi_allocator);
local array<Alias> deshi__cmd_aliases(deshi_allocator);
local str8 deshi__last_cmd_desc;
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@add
void cmd_add(CmdFunc func, str8 name, str8 desc, Type* args, u32 arg_count){
deshi__cmd_commands.add(Command{});
Command* cmd = &deshi__cmd_commands[deshi__cmd_commands.count-1];
cmd->func = func;
cmd->name = name;
cmd->desc = desc;
cmd->args = args;
cmd->arg_count = arg_count;
cmd->min_args = 0;
cmd->max_args = 0;
str8_builder builder;
str8_builder_init(&builder, name, deshi_allocator);
forI(arg_count){
cmd->max_args++;
str8_builder_append(&builder, str8_lit(" "));
if(args[i] & CmdArgument_OPTIONAL){
str8_builder_append(&builder, str8_lit("["));
}else{
str8_builder_append(&builder, str8_lit("<"));
cmd->min_args++;
}
if (args[i] & CmdArgument_S32){
str8_builder_append(&builder, str8_lit("S32"));
}else if(args[i] & CmdArgument_String){
str8_builder_append(&builder, str8_lit("String"));
}else{
Assert(!"unhandled command arguent");
NotImplemented;
}
if(args[i] & CmdArgument_OPTIONAL){
str8_builder_append(&builder, str8_lit("]"));
}else{
str8_builder_append(&builder, str8_lit(">"));
}
}
str8_builder_fit(&builder);
cmd->usage.str = builder.str;
cmd->usage.count = builder.count;
}
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@run
void cmd_run(str8 input){
array<str8> args(deshi_temp_allocator);
//split input by spaces (treating double quoted strings as one item)
//TODO nested aliases
while(input){
str8_advance_while(&input, ' ');
if(!input) break;
str8 word = input;
if(str8_index(word, 0).codepoint == '\"'){
str8_advance(&word);
word = str8_eat_until(word, '\"');
if(word){
args.add(word);
input.str = word.str+word.count+1;
input.count -= word.count+2;
}else{
args.add(input);
break;
}
}else{
word = str8_eat_until(word, ' ');
if(word){
b32 aliased = false;
forE(deshi__cmd_aliases){
if(str8_equal(word, it->alias)){
str8 temp = it->actual;
while(temp){
str8_advance_while(&temp, ' ');
str8 before = temp;
str8_advance_until(&temp, ' ');
args.add(str8{before.str, before.count-temp.count});
}
aliased = true;
break;
}
}
if(!aliased) args.add(word);
input.str = word.str+word.count;
input.count -= word.count;
}else{
b32 aliased = false;
forE(deshi__cmd_aliases){
if(str8_equal(input, it->alias)){
str8 temp = it->actual;
while(temp){
str8_advance_while(&temp, ' ');
str8 before = temp;
str8_advance_until(&temp, ' ');
args.add(str8{before.str, before.count-temp.count});
}
aliased = true;
break;
}
}
if(!aliased) args.add(input);
break;
}
}
}
if(args.count){
u32 args_count = args.count-1;
b32 found = false;
forE(deshi__cmd_commands){
if(str8_equal(args[0], it->name)){
if(it->func){
if(args_count < it->min_args){
LogE("cmd", "Command '",args[0],"' requires at least ",it->min_args," arguments");
}else if(args_count > it->max_args){
LogE("cmd", "Command '",args[0],"' requires at most ",it->max_args," arguments");
}else{
it->func(args.data+1, args_count);
}
}else{
LogE("cmd", "Command '",args[0],"' has no registered function");
}
found = true;
break;
}
}
if(!found){
LogE("cmd", "Unknown command '",args[0],"'");
}
}
}
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@init
void cmd_init(){
DeshiStageInitStart(DS_CMD, DS_MEMORY, "Attempted to initialize Cmd module before initializing Memory module");
DESHI_CMD_START(test, "testing sandbox"){
console_log("{{c=magen}blah blah");
}DESHI_CMD_END_NO_ARGS(test);
DESHI_CMD_START(dir, "List the contents of a directory"){
array<File> files = file_search_directory(args[0]);
char time_str[1024];
if(files.count){
Log("cmd","Directory of '",args[0],"':");
forE(files){
strftime(time_str,1024,"%D %R",localtime((time_t*)&it->last_write_time));
Logf("cmd","%s %s %-30s %lu bytes", time_str,((it->is_directory)?"<DIR> ":"<FILE>"),
(const char*)it->name.str,it->bytes);
}
}
}DESHI_CMD_END(dir, CmdArgument_String);
DESHI_CMD_START(rm, "Remove a file"){
file_delete(args[0]);
}DESHI_CMD_END(rm, CmdArgument_String);
DESHI_CMD_START(file_exists, "Checks if a file exists"){
Log("cmd","File '",args[0],"' ",(file_exists(args[0])) ? "exists." : "does not exist.");
}DESHI_CMD_END(file_exists, CmdArgument_String);
DESHI_CMD_START(rename, "Renames a file"){
file_rename(args[0], args[1]);
}DESHI_CMD_END(rename, CmdArgument_String, CmdArgument_String);
DESHI_CMD_START(add, "Adds two numbers together"){
//TODO rework this to be 'calc' instead of just 'add'
s32 i0 = atoi(temp_str8_cstr(args[0]));
s32 i1 = atoi(temp_str8_cstr(args[1]));
Log("cmd", i0," + ",i1," = ", i0+i1);
}DESHI_CMD_END(add, CmdArgument_S32, CmdArgument_S32);
DESHI_CMD_START(daytime, "Logs the time in day-time format"){
u8 time_buffer[512];
time_t rawtime = time(0);
strftime((char*)time_buffer, 512, "%c", localtime(&rawtime));
Log("cmd",(const char*)time_buffer);
}DESHI_CMD_END_NO_ARGS(daytime);
DESHI_CMD_START(list, "Lists available commands"){
str8_builder builder;
str8_builder_init(&builder, {}, deshi_temp_allocator);
forE(deshi__cmd_commands){
str8_builder_append(&builder, it->name);
str8_builder_append(&builder, str8_lit(": "));
str8_builder_append(&builder, it->desc);
str8_builder_append(&builder, str8_lit("\n"));
}
Log("cmd", (const char*)builder.str);
}DESHI_CMD_END_NO_ARGS(list);
DESHI_CMD_START(help, "Logs description and usage of specified command"){
if(arg_count){
b32 found = false;
forE(deshi__cmd_commands){
if(str8_equal(it->name, args[0])){
Log("cmd", (const char*)it->desc.str);
Log("cmd", (const char*)it->usage.str);
found = true;
break;
}
}
if(!found) LogE("cmd", "Command '",args[0],"' not found");
}else{
Log("cmd", "Use 'help <command>' to get a description and usage of the command");
Log("cmd", "Use 'list' to get a list of all available commands");
Log("cmd", "Usage Format: command <required> [optional]");
}
}DESHI_CMD_END(help, CmdArgument_String|CmdArgument_OPTIONAL);
DESHI_CMD_START(alias, "Gives an alias to specified command and arguments"){
//check that alias' actual won't contain the alias
str8 cursor = args[1];
u32 alias_len = str8_length(args[0]);
u32 prev_codepoint = -1;
while(cursor){
if(args[0].count > cursor.count) break;
if( str8_nequal(cursor, args[0], alias_len)
&& (prev_codepoint == -1 || prev_codepoint == ' ')
&& (cursor.str+args[0].count == cursor.str+cursor.count || str8_index(cursor, alias_len).codepoint == ' ')){
LogE("cmd", "Aliases can't be recursive");
return;
}
prev_codepoint = str8_advance(&cursor).codepoint;
}
//check that alias doesnt start with a number
if(isdigit(str8_index(args[0], 0).codepoint)){
LogE("cmd", "Aliases can't start with a number");
return;
}
//check if name is used by a command
forE(deshi__cmd_commands){
if(str8_equal(it->name, args[0])){
LogE("cmd", "Aliases can't use the same name as an existing command");
return;
}
}
//check if alias already exists
u32 idx = -1;
forE(deshi__cmd_aliases){
if(str8_equal(it->alias, args[0])){
idx = it-it_begin;
break;
}
}
if(idx == -1){
deshi__cmd_aliases.add({str8_copy(args[0], deshi_allocator), str8_copy(args[1], deshi_allocator)});
}else{
memory_zfree(args[1].str);
deshi__cmd_aliases[idx].actual = str8_copy(args[1], deshi_allocator);
}
}DESHI_CMD_END(alias, CmdArgument_String, CmdArgument_String);
DESHI_CMD_START(aliases, "Lists available aliases"){
forE(deshi__cmd_aliases){
Log("cmd", (const char*)it->alias.str,": ",(const char*)it->actual.str);
}
}DESHI_CMD_END_NO_ARGS(aliases);
DESHI_CMD_START(window_display_mode, "Changes whether the window is in windowed(0), borderless(1), or fullscreen(2) mode"){
s32 mode = atoi((const char*)args[0].str);
switch(mode){
case 0:{
window_display_mode(window_active, DisplayMode_Windowed);
Log("cmd", "Window display mode updated to 'windowed'");
}break;
case 1:{
window_display_mode(window_active, DisplayMode_Borderless);
Log("cmd", "Window display mode updated to 'borderless'");
}break;
case 2:{
window_display_mode(window_active, DisplayMode_BorderlessMaximized);
Log("cmd", "Window display mode updated to 'borderless maximized'");
}break;
case 3:{
window_display_mode(window_active, DisplayMode_Fullscreen);
Log("cmd", "Window display mode updated to 'fullscreen'");
}break;
default:{
Log("cmd", "Display Modes: 0=Windowed, 1=Borderless, 2=Borderless Maximized, 3=Fullscreen");
}break;
}
}DESHI_CMD_END(window_display_mode, CmdArgument_S32);
DESHI_CMD_START(window_title, "Changes the title of the active window"){
window_title(window_active, args[0]);
Log("cmd","Updated active window's title to: ",args[0]);
}DESHI_CMD_END(window_title, CmdArgument_String);
DESHI_CMD_START(window_cursor_mode, "Changes whether the cursor is in default(0), first person(1), or hidden(2) mode"){
s32 mode = atoi((const char*)args[0].str);
switch(mode){
case 0:{
window_cursor_mode(window_active, CursorMode_Default);
Log("cmd", "Cursor mode updated to 'default'");
}break;
case 1:{
window_cursor_mode(window_active, CursorMode_FirstPerson);
Log("cmd", "Cursor mode updated to 'first person'");
}break;
default:{
Log("cmd", "Cursor Modes: 0=Default, 1=First Person");
}break;
}
}DESHI_CMD_END(window_cursor_mode, CmdArgument_S32);
DESHI_CMD_START(window_raw_input, "Changes whether the window uses raw input"){
LogE("cmd","Raw Input not setup yet");
return;
s32 mode = atoi((const char*)args[0].str);
switch(mode){
case 0:{
//window_active->UpdateRawInput(false);
Log("cmd", "Raw input updated to 'false'");
}break;
case 1:{
//window_active->UpdateRawInput(true);
Log("cmd", "Raw input updated to 'true'");
}break;
default:{
Log("cmd", "Raw Input: 0=False, 1=True");
}break;
}
}DESHI_CMD_END(window_raw_input, CmdArgument_S32);
DESHI_CMD_START(window_info, "Lists window's vars"){
str8 dispMode;
switch(window_active->display_mode){
case(DisplayMode_Windowed): { dispMode = str8_lit("Windowed"); }break;
case(DisplayMode_Borderless): { dispMode = str8_lit("Borderless"); }break;
case(DisplayMode_BorderlessMaximized):{ dispMode = str8_lit("Borderless Maximized"); }break;
case(DisplayMode_Fullscreen): { dispMode = str8_lit("Fullscreen"); }break;
}
str8 cursMode;
switch(window_active->cursor_mode){
case(CursorMode_Default): { cursMode = str8_lit("Default"); }break;
case(CursorMode_FirstPerson):{ cursMode = str8_lit("First Person"); }break;
}
Log("cmd",
"Window Info"
"\n Index: ",window_active->index,
"\n Title: ",window_active->title,
"\n Client Pos: ",window_active->x,",",window_active->y,
"\n Client Dims: ",window_active->width,"x",window_active->height,
"\n Decorated Pos: ",window_active->position_decorated.x,",",window_active->position_decorated.y,
"\n Decorated Dims: ",window_active->dimensions_decorated.x,"x",window_active->dimensions_decorated.y,
"\n Display Mode: ",dispMode,
"\n Cursor Mode: ",cursMode,
"\n Restore Pos: ",window_active->restore.x,",",window_active->restore.y,
"\n Restore Dims: ",window_active->restore.width,"x",window_active->restore.height);
}DESHI_CMD_END_NO_ARGS(window_info);
DESHI_CMD_START(mat_list, "Lists the materials and their info"){
Log("cmd", "Material List:\nName\tShader\tTextures");
forI(Storage::MaterialCount()){
Material* mat = Storage::MaterialAt(i);
str8_builder builder;
str8_builder_init(&builder, str8{(u8*)mat->name, (s64)strlen(mat->name)}, deshi_temp_allocator);
str8_builder_append(&builder, str8_lit("\t"));
str8_builder_append(&builder, ShaderStrings[mat->shader]);
str8_builder_append(&builder, str8_lit("\t"));
forI(mat->textures.count){
str8_builder_append(&builder, str8_lit(" "));
str8_builder_append(&builder, Storage::TextureName(mat->textures[i]));
}
Log("cmd", (const char*)builder.str);
}
}DESHI_CMD_END_NO_ARGS(mat_list);
DESHI_CMD_START(mat_texture, "Changes a texture of a material"){
s32 matID = atoi(temp_str8_cstr(args[0]));
s32 texSlot = atoi(temp_str8_cstr(args[1]));
s32 texID = atoi(temp_str8_cstr(args[2]));
Storage::MaterialAt(matID)->textures[texSlot] = texID;
Log("cmd", "Updated material ",Storage::MaterialName(matID),"'s texture",texSlot," to ",Storage::TextureName(texID));
}DESHI_CMD_END(mat_texture, CmdArgument_S32, CmdArgument_S32, CmdArgument_S32);
DESHI_CMD_START(mat_shader, "Changes the shader of a material"){
s32 matID = atoi(temp_str8_cstr(args[0]));
s32 shader = atoi(temp_str8_cstr(args[1]));
Storage::MaterialAt(matID)->shader = (Shader)shader;
Log("cmd", "Updated material ",Storage::MaterialName(matID),"'s shader to ", ShaderStrings[shader]);
}DESHI_CMD_END(mat_shader, CmdArgument_S32, CmdArgument_S32);
DESHI_CMD_START(shader_reload, "Reloads specified shader"){
s32 id = atoi((const char*)args[0].str);
if(id == -1){
render_reload_all_shaders();
console_log("{{t=CMD,c=magen}Reloaded all shaders");
}else if(id < Shader_COUNT){
render_reload_shader(id);
console_log("{{t=CMD,c=magen}Reloaded '",ShaderStrings[id]);
}else{
LogE("cmd", "There is no shader with id: ",id);
}
}DESHI_CMD_END(shader_reload, CmdArgument_S32);
DESHI_CMD_START(shader_list, "Lists the shaders and their info"){
Log("cmd", "Shader List:\nID\tName");
forI(ArrayCount(ShaderStrings)){
Log("cmd", i,'\t',ShaderStrings[i]);
}
}DESHI_CMD_END_NO_ARGS(shader_list);
DESHI_CMD_START(texture_load, "Loads a specific texture"){
Stopwatch load_stopwatch = start_stopwatch();
TextureType type = TextureType_2D;
if(arg_count == 2) type = (TextureType)atoi(temp_str8_cstr(args[1]));
Storage::CreateTextureFromFile(args[0], ImageFormat_RGBA, type);
Log("cmd", "Loaded texture '",args[0],"' in ",peek_stopwatch(load_stopwatch),"ms");
}DESHI_CMD_END(texture_load, CmdArgument_String, CmdArgument_S32|CmdArgument_OPTIONAL);
DESHI_CMD_START(texture_list, "Lists the textures and their info"){
Log("cmd", "Texture List:\nName\tWidth\tHeight\tDepth\tMipmaps\tType");
forI(Storage::TextureCount()){
Texture* tex = Storage::TextureAt(i);
Log("cmd", '\n',tex->name,'\t',tex->width,'\t',tex->height,'\t',tex->depth, '\t',tex->mipmaps,'\t',TextureTypeStrings[tex->type]);
}
}DESHI_CMD_END_NO_ARGS(texture_list);
DESHI_CMD_START(quit, "Exits the application"){
platform_exit();
}DESHI_CMD_END_NO_ARGS(quit);
DeshiStageInitEnd(DS_CMD);
}
#undef DESHI_CMD_START
#undef DESHI_CMD_END
| 34.545842
| 133
| 0.660351
|
sellesoft
|
9dd39adbcf01df8879247d8e0f45898bc7bd4eea
| 1,628
|
cpp
|
C++
|
LinkedList/0002-Add-Two-Numbers/main.cpp
|
FeiZhao0531/PlayLeetCode
|
ed23477fd6086d5139bda3d93feeabc09b06854d
|
[
"MIT"
] | 5
|
2019-05-11T18:33:32.000Z
|
2019-12-13T09:13:02.000Z
|
LinkedList/0002-Add-Two-Numbers/main.cpp
|
FeiZhao0531/PlayLeetCode
|
ed23477fd6086d5139bda3d93feeabc09b06854d
|
[
"MIT"
] | null | null | null |
LinkedList/0002-Add-Two-Numbers/main.cpp
|
FeiZhao0531/PlayLeetCode
|
ed23477fd6086d5139bda3d93feeabc09b06854d
|
[
"MIT"
] | null | null | null |
/// Source : https://leetcode.com/problems/add-two-numbers/description/
/// Author : Fei
/// Time : Jun-4-2019
#include "../SingleLinkedList.h"
#include "../SingleLinkedList.cpp"
#include <cassert>
using namespace std;
class Solution
{
public:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
assert( l1 && l2);
ListNode* sumHead = new ListNode(0);
ListNode* curr = sumHead;
int carry = 0;
while( l1 || l2 || carry) {
int sum = carry;
if( l1) {
sum += l1->val;
l1 = l1->next;
}
if( l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
curr->next = new ListNode( sum % 10);
curr = curr->next;
}
ListNode* res = sumHead->next;
delete sumHead;
sumHead = NULL;
return res;
}
};
int main()
{
int arr1[] = {2,4,3,1};
int arr2[] = {5,6,4};
// int arr1[] = {0};
// int arr2[] = {0};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int n2 = sizeof(arr2)/sizeof(arr2[0]);
SingleLinkedList mysinglelinkedlist;
ListNode* l1 = mysinglelinkedlist.createSingleLinkedList(arr1, n1);
ListNode* l2 = mysinglelinkedlist.createSingleLinkedList(arr2, n2);
mysinglelinkedlist.printSingleLinkedList(l1);
mysinglelinkedlist.printSingleLinkedList(l2);
ListNode* head = Solution().addTwoNumbers(l1,l2);
mysinglelinkedlist.printSingleLinkedList(head);
mysinglelinkedlist.deleteSingleLinkedList(head);
return 0;
}
| 25.046154
| 71
| 0.565725
|
FeiZhao0531
|
9dd6cee88efd3209a4e42d91fa65b737411476e3
| 850
|
cxx
|
C++
|
src/TrackFit/KalmanFilterFit/FitMatrices/StdProjectionMatrix.cxx
|
fermi-lat/TkrRecon
|
9174a0ab1310038d3956ab4dcc26e06b8a845daf
|
[
"BSD-3-Clause"
] | null | null | null |
src/TrackFit/KalmanFilterFit/FitMatrices/StdProjectionMatrix.cxx
|
fermi-lat/TkrRecon
|
9174a0ab1310038d3956ab4dcc26e06b8a845daf
|
[
"BSD-3-Clause"
] | null | null | null |
src/TrackFit/KalmanFilterFit/FitMatrices/StdProjectionMatrix.cxx
|
fermi-lat/TkrRecon
|
9174a0ab1310038d3956ab4dcc26e06b8a845daf
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* @class StdProjectionMatrix
*
* @brief Definition of a Kalman Filter projection matrix. This is used to projected out the measured
* coordinates (and errors) from the state vector (covariance matrix) during the track fits
*
* @author Tracy Usher
*
* $Header: /nfs/slac/g/glast/ground/cvs/TkrRecon/src/TrackFit/KalmanFilterFit/FitMatrices/StdProjectionMatrix.cxx,v 1.2 2004/10/01 21:07:39 usher Exp $
*/
#include "StdProjectionMatrix.h"
#include "src/TrackFit/KalmanFilterFit/KalmanFilterInit.h"
#include "idents/TkrId.h"
StdProjectionMatrix::StdProjectionMatrix() : m_none(1,4), m_projX(1,4), m_projY(1,4)
{
m_projX(1,1) = 1;
m_projY(1,3) = 1;
return;
}
KFmatrix& StdProjectionMatrix::operator()(const idents::TkrId &id)
{
if (id.getView() == idents::TkrId::eMeasureX) return m_projX;
return m_projY;
}
| 27.419355
| 152
| 0.716471
|
fermi-lat
|
9dd6f5554452911a8c6ef1b2f5126a2e0ace466b
| 6,923
|
cpp
|
C++
|
components/z8lua/lpico8lib.cpp
|
concreted/tac08
|
ce0743c9c98b458e67f7473eaf423520f639a2e5
|
[
"MIT"
] | 1
|
2021-01-02T19:18:19.000Z
|
2021-01-02T19:18:19.000Z
|
components/z8lua/lpico8lib.cpp
|
concreted/tac08
|
ce0743c9c98b458e67f7473eaf423520f639a2e5
|
[
"MIT"
] | null | null | null |
components/z8lua/lpico8lib.cpp
|
concreted/tac08
|
ce0743c9c98b458e67f7473eaf423520f639a2e5
|
[
"MIT"
] | null | null | null |
//
// ZEPTO-8 — Fantasy console emulator
//
// Copyright © 2016—2017 Sam Hocevar <sam@hocevar.net>
//
// This program is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What the Fuck You Want
// to Public License, Version 2, as published by the WTFPL Task Force.
// See http://www.wtfpl.net/ for more details.
//
#include <cmath>
#include <cctype>
#include <cstring>
#include <algorithm>
#define lpico8lib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "llimits.h"
#include "lobject.h"
#include "lstate.h"
#define TAU 6.2831853071795864769252867665590057683936
static int pico8_max(lua_State *l) {
lua_pushnumber(l, lua_Number::max(lua_tonumber(l, 1), lua_tonumber(l, 2)));
return 1;
}
static int pico8_min(lua_State *l) {
lua_pushnumber(l, lua_Number::min(lua_tonumber(l, 1), lua_tonumber(l, 2)));
return 1;
}
static int pico8_mid(lua_State *l) {
lua_Number x = lua_tonumber(l, 1);
lua_Number y = lua_tonumber(l, 2);
lua_Number z = lua_tonumber(l, 3);
lua_pushnumber(l, x > y ? y > z ? y : lua_Number::min(x, z)
: x > z ? x : lua_Number::min(y, z));
return 1;
}
static int pico8_ceil(lua_State *l) {
lua_pushnumber(l, lua_Number::ceil(lua_tonumber(l, 1)));
return 1;
}
static int pico8_flr(lua_State *l) {
lua_pushnumber(l, lua_Number::floor(lua_tonumber(l, 1)));
return 1;
}
static int pico8_cos(lua_State *l) {
lua_pushnumber(l, cast_num(std::cos(-TAU * (double)lua_tonumber(l, 1))));
return 1;
}
static int pico8_sin(lua_State *l) {
lua_pushnumber(l, cast_num(std::sin(-TAU * (double)lua_tonumber(l, 1))));
return 1;
}
static int pico8_atan2(lua_State *l) {
lua_Number x = lua_tonumber(l, 1);
lua_Number y = lua_tonumber(l, 2);
// This could simply be atan2(-y,x) but since PICO-8 decided that
// atan2(0,0) = 0.75 we need to do the same in our version.
double a = 0.75 + std::atan2((double)x, (double)y) / TAU;
lua_pushnumber(l, cast_num(a >= 1 ? a - 1 : a));
return 1;
}
static int pico8_sqrt(lua_State *l) {
lua_Number x = lua_tonumber(l, 1);
/* FIXME PICO-8 actually returns stuff for negative values */
lua_pushnumber(l, cast_num(x.bits() >= 0 ? std::sqrt((double)x) : 0));
return 1;
}
static int pico8_abs(lua_State *l) {
lua_pushnumber(l, lua_Number::abs(lua_tonumber(l, 1)));
return 1;
}
static int pico8_sgn(lua_State *l) {
lua_pushnumber(l, cast_num(lua_tonumber(l, 1).bits() >= 0 ? 1.0 : -1.0));
return 1;
}
static int pico8_band(lua_State *l) {
lua_pushnumber(l, lua_tonumber(l, 1) & lua_tonumber(l, 2));
return 1;
}
static int pico8_bor(lua_State *l) {
lua_pushnumber(l, lua_tonumber(l, 1) | lua_tonumber(l, 2));
return 1;
}
static int pico8_bxor(lua_State *l) {
lua_pushnumber(l, lua_tonumber(l, 1) ^ lua_tonumber(l, 2));
return 1;
}
static int pico8_bnot(lua_State *l) {
lua_pushnumber(l, ~lua_tonumber(l, 1));
return 1;
}
static int pico8_shl(lua_State *l) {
// If y is negative, it is interpreted modulo 32.
// If y is >= 32, result is always zero.
int32_t xbits = lua_tonumber(l, 1).bits();
int y = (int)lua_tonumber(l, 2);
lua_pushnumber(l, lua_Number::frombits(y >= 32 ? 0 : xbits << (y & 0x1f)));
return 1;
}
static int pico8_lshr(lua_State *l) {
int32_t xbits = lua_tonumber(l, 1).bits();
int y = (int)lua_tonumber(l, 2);
lua_pushnumber(l, lua_Number::frombits(y >= 32 ? 0 : (uint32_t)xbits >> (y & 0x1f)));
return 1;
}
static int pico8_shr(lua_State *l) {
// If y is negative, it is interpreted modulo 32.
// If y is >= 32, only the sign is preserved, so it's
// the same as for y == 31.
int32_t xbits = lua_tonumber(l, 1).bits();
int y = (int)lua_tonumber(l, 2);
lua_pushnumber(l, lua_Number::frombits(xbits >> (std::min(y, 31) & 0x1f)));
return 1;
}
static int pico8_rotl(lua_State *l) {
int32_t xbits = lua_tonumber(l, 1).bits();
int y = 0x1f & (int)lua_tonumber(l, 2);
lua_pushnumber(l, lua_Number::frombits((xbits << y) | ((uint32_t)xbits >> (32 - y))));
return 1;
}
static int pico8_rotr(lua_State *l) {
int32_t xbits = lua_tonumber(l, 1).bits();
int y = 0x1f & (int)lua_tonumber(l, 2);
lua_pushnumber(l, lua_Number::frombits(((uint32_t)xbits >> y) | (xbits << (32 - y))));
return 1;
}
static int pico8_tostr(lua_State *l) {
char buffer[20];
char const *s = buffer;
switch (lua_type(l, 1))
{
case LUA_TNUMBER: {
lua_Number x = lua_tonumber(l, 1);
if (lua_toboolean(l, 2)) {
uint32_t b = (uint32_t)x.bits();
sprintf(buffer, "0x%04x.%04x", (b >> 16) & 0xffff, b & 0xffff);
} else {
lua_number2str(buffer, x);
}
break;
}
case LUA_TSTRING: s = lua_tostring(l, 1); break;
case LUA_TBOOLEAN: s = lua_toboolean(l, 1) ? "true" : "false"; break;
default: sprintf(buffer, "[%s]", luaL_typename(l, 1)); break;
}
lua_pushstring(l, s);
return 1;
}
static int pico8_tonum(lua_State *l) {
char const *s = lua_tostring(l, 1);
lua_Number ret;
// If parsing failed, PICO-8 returns nothing
if (!luaO_str2d(s, strlen(s), &ret)) return 0;
lua_pushnumber(l, ret);
return 1;
}
static void update_prng(global_State *g) {
g->prngseed2 = g->prngseed1 + ((g->prngseed2 >> 16) | (g->prngseed2 << 16));
g->prngseed1 += g->prngseed2;
}
static int pico8_srand(lua_State *L) {
uint32_t seed = lua_tonumber(L, 1).bits();
G(L)->prngseed1 = seed ? seed : 0xdeadbeef;
G(L)->prngseed2 = G(L)->prngseed1 ^ 0xbead29ba;
for (int i = 0; i < 32; ++i)
update_prng(G(L));
return 0;
}
static int pico8_rnd(lua_State *L) {
uint32_t range = lua_isnone(L, 1) ? 0x10000 : lua_tonumber(L, 1).bits();
update_prng(G(L));
lua_pushnumber(L, lua_Number::frombits(range ? G(L)->prngseed2 % range : 0));
return 1;
}
static const luaL_Reg pico8lib[] = {
{"max", pico8_max},
{"min", pico8_min},
{"mid", pico8_mid},
{"ceil", pico8_ceil},
{"flr", pico8_flr},
{"cos", pico8_cos},
{"sin", pico8_sin},
{"atan2", pico8_atan2},
{"sqrt", pico8_sqrt},
{"abs", pico8_abs},
{"sgn", pico8_sgn},
{"band", pico8_band},
{"bor", pico8_bor},
{"bxor", pico8_bxor},
{"bnot", pico8_bnot},
{"shl", pico8_shl},
{"shr", pico8_shr},
{"lshr", pico8_lshr},
{"rotl", pico8_rotl},
{"rotr", pico8_rotr},
{"tostr", pico8_tostr},
{"tonum", pico8_tonum},
{"srand", pico8_srand},
{"rnd", pico8_rnd},
{NULL, NULL}
};
/*
** Register PICO-8 functions in global table
*/
LUAMOD_API int luaopen_pico8 (lua_State *L) {
lua_pushglobaltable(L);
luaL_setfuncs(L, pico8lib, 0);
return 1;
}
| 27.915323
| 90
| 0.619674
|
concreted
|
9dd7e968b3ad4c4aa4f1ecf9cae9d75fd798df51
| 1,557
|
cpp
|
C++
|
test/test.cpp
|
jermp/mm_file
|
ed6dbb828d7ed85128241ef6693bf383d7f7cb2d
|
[
"MIT"
] | 8
|
2019-06-06T13:31:01.000Z
|
2022-02-09T01:35:48.000Z
|
test/test.cpp
|
jermp/mm_file
|
ed6dbb828d7ed85128241ef6693bf383d7f7cb2d
|
[
"MIT"
] | null | null | null |
test/test.cpp
|
jermp/mm_file
|
ed6dbb828d7ed85128241ef6693bf383d7f7cb2d
|
[
"MIT"
] | 1
|
2020-10-30T19:35:30.000Z
|
2020-10-30T19:35:30.000Z
|
#include <iostream>
#include "../include/mm_file/mm_file.hpp"
int main() {
std::string filename("./tmp.bin");
static const size_t n = 13;
{
// write n uint32_t integers
mm::file_sink<uint32_t> fout(filename, n);
std::cout << "mapped " << fout.bytes() << " bytes "
<< "for " << fout.size() << " integers" << std::endl;
auto* data = fout.data();
for (uint32_t i = 0; i != fout.size(); ++i) {
data[i] = i;
std::cout << "written " << data[i] << std::endl;
}
// test iterator
for (auto x : fout) {
std::cout << "written " << x << std::endl;
}
fout.close();
}
{
// instruct the kernel that we will read the content
// of the file sequentially
int advice = mm::advice::sequential;
// read the stream as uint16_t integers
mm::file_source<uint16_t> fin1(filename, advice);
std::cout << "mapped " << fin1.bytes() << " bytes "
<< "for " << fin1.size() << " integers" << std::endl;
auto const* data = fin1.data();
for (uint32_t i = 0; i != fin1.size(); ++i) {
std::cout << "read " << data[i] << std::endl;
}
fin1.close();
// test iterator
mm::file_source<uint16_t> fin2;
fin2.open(filename, advice);
for (auto x : fin2) {
std::cout << "read " << x << std::endl;
}
fin2.close();
}
std::remove(filename.c_str());
return 0;
}
| 27.803571
| 71
| 0.478484
|
jermp
|
9de12943e1145ac83a5fd5b10b45272fb5dea7a9
| 3,716
|
cpp
|
C++
|
GVRf/Framework/framework/src/main/jni/objects/components/bone_jni.cpp
|
sidia-dev-team/GearVRf
|
d93d62d49e5fc5b55dc00a485db92ec8fe004db1
|
[
"Apache-2.0"
] | 474
|
2015-03-27T17:14:43.000Z
|
2022-03-30T23:10:38.000Z
|
GVRf/Framework/framework/src/main/jni/objects/components/bone_jni.cpp
|
sidia-dev-team/GearVRf
|
d93d62d49e5fc5b55dc00a485db92ec8fe004db1
|
[
"Apache-2.0"
] | 1,677
|
2015-03-28T02:00:21.000Z
|
2019-10-21T13:28:44.000Z
|
GVRf/Framework/framework/src/main/jni/objects/components/bone_jni.cpp
|
sidia-dev-team/GearVRf
|
d93d62d49e5fc5b55dc00a485db92ec8fe004db1
|
[
"Apache-2.0"
] | 260
|
2015-03-27T23:55:12.000Z
|
2022-03-18T03:46:41.000Z
|
/***************************************************************************
* JNI
***************************************************************************/
#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "objects/components/bone.h"
#include "util/gvr_jni.h"
namespace gvr {
extern "C" {
JNIEXPORT jlong JNICALL
Java_org_gearvrf_NativeBone_ctor(JNIEnv * env, jobject obj);
JNIEXPORT jlong JNICALL
Java_org_gearvrf_NativeBone_getComponentType(JNIEnv * env, jobject clz);
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_setName(JNIEnv * env, jobject clz, jlong ptr,
jstring name);
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_setOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr,
jfloatArray jOffsetMatrix);
JNIEXPORT jfloatArray JNICALL
Java_org_gearvrf_NativeBone_getOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr);
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_setFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr,
jfloatArray jOffsetMatrix);
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_getFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr, jobject jFloatBuffer);
} // extern "C"
JNIEXPORT jlong JNICALL
Java_org_gearvrf_NativeBone_ctor(JNIEnv * env, jobject clz) {
return reinterpret_cast<jlong>(new Bone());
}
JNIEXPORT jlong JNICALL
Java_org_gearvrf_NativeBone_getComponentType(JNIEnv * env, jobject clz) {
return Bone::getComponentType();
}
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_setName(JNIEnv * env, jobject clz, jlong ptr,
jstring name) {
Bone* bone = reinterpret_cast<Bone*>(ptr);
if (!name || !env->GetStringLength(name)) {
bone->setName("");
return;
}
const char* charName = env->GetStringUTFChars(name, NULL);
bone->setName(charName);
env->ReleaseStringUTFChars(name, charName);
}
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_setOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr,
jfloatArray jOffsetMatrix) {
Bone* bone = reinterpret_cast<Bone*>(ptr);
if (!jOffsetMatrix)
return;
jfloat* mat_arr = env->GetFloatArrayElements(jOffsetMatrix, JNI_FALSE);
glm::mat4 matrix = glm::make_mat4x4(mat_arr);
bone->setOffsetMatrix(matrix);
env->ReleaseFloatArrayElements(jOffsetMatrix, mat_arr, JNI_ABORT);
}
JNIEXPORT jfloatArray JNICALL
Java_org_gearvrf_NativeBone_getOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr) {
Bone* bone = reinterpret_cast<Bone*>(ptr);
glm::mat4 matrix;
if (bone) {
matrix = bone->getOffsetMatrix();
}
jsize size = sizeof(matrix) / sizeof(jfloat);
jfloatArray jmatrix = env->NewFloatArray(size);
env->SetFloatArrayRegion(jmatrix, 0, size, glm::value_ptr(matrix));
return jmatrix;
}
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_setFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr,
jfloatArray jTransform) {
Bone* bone = reinterpret_cast<Bone*>(ptr);
if (!jTransform)
return;
jfloat* mat_arr = env->GetFloatArrayElements(jTransform, JNI_FALSE);
glm::mat4 matrix(glm::make_mat4x4(mat_arr));
bone->setFinalTransformMatrix(matrix);
env->ReleaseFloatArrayElements(jTransform, mat_arr, JNI_ABORT);
}
JNIEXPORT void JNICALL
Java_org_gearvrf_NativeBone_getFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr, jobject buffer) {
Bone* bone = reinterpret_cast<Bone*>(ptr);
glm::mat4 matrix = bone->getFinalTransformMatrix();
float *ptrBuffer = static_cast<float*>(env->GetDirectBufferAddress(buffer));
std::memcpy(ptrBuffer, glm::value_ptr(matrix), sizeof matrix);
}
} // namespace gvr
| 31.760684
| 116
| 0.699139
|
sidia-dev-team
|
9de2b001e9267ff1935a2426223f12bf406b5efe
| 225
|
cpp
|
C++
|
Pack_plugins/Pack_tool/ToolsModel.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | 1
|
2019-12-25T13:36:01.000Z
|
2019-12-25T13:36:01.000Z
|
Pack_plugins/Pack_tool/ToolsModel.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | null | null | null |
Pack_plugins/Pack_tool/ToolsModel.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | 1
|
2020-08-05T14:05:15.000Z
|
2020-08-05T14:05:15.000Z
|
#include "ToolsModel.h"
#include <QDesktopServices>
#include <QUrl>
ToolsModel::ToolsModel(QObject *parent) : QObject(parent)
{
}
void ToolsModel::openUrl(const QString &url)
{
QDesktopServices::openUrl(QUrl(url));
}
| 16.071429
| 57
| 0.728889
|
GreatCong
|
9de6658e6542fb507a086f453e6e84eafe9c93fa
| 1,155
|
cpp
|
C++
|
c10/10.5.cpp
|
sarthak-gupta-sg/hello-world
|
324f321a5454964b35b8399884d8c99971bd3425
|
[
"Apache-2.0"
] | null | null | null |
c10/10.5.cpp
|
sarthak-gupta-sg/hello-world
|
324f321a5454964b35b8399884d8c99971bd3425
|
[
"Apache-2.0"
] | null | null | null |
c10/10.5.cpp
|
sarthak-gupta-sg/hello-world
|
324f321a5454964b35b8399884d8c99971bd3425
|
[
"Apache-2.0"
] | 1
|
2020-05-30T04:30:16.000Z
|
2020-05-30T04:30:16.000Z
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <cstring>
using namespace std;
int main()
{
vector<const char * > roster1 { "abc", "def", "ghi"};
list<const char * > roster2 { "abc", "def", "ghi"};
//list<const char * > roster2(roster1.cbegin(), roster1.cend());
bool result;
result = equal(roster1.cbegin(), roster1.cend(), roster2.cbegin());
cout << "Your result is: " << result << "\n";
std::cout << (void *) roster1[0] << std::endl;
std::cout << (void *) roster2.front() << std::endl;
char const * c1 = "abcdef";
char const * c2 = "abcdef";
cout << *c1 << "\n";
if(c1 == c2)
{
cout << (void *)c1 << " and " << (void *)c2 << " are equal\n" ;
}
else
{
cout << (void *)c1 << " and " << (void *)c2 << " are not equal" ;
}
cout << "On linux g++ they are equal. On Windows cl.exe they are unequal\n";
cout << "\nstrlen: " << strlen(c1) << " vs sizeof: " << sizeof(c1) << "\n";
char c3[] = "def";
cout << "\nstrlen: " << strlen(c3) << " vs sizeof: " << sizeof(c3) << "\n";
return 0;
}
| 26.25
| 80
| 0.505628
|
sarthak-gupta-sg
|
9de8a46824c704648359b5985afea7ee55d93062
| 14,883
|
cpp
|
C++
|
cpp/libs/Molecular/CLCFGO_lib.cpp
|
ProkopHapala/SimpleSimulationEngine
|
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
|
[
"MIT"
] | 26
|
2016-12-04T04:45:12.000Z
|
2022-03-24T09:39:28.000Z
|
cpp/libs/Molecular/CLCFGO_lib.cpp
|
ProkopHapala/SimpleSimulationEngine
|
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
|
[
"MIT"
] | null | null | null |
cpp/libs/Molecular/CLCFGO_lib.cpp
|
ProkopHapala/SimpleSimulationEngine
|
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
|
[
"MIT"
] | 2
|
2019-02-09T12:31:06.000Z
|
2019-04-28T02:24:50.000Z
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
#include <vector>
#include <unordered_map>
#include <string>
#include "fastmath.h"
#include "Vec3.h"
#include "Mat3.h"
//#include "VecN.h"
#include "testUtils.h"
#include "integration.h"
#include "AOIntegrals.h"
//#include "AOrotations.h"
Vec3d DEBUG_dQdp;
int DEBUG_iter = 0;
int DEBUG_log_iter = 0;
int i_DEBUG=0;
#include "Grid.h"
#include "GaussianBasis.h"
#include "CLCFGO.h"
#include "CLCFGO_tests.h"
#include "eFF.h"
// ============ Global Variables
CLCFGO solver;
std::unordered_map<std::string, double*> buffers;
std::unordered_map<std::string, int*> ibuffers;
extern "C"{
// ========= Grid initialization
void makeDefaultBuffers(){
// atoms (ions)
buffers["apos" ]= (double*)solver.apos ;
buffers["aforce"]= (double*)solver.aforce ;
//buffers["aQs" ]= solver.aQs ;
//buffers["aQsize"]= solver.aQsize ;
//buffers["aPsize"]= solver.aPsize ;
//buffers["aPcoef"]= solver.aPcoef ;
buffers["aPars"]= (double*)solver.aPars ;
ibuffers["atype"]= solver.atype ;
// orbitals
buffers["opos"]= (double*)solver.opos ;
buffers["odip"]= (double*)solver.odip ;
buffers["oEs" ]= solver.oEs ;
buffers["oQs" ]= solver.oQs ;
ibuffers["onq" ]= solver.onq ;
ibuffers["ospin"]= solver.ospin ;
// --- Wave-function components for each orbital
buffers["epos" ]= (double*)solver.epos ;
buffers["esize"]= solver.esize ;
buffers["ecoef"]= solver.ecoef ;
// --- Forces acting on wave-functions components
buffers["efpos" ]= (double*)solver.efpos ;
buffers["efsize"]= solver.efsize ;
buffers["efcoef"]= solver.efcoef ;
// --- Forces acting on wave-functions components
buffers["enfpos" ]= (double*)solver.enfpos ;
buffers["enfsize"]= solver.enfsize ;
buffers["enfcoef"]= solver.enfcoef ;
// --- Auxuliary electron density expansion basis functions
buffers["rhoP"]= (double*)solver.rhoP ;
buffers["rhoQ"]= solver.rhoQ ;
buffers["rhoS"]= solver.rhoS ;
// --- Forces acting on auxuliary density basis functions
buffers["rhofP"]= (double*)solver.rhofP ;
buffers["rhofQ"]= solver.rhofQ ;
buffers["rhofS"]= solver.rhofS ;
//buffers.insert( { "rhoEQ", solver.rhoEQ } );
}
bool loadFromFile( char const* filename ){
bool b = solver.loadFromFile( filename );
//solver.setDefaultValues();
makeDefaultBuffers();
return b;
}
void init( int natom_, int nOrb_, int perOrb_, int natypes_ ){
solver.realloc( natom_, nOrb_, perOrb_, natypes_ );
solver.setDefaultValues();
makeDefaultBuffers();
}
double evalFunc( double r, double s ){
double fr,fs;
return Gauss::Coulomb( r, s, fr, fs );
}
void evalFuncDerivs( int n, double* r, double* s, double* Es, double* Fs ){
double fr,fs;
for(int i=0; i<n; i++){
//return Gauss::Coulomb( r, s, fr, fs );
//Es[i] = erfx_e6( r[i], s[i], Fs[i] );
//Es[i] = CoulombGauss( r[i], s[i], Fs[i], fs, 1 );
//Es[i] = CoulombGauss( r[i], s[i], fr, Fs[i], 1 );
//solver.esize[0] = s[i]; Es[i] = solver.eval(); Fs[i]=solver.efsize[0];
//Es[i] = erfx_e6( r[i], 1/s[i], Fs[i] ); Fs[i]*=-1;
double fs,fr; Es[i]=Gauss::Coulomb( r[i], s[i],fr,fs ); Fs[i]=-fr*r[i];
}
}
double eval(){ return solver.eval(); };
double coulombOrbPair( int io, int jo ){ solver.clearAuxDens(); return solver.CoulombOrbPair( io, jo ); }
double projectOrb( int io, bool bNormalize ){
solver.bNormalize=bNormalize;
solver.bNormForce=true; solver.bNormForce=true;
if(bNormalize)solver.normalizeOrb(io);
Vec3d dip;
solver.cleanForces();
return solver.projectOrb(io, dip);
}
double* getEnergyPointer(){ return &solver.Ek; }
int* getDimPointer (){ return &solver.natypes; }
void printSetup (){ solver.printSetup(); }
void printAtomsAndElectrons(){ solver.printAtoms(); solver.printElectrons(); }
/*
int* getTypes (){ return (int*) ff.types; }
double* getPoss (){ return (double*)ff.poss; }
double* getQrots (){ return (double*)ff.qrots; }
double* getHbonds(){ return (double*)ff.hbonds; }
double* getEbonds(){ return (double*)ff.ebonds; }
double* getBondCaps(){ return (double*)ff.bondCaps; }
*/
double* getBuff(const char* name){
auto got = buffers.find( name );
if( got==buffers.end() ){ return 0; }
else { return got->second; }
}
void setBuff(const char* name, double* buff){
buffers[name] = buff;
//auto got = buffers.find( name );
//if( got==buffers.end() ){ return null; }
//else { return got->second; }
}
int* getIBuff(const char* name){
auto got = ibuffers.find( name );
if( got == ibuffers.end() ){ return 0; }
else { return got->second; }
}
void setIBuff(const char* name, int* buff){
ibuffers[name] = buff;
//auto got = buffers.find( name );
//if( got==buffers.end() ){ return null; }
//else { return got->second; }
}
void atomsPotAtPoints( int n, double* ps, double* out, double s, double Q ){ solver.atomsPotAtPoints( n, (Vec3d*)ps, out, s, Q ); };
void orbAtPoints ( int io, int n, double* ps, double* out ){ solver.orbAtPoints ( io, n, (Vec3d*)ps, out ); };
void rhoAtPoints ( int io, int n, double* ps, double* out ){ solver.rhoAtPoints ( io, n, (Vec3d*)ps, out ); };
void hartreeAtPoints ( int io, int n, double* ps, double* out ){ solver.hartreeAtPoints ( io, n, (Vec3d*)ps, out ); };
double test_Poisson( int io, double Rmax, double gStep, double * line_rho, double* line_rho_, bool bPrint, bool bSave, bool useWf ){
return test_Poisson( solver, io, Rmax, gStep, line_rho, line_rho_, bPrint, bSave, useWf );
}
double test_OrbInteraction( int iMODE, int io, int jo, int nint, double dx, double Rmax, double gStep, double * line_Ek, double* line_Ek_g, double * line_f1, double* line_f2, int bPrint, bool bSave ){
return test_OrbInteraction( solver, iMODE, io, jo, nint, dx, Rmax, gStep, line_Ek, line_Ek_g, line_f1, line_f2, bPrint, bSave );
}
void test_GaussIntegral_ST( int iMODE, int n, double sj, double* sis, double* rs, double* E, double* fr, double* fs ){
for(int i=0; i<n; i++){
double si = sis[i];
double r_ = rs [i];
double r2 = r_*r_;
_Gauss_sij_aux( si, sj )
if ( iMODE==1 ){
_Gauss_overlap( r2, si, sj );
E[i]=S; fr[i]=dS_dr*r_; fs[i]=dS_dsi;
}else if ( iMODE==2 ) {
_Gauss_tau ( r2, si, sj );
E[i]=tau; fr[i]=dTau_dr*r_; fs[i]=dTau_dsi;
}else if ( iMODE==3 ) {
_Gauss_overlap( r2, si, sj );
_Gauss_tau ( r2, si, sj );
_Gauss_kinetic( r2, si, sj );
E[i]=T; fr[i]=dT_dr*r_; fs[i]=dT_dsi;
}
}
}
#define NEWBUFF(name,N) double* name = new double[N]; buffers.insert( {#name, name} );
void testDerivsP_Coulomb_model( int n, double x0, double dx ){
//initTestElectrons( );
for(int i=0; i<solver.nBas; i++){ printf( "epos[%i] (%g,%g,%g) \n", i, solver.epos[i].x,solver.epos[i].y,solver.epos[i].z); }
solver.toRho(0,1, 0);
solver.toRho(2,3, 1);
NEWBUFF(l_xs,n)
NEWBUFF(l_Q,n)
NEWBUFF(l_dQ_ana,n)
NEWBUFF(l_dQ_num,n)
NEWBUFF(l_r,n)
NEWBUFF(l_E,n)
NEWBUFF(l_Fana,n)
NEWBUFF(l_Fnum,n)
solver.bEvalKinetic = false;
for(int i=0; i<n; i++){
DEBUG_iter=i;
solver.cleanForces();
double x = x0 + i*dx;
l_xs[i] = x;
solver.epos[0].x=x;
solver.toRho (0,1, 0); // w0*w1 -> q0
solver.toRho (2,3, 1); // w2*w3 -> q1
double E_ = solver.CoublombElement(0,1); // E = C( q0, q1 )
double E = E_ * solver.rhoQ[0] * solver.rhoQ[1]; // E(q0,q1) * q0 * q1
solver.fromRho( 0,1, 0 ); // w0,w1 <- q0
l_Q [i] = solver.rhoQ[0];
l_dQ_ana[i] = DEBUG_dQdp.x;
if(i>1) l_dQ_num[i-1] = (l_Q[i] - l_Q[i-2])/(2*dx);
l_r[i] = (solver.rhoP[0] - solver.rhoP[1]).norm();
l_Fana[i] = solver.efpos[0].x; // This is used when fromRho() is modified
l_E[i] = E; //func( line_E->xs[i], line_Fana->ys[i] );
if(i>1) l_Fnum[i-1] = (l_E[i] - l_E[i-2])/(2*dx);
}
//double* buff = buffers["l_xs"];
//for(int i=0; i<n; i++){ printf("%i : %g \n", i, buff[i]); }
}
void testDerivsS_Coulomb_model( int n, double x0, double dx ){
//initTestElectrons( );
for(int i=0; i<solver.nBas; i++){ printf( "epos[%i] (%g,%g,%g) \n", i, solver.epos[i].x,solver.epos[i].y,solver.epos[i].z); }
solver.toRho(0,1, 0);
solver.toRho(2,3, 1);
NEWBUFF(l_xs,n)
NEWBUFF(l_Q,n)
NEWBUFF(l_dQ_ana,n)
NEWBUFF(l_dQ_num,n)
NEWBUFF(l_r,n)
NEWBUFF(l_E,n)
NEWBUFF(l_Fana,n)
NEWBUFF(l_Fnum,n)
solver.bEvalKinetic = false;
for(int i=0; i<n; i++){
DEBUG_iter=i;
//printf("testDerivsS_Coulomb_model[%i] \n", i );
solver.cleanForces();
double x = x0 + i*dx;
l_xs[i] = x;
solver.esize[0]=x;
solver.toRho (0,1, 0); // w0*w1 -> q0
solver.toRho (2,3, 1); // w2*w3 -> q1
double E_ = solver.CoublombElement(0,1); // E = C( q0, q1 )
double E = E_ * solver.rhoQ[0] * solver.rhoQ[1]; // E(q0,q1) * q0 * q1
solver.fromRho( 0,1, 0 ); // w0,w1 <- q0
l_Q [i] = solver.rhoQ[0];
l_dQ_ana[i] = DEBUG_dQdp.x;
if(i>1) l_dQ_num[i-1] = (l_Q[i] - l_Q[i-2])/(2*dx);
l_r[i] = (solver.rhoP[0] - solver.rhoP[1]).norm();
l_Fana[i] = solver.efsize[0]; // This is used when fromRho() is modified
l_E[i] = E; //func( line_E->xs[i], line_Fana->ys[i] );
if(i>1) l_Fnum[i-1] = (l_E[i] - l_E[i-2])/(2*dx);
//return;
}
//double* buff = buffers["l_xs"];
//for(int i=0; i<n; i++){ printf("%i : %g \n", i, buff[i]); }
}
void testDerivsP_Total( int n, double x0, double dx ){
for(int i=0; i<solver.nBas; i++){ printf( "epos[%i] (%g,%g,%g) s %g c %g \n", i, solver.epos[i].x,solver.epos[i].y,solver.epos[i].z, solver.esize[i], solver.ecoef[i] ); }
//NEWBUFF(l_r,n)
NEWBUFF(l_xs,n)
NEWBUFF(l_Q,n)
NEWBUFF(l_E,n)
NEWBUFF(l_Fana,n)
NEWBUFF(l_Fnum,n)
solver.bEvalKinetic = false;
for(int i=0; i<n; i++){
DEBUG_iter=i;
double x = x0 + i*dx;
l_xs[i] = x;
solver.epos[0].x=x;
//printf( ">>> testDerivs_Total [%i] \n", i );
solver.cleanForces();
//solver.projectOrb( 0, dip, false );
//solver.projectOrb( 1, dip, false );
//double E = solver.CoulombOrbPair( 0, 1 );
double E = solver.eval();
double xc = solver.rhoP[2].x; //line_Qc->ys[i] = xc;
l_Fana[i]= solver.efpos[0].x;
l_E[i] = E;
l_Q[i] = solver.oQs[0];
//printf( "<<< testDerivs_Total i[%i] x %g E %g \n", i, x, E );
if(i>1)l_Fnum[i-1] = (l_E[i] - l_E[i-2])/(2*dx);
//return;
}
//for(int i=0;i<n;i++){ line_E->ys[i] -= line_E->ys[n-1]; };
}
void testDerivsS_Total( int n, double x0, double dx ){
for(int i=0; i<solver.nBas; i++){ printf( "epos[%i] (%g,%g,%g) s %g c %g \n", i, solver.epos[i].x,solver.epos[i].y,solver.epos[i].z, solver.esize[i], solver.ecoef[i] ); }
//NEWBUFF(l_r,n)
NEWBUFF(l_xs,n)
NEWBUFF(l_Q,n)
NEWBUFF(l_E,n)
NEWBUFF(l_Fana,n)
NEWBUFF(l_Fnum,n)
solver.bEvalKinetic = false;
for(int i=0; i<n; i++){
DEBUG_iter=i;
double x = x0 + i*dx;
l_xs[i] = x;
solver.esize[0]=x;
//printf( ">>> testDerivs_Total [%i] \n", i );
solver.cleanForces();
double E = solver.eval();
//double xc = solver.rhoP[2].x; //line_Qc->ys[i] = xc;
l_Fana[i]= solver.efsize[0];
//printf( "i %i x %g efsize[0] %g \n", i, x, solver.efsize[0] );
l_E[i] = E;
l_Q[i] = solver.oQs[0];
//printf( "<<< testDerivs_Total i[%i] x %g E %g \n", i, x, E );
if(i>1)l_Fnum[i-1] = (l_E[i] - l_E[i-2])/(2*dx);
//return;
}
//for(int i=0;i<n;i++){ line_E->ys[i] -= line_E->ys[n-1]; };
}
void testDerivsTotal( int n, double* xs, double* Es, double* Fs, int what ){
/*
solver.bNormalize = 0;
solver.bEvalKinetic = 0;
solver.bEvalCoulomb = 0;
solver.bEvalExchange = 0;
solver.bEvalPauli = 0;
solver.iPauliModel = 1;
solver.bEvalAA = 0;
solver.bEvalAE = 1;
solver.bEvalAECoulomb = 1;
solver.bEvalAEPauli = 0;
*/
return testDerivsTotal( solver, n, xs, Es, Fs, what );
}
void testDerivsCoulombModel( int n, double* xs, double* Es, double* Fs, int what ){
return testDerivsCoulombModel( solver, n, xs, Es, Fs, what );
}
void setSwitches(bool bNormalize, bool bEvalKinetic, bool bEvalCoulomb, bool bEvalExchange, bool bEvalPauli, int iPauliModel, bool bEvalAA, bool bEvalAE, bool bEvalAECoulomb, bool bEvalAEPauli ){
solver.bNormalize = bNormalize;
solver.bEvalKinetic = bEvalKinetic;
solver.bEvalCoulomb = bEvalCoulomb;
solver.bEvalExchange = bEvalExchange;
solver.bEvalPauli = bEvalPauli;
solver.iPauliModel = iPauliModel;
solver.bEvalAA = bEvalAA;
solver.bEvalAE = bEvalAE;
solver.bEvalAECoulomb = bEvalAECoulomb;
solver.bEvalAEPauli = bEvalAEPauli;
}
void setSwitches_(int bNormalize, int bNormForce, int bEvalKinetic, int bEvalCoulomb, int bEvalExchange, int bEvalPauli, int bEvalAA, int bEvalAE, int bEvalAECoulomb, int bEvalAEPauli ){
//printf( "\n\n\n\n#### setSwitches_ bEvalAEPauli %i \n", bEvalAEPauli );
#define _setbool(b,i) { if(i>0){b=true;}else if(i<0){b=false;} }
_setbool( solver.bNormalize , bNormalize );
_setbool( solver.bNormForce , bNormForce );
_setbool( solver.bEvalKinetic , bEvalKinetic );
_setbool( solver.bEvalCoulomb , bEvalCoulomb );
_setbool( solver.bEvalExchange , bEvalExchange );
_setbool( solver.bEvalPauli , bEvalPauli );
_setbool( solver.bEvalAA , bEvalAA );
_setbool( solver.bEvalAE , bEvalAE );
_setbool( solver.bEvalAECoulomb , bEvalAECoulomb );
_setbool( solver.bEvalAEPauli , bEvalAEPauli );
#undef _setbool
}
void setPauliMode( int iPauli ){ solver.iPauliModel = iPauli; }
} // extern "C"
| 37.678481
| 201
| 0.563932
|
ProkopHapala
|
9ded4c0e6c98c96d1dc7e14a4ca4d784bf9d9ba4
| 13,759
|
cpp
|
C++
|
common/operations/Softmax.cpp
|
riscv-android-src/platform-packages-modules-NeuralNetworks
|
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
|
[
"Apache-2.0"
] | null | null | null |
common/operations/Softmax.cpp
|
riscv-android-src/platform-packages-modules-NeuralNetworks
|
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
|
[
"Apache-2.0"
] | null | null | null |
common/operations/Softmax.cpp
|
riscv-android-src/platform-packages-modules-NeuralNetworks
|
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2019 The Android Open Source 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.
*/
#define LOG_TAG "Operations"
#include "Softmax.h"
#include <algorithm>
#include <cfloat>
#include <limits>
#include <vector>
#include "OperationResolver.h"
#include "Tracing.h"
#include "nnapi/Validation.h"
#ifdef NN_INCLUDE_CPU_IMPLEMENTATION
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wsign-compare"
#pragma clang diagnostic ignored "-Winvalid-partial-specialization"
#include <tensorflow/lite/kernels/internal/optimized/legacy_optimized_ops.h>
#include <tensorflow/lite/kernels/internal/optimized/optimized_ops.h>
#pragma clang diagnostic pop
#include "CpuOperationUtils.h"
#endif // NN_INCLUDE_CPU_IMPLEMENTATION
namespace android {
namespace nn {
namespace softmax {
#ifdef NN_INCLUDE_CPU_IMPLEMENTATION
namespace {
inline bool softmaxSlowFloat32(const float* inputData, const Shape& inputShape, const float beta,
int32_t axis, float* outputData, const Shape& /*outputShape*/) {
NNTRACE_TRANS("softmaxFloatSlow32");
const uint32_t outerSize = getNumberOfElements(inputShape, 0, axis);
const uint32_t axisSize = getSizeOfDimension(inputShape, axis);
const uint32_t innerSize =
getNumberOfElements(inputShape, axis + 1, getNumberOfDimensions(inputShape));
for (uint32_t outer = 0; outer < outerSize; ++outer) {
const float* inputBeg = inputData + outer * axisSize * innerSize;
const float* inputEnd = inputBeg + axisSize * innerSize;
float* outputBeg = outputData + outer * axisSize * innerSize;
for (uint32_t inner = 0; inner < innerSize; ++inner, ++inputBeg, ++inputEnd, ++outputBeg) {
// Find max
float maxValue = -FLT_MAX;
for (const float* p = inputBeg; p < inputEnd; p += innerSize) {
maxValue = std::max(maxValue, *p);
}
// Compute sum
float sum = 0.0f;
for (const float* p = inputBeg; p < inputEnd; p += innerSize) {
sum += std::exp((*p - maxValue) * beta);
}
// Compute result
float* pOut = outputBeg;
for (const float* p = inputBeg; p < inputEnd; p += innerSize, pOut += innerSize) {
*pOut = std::exp((*p - maxValue) * beta) / sum;
}
}
}
return true;
}
bool softmaxFloat32(const float* inputData, const Shape& inputShape, const float beta, int32_t axis,
float* outputData, const Shape& outputShape) {
int32_t ndim = getNumberOfDimensions(inputShape);
NN_CHECK(handleNegativeAxis(inputShape, &axis));
// TFLite optimized implementation only supports computation along the last axis
if (axis == ndim - 1) {
NNTRACE_COMP("optimized_ops::Softmax::float");
tflite::SoftmaxParams param = {.beta = beta};
tflite::optimized_ops::Softmax(param, convertShapeToTflshape(inputShape), inputData,
convertShapeToTflshape(outputShape), outputData);
return true;
} else {
return softmaxSlowFloat32(inputData, inputShape, beta, axis, outputData, outputShape);
}
}
bool softmaxFloat16(const _Float16* inputData, const Shape& inputShape, const float beta,
int32_t axis, _Float16* outputData, const Shape& outputShape) {
NNTRACE_TRANS("softmaxFloat16");
std::vector<float> inputData_float32(getNumberOfElements(inputShape));
convertFloat16ToFloat32(inputData, &inputData_float32);
std::vector<float> outputData_float32(getNumberOfElements(outputShape));
softmaxFloat32(inputData_float32.data(), inputShape, beta, axis, outputData_float32.data(),
outputShape);
convertFloat32ToFloat16(outputData_float32, outputData);
return true;
}
template <typename T>
bool softmaxQuant8Impl(const T* inputData, const Shape& inputShape, const float /*beta*/,
int32_t axis, int32_t inputMultiplier, int32_t inputLeftShift, float diffMin,
T* outputData, const Shape& /*outputShape*/) {
NNTRACE_TRANS("softmaxQuant8");
// The representation chosen for the input to the exp() function is Q5.26.
// We need to leave extra space since values that we skip might be as large as
// -32 before multiplying by input_beta_multiplier, and therefore as large as
// -16 afterwards. Note that exp(-8) is definitely not insignificant to
// accumulation, but exp(-16) definitely is.
static const int32_t kScaledDiffIntegerBits = 5;
static const int kAccumulationIntegerBits = 12;
using FixedPointScaledDiff = gemmlowp::FixedPoint<int32_t, kScaledDiffIntegerBits>;
using FixedPointAccum = gemmlowp::FixedPoint<int32_t, kAccumulationIntegerBits>;
using FixedPoint0 = gemmlowp::FixedPoint<int32_t, 0>;
const uint32_t outerSize = getNumberOfElements(inputShape, 0, axis);
const uint32_t axisSize = getSizeOfDimension(inputShape, axis);
const uint32_t innerSize =
getNumberOfElements(inputShape, axis + 1, getNumberOfDimensions(inputShape));
for (uint32_t outer = 0; outer < outerSize; ++outer) {
const T* inputBeg = inputData + outer * axisSize * innerSize;
const T* inputEnd = inputBeg + axisSize * innerSize;
T* outputBeg = outputData + outer * axisSize * innerSize;
for (uint32_t inner = 0; inner < innerSize; ++inner, ++inputBeg, ++inputEnd, ++outputBeg) {
// Find max
T maxValue = std::is_same_v<T, int8_t> ? -128 : 0;
for (const T* p = inputBeg; p < inputEnd; p += innerSize) {
maxValue = std::max(maxValue, *p);
}
// Compute sum
FixedPointAccum sum_of_exps = FixedPointAccum::Zero();
for (const T* p = inputBeg; p < inputEnd; p += innerSize) {
int32_t input_diff = static_cast<int32_t>(*p) - maxValue;
if (input_diff >= diffMin) {
const int32_t input_diff_rescaled =
tflite::MultiplyByQuantizedMultiplierGreaterThanOne(
input_diff, inputMultiplier, inputLeftShift);
const auto scaled_diff_f8 = FixedPointScaledDiff::FromRaw(input_diff_rescaled);
sum_of_exps = sum_of_exps + gemmlowp::Rescale<kAccumulationIntegerBits>(
exp_on_negative_values(scaled_diff_f8));
}
}
uint32_t fixed_sum_of_exps = static_cast<uint32_t>(sum_of_exps.raw());
int32_t headroom_plus_one = tflite::CountLeadingZeros(fixed_sum_of_exps);
// This is the number of bits to the left of the binary point above 1.0.
// Consider fixed_sum_of_exps=1.25. In that case shifted_scale=0.8 and
// no later adjustment will be needed.
int32_t num_bits_over_unit = kAccumulationIntegerBits - headroom_plus_one;
int32_t shifted_sum_minus_one = static_cast<int32_t>(
(fixed_sum_of_exps << headroom_plus_one) - (static_cast<uint32_t>(1) << 31));
FixedPoint0 shifted_scale = gemmlowp::one_over_one_plus_x_for_x_in_0_1(
FixedPoint0::FromRaw(shifted_sum_minus_one));
// Compute result
constexpr int32_t q_min = std::numeric_limits<T>::min();
constexpr int32_t q_max = std::numeric_limits<T>::max();
T* pOut = outputBeg;
for (const T* p = inputBeg; p < inputEnd; p += innerSize, pOut += innerSize) {
int32_t input_diff = static_cast<int32_t>(*p) - maxValue;
if (input_diff >= diffMin) {
const int32_t input_diff_rescaled =
tflite::MultiplyByQuantizedMultiplierGreaterThanOne(
input_diff, inputMultiplier, inputLeftShift);
const auto scaled_diff_f8 = FixedPointScaledDiff::FromRaw(input_diff_rescaled);
FixedPoint0 exp_in_0 = exp_on_negative_values(scaled_diff_f8);
int32_t unsat_output = gemmlowp::RoundingDivideByPOT(
(shifted_scale * exp_in_0).raw(), num_bits_over_unit + 31 - 8);
if (std::is_same_v<T, int8_t>) {
unsat_output -= 128;
}
*pOut = static_cast<T>(std::max(std::min(unsat_output, q_max), q_min));
} else {
*pOut = std::is_same_v<T, int8_t> ? -128 : 0;
}
}
}
}
return true;
}
template <typename T>
bool softmaxQuant8(const T* inputData, const Shape& inputShape, const float beta, int32_t axis,
T* outputData, const Shape& outputShape) {
[[maybe_unused]] int32_t ndim = getNumberOfDimensions(inputShape);
NN_CHECK(handleNegativeAxis(inputShape, &axis));
if ((inputShape.type == OperandType::TENSOR_QUANT8_ASYMM && outputShape.offset != 0) ||
(inputShape.type == OperandType::TENSOR_QUANT8_ASYMM_SIGNED &&
outputShape.offset != -128) ||
outputShape.scale != 1.f / 256) {
LOG(ERROR) << "incorrect scale / offset for output";
return false;
}
static const int32_t kScaledDiffIntegerBits = 5;
const double input_beta_real_multiplier =
std::min(1.0 * beta * inputShape.scale * (1 << (31 - kScaledDiffIntegerBits)),
(1LL << 31) - 1.0);
int32_t inputMultiplier = 0, inputLeftShift = 0;
if (!QuantizeMultiplierGreaterThanOne(input_beta_real_multiplier, &inputMultiplier,
&inputLeftShift)) {
return false;
}
int32_t diffMin = -CalculateInputRadius(kScaledDiffIntegerBits, inputLeftShift);
return softmaxQuant8Impl(inputData, inputShape, beta, axis, inputMultiplier, inputLeftShift,
diffMin, outputData, outputShape);
}
} // namespace
bool prepare(IOperationExecutionContext* context) {
Shape input = context->getInputShape(kInputTensor);
float beta = (input.type == OperandType::TENSOR_FLOAT16)
? context->getInputValue<_Float16>(kBetaScalar)
: context->getInputValue<float>(kBetaScalar);
NN_RET_CHECK_LE(getNumberOfDimensions(input), 4u);
NN_RET_CHECK_GT(beta, 0.0f);
Shape output = context->getOutputShape(kOutputTensor);
output.dimensions = input.dimensions;
return context->setOutputShape(kOutputTensor, output);
}
bool execute(IOperationExecutionContext* context) {
// Bypass execution in the case of zero-sized input.
if (getNumberOfElements(context->getOutputShape(kOutputTensor)) == 0) return true;
int32_t axis = (context->getNumInputs() == kNumInputs)
? context->getInputValue<int32_t>(kAxisScalar)
: -1;
switch (context->getInputType(kInputTensor)) {
case OperandType::TENSOR_FLOAT16:
return softmaxFloat16(context->getInputBuffer<_Float16>(kInputTensor),
context->getInputShape(kInputTensor),
context->getInputValue<_Float16>(kBetaScalar), axis,
context->getOutputBuffer<_Float16>(kOutputTensor),
context->getOutputShape(kOutputTensor));
case OperandType::TENSOR_FLOAT32:
return softmaxFloat32(context->getInputBuffer<float>(kInputTensor),
context->getInputShape(kInputTensor),
context->getInputValue<float>(kBetaScalar), axis,
context->getOutputBuffer<float>(kOutputTensor),
context->getOutputShape(kOutputTensor));
case OperandType::TENSOR_QUANT8_ASYMM:
return softmaxQuant8(context->getInputBuffer<uint8_t>(kInputTensor),
context->getInputShape(kInputTensor),
context->getInputValue<float>(kBetaScalar), axis,
context->getOutputBuffer<uint8_t>(kOutputTensor),
context->getOutputShape(kOutputTensor));
case OperandType::TENSOR_QUANT8_ASYMM_SIGNED:
return softmaxQuant8(context->getInputBuffer<int8_t>(kInputTensor),
context->getInputShape(kInputTensor),
context->getInputValue<float>(kBetaScalar), axis,
context->getOutputBuffer<int8_t>(kOutputTensor),
context->getOutputShape(kOutputTensor));
default:
NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
}
}
#endif // NN_INCLUDE_CPU_IMPLEMENTATION
} // namespace softmax
NN_REGISTER_OPERATION(SOFTMAX, "SOFTMAX", softmax::validate, softmax::prepare, softmax::execute,
.allowZeroSizedInput = true);
} // namespace nn
} // namespace android
| 47.940767
| 100
| 0.630714
|
riscv-android-src
|
9df3b13073598a0ef2116e9567a8618ec28c1ba2
| 1,341
|
cpp
|
C++
|
meta_struct_20/cppcon_version/meta_struct_1.cpp
|
google/cpp-from-the-sky-down
|
10c8d16e877796f2906bedbd3a66fb6469b3a211
|
[
"Apache-2.0"
] | 219
|
2018-08-15T22:01:07.000Z
|
2022-03-23T11:46:54.000Z
|
meta_struct_20/cppcon_version/meta_struct_1.cpp
|
google/cpp-from-the-sky-down
|
10c8d16e877796f2906bedbd3a66fb6469b3a211
|
[
"Apache-2.0"
] | 5
|
2018-09-11T06:15:28.000Z
|
2022-01-05T15:27:31.000Z
|
meta_struct_20/cppcon_version/meta_struct_1.cpp
|
google/cpp-from-the-sky-down
|
10c8d16e877796f2906bedbd3a66fb6469b3a211
|
[
"Apache-2.0"
] | 27
|
2018-09-11T06:14:40.000Z
|
2022-03-20T09:46:14.000Z
|
#include <algorithm>
#include <cstddef>
template <std::size_t N>
struct fixed_string {
constexpr fixed_string(const char (&foo)[N + 1]) {
std::copy_n(foo, N + 1, data);
}
auto operator<=>(const fixed_string&) const = default;
char data[N + 1] = {};
};
template <std::size_t N>
fixed_string(const char (&str)[N]) -> fixed_string<N - 1>;
template <fixed_string Tag, typename T>
struct member {
constexpr static auto tag() { return Tag; }
using element_type = T;
T value;
};
template <typename... Members>
struct meta_struct : Members... {};
template<fixed_string tag, typename T>
decltype(auto) get_impl(member<tag, T>& m) {
return (m.value);
}
template<fixed_string tag, typename T>
decltype(auto) get_impl(const member<tag, T>& m) {
return (m.value);
}
template<fixed_string tag, typename T>
decltype(auto) get_impl(member<tag, T>&& m) {
return std::move(m.value);
}
template<fixed_string tag, typename MetaStruct>
decltype(auto) get(MetaStruct&& s) {
return get_impl<tag>(std::forward<MetaStruct>(s));
}
#include <iostream>
#include <string>
int main() {
using Person = meta_struct< //
member<"id", int>, //
member<"name", std::string> //
>;
Person p;
get<"id">(p) = 1;
get<"name">(p) = "John";
std::cout << get<"id">(p) << " " << get<"name">(p) << "\n";
}
| 21.629032
| 61
| 0.633855
|
google
|
9df4a23e4e574681f332fe213b1e6627818591cd
| 1,815
|
cc
|
C++
|
algorithms/background/glm/boost_python/ext.cc
|
TiankunZhou/dials
|
bd5c95b73c442cceb1c61b1690fd4562acf4e337
|
[
"BSD-3-Clause"
] | 58
|
2015-10-15T09:28:20.000Z
|
2022-03-28T20:09:38.000Z
|
algorithms/background/glm/boost_python/ext.cc
|
TiankunZhou/dials
|
bd5c95b73c442cceb1c61b1690fd4562acf4e337
|
[
"BSD-3-Clause"
] | 1,741
|
2015-11-24T08:17:02.000Z
|
2022-03-31T15:46:42.000Z
|
algorithms/background/glm/boost_python/ext.cc
|
TiankunZhou/dials
|
bd5c95b73c442cceb1c61b1690fd4562acf4e337
|
[
"BSD-3-Clause"
] | 45
|
2015-10-14T13:44:16.000Z
|
2022-03-22T14:45:56.000Z
|
/*
* ext.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/background/glm/robust_poisson_mean.h>
#include <dials/algorithms/background/glm/creator.h>
namespace dials { namespace algorithms { namespace background { namespace boost_python {
using namespace boost::python;
BOOST_PYTHON_MODULE(dials_algorithms_background_glm_ext) {
class_<RobustPoissonMean>("RobustPoissonMean", no_init)
.def(init<const af::const_ref<double>&, double, double, double, std::size_t>(
(arg("Y"),
arg("mean0"),
arg("c") = 1.345,
arg("tolerance") = 1e-3,
arg("max_iter") = 100)))
.def("mean", &RobustPoissonMean::mean)
.def("niter", &RobustPoissonMean::niter)
.def("error", &RobustPoissonMean::error)
.def("converged", &RobustPoissonMean::converged);
class_<GLMBackgroundCreator> creator("Creator", no_init);
creator
.def(init<GLMBackgroundCreator::Model, double, std::size_t, std::size_t>((
arg("model"), arg("tuning_constant"), arg("max_iter"), arg("min_pixels") = 10)))
.def("__call__", &GLMBackgroundCreator::shoebox)
.def("__call__", &GLMBackgroundCreator::volume);
scope in_creator = creator;
enum_<GLMBackgroundCreator::Model>("model")
.value("constant2d", GLMBackgroundCreator::Constant2d)
.value("constant3d", GLMBackgroundCreator::Constant3d)
.value("loglinear2d", GLMBackgroundCreator::LogLinear2d)
.value("loglinear3d", GLMBackgroundCreator::LogLinear3d);
}
}}}} // namespace dials::algorithms::background::boost_python
| 36.3
| 88
| 0.686501
|
TiankunZhou
|
9df5a52a4836c72b14bdce9701b3cab75024ea52
| 955
|
hpp
|
C++
|
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/depth/visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/depth/visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/depth/visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_STATE_CORE_DEPTH_STENCIL_DEPTH_VISITOR_HPP_INCLUDED
#define SGE_D3D9_STATE_CORE_DEPTH_STENCIL_DEPTH_VISITOR_HPP_INCLUDED
#include <sge/d3d9/state/render_vector.hpp>
#include <sge/renderer/state/core/depth_stencil/depth/enabled_fwd.hpp>
#include <sge/renderer/state/core/depth_stencil/depth/off_fwd.hpp>
namespace sge
{
namespace d3d9
{
namespace state
{
namespace core
{
namespace depth_stencil
{
namespace depth
{
class visitor
{
public:
typedef sge::d3d9::state::render_vector result_type;
result_type operator()(sge::renderer::state::core::depth_stencil::depth::off const &) const;
result_type operator()(sge::renderer::state::core::depth_stencil::depth::enabled const &) const;
};
}
}
}
}
}
}
#endif
| 21.704545
| 98
| 0.762304
|
cpreh
|
9dfe69429c5cf404fde62bcfe39ee68802b20349
| 1,064
|
hpp
|
C++
|
Embedded/terranova_sketch/ImuSensor.hpp
|
dhawkes36/TerraNova
|
8fc460d5f221370c8f0b84851c72432dea148b4e
|
[
"MIT"
] | null | null | null |
Embedded/terranova_sketch/ImuSensor.hpp
|
dhawkes36/TerraNova
|
8fc460d5f221370c8f0b84851c72432dea148b4e
|
[
"MIT"
] | null | null | null |
Embedded/terranova_sketch/ImuSensor.hpp
|
dhawkes36/TerraNova
|
8fc460d5f221370c8f0b84851c72432dea148b4e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Arduino.h>
#include <Wire.h>
#include <math.h>
#include "SparkFunLSM9DS1.h"
#define LSM9DS1_M 0x1E // Would be 0x1C if SDO_M is LOW
#define LSM9DS1_AG 0x6B // Would be 0x6A if SDO_AG is LOW
// Earth's magnetic field varies by location. Add or subtract
// a declination to get a more accurate heading. Calculate
// your's here:
// http://www.ngdc.noaa.gov/geomag-web/#declination
#define DECLINATION 12
struct ImuData
{
float gyro_x = NAN;
float gyro_y = NAN;
float gyro_z = NAN;
float accel_x = NAN;
float accel_y = NAN;
float accel_z = NAN;
float mag_x = NAN;
float mag_y = NAN;
float mag_z = NAN;
float pitch = NAN;
float roll = NAN;
float heading = NAN;
};
class ImuSensor
{
public:
ImuSensor():imu_(new LSM9DS1()){};
~ImuSensor(){delete imu_;};
bool init();
ImuData getData();
private:
LSM9DS1 *imu_;
float pitch_;
float roll_;
float heading_;
void calculateAttitude(const float &ax, const float &ay, const float &az, float mx, float my, float mz);
};
| 19.703704
| 108
| 0.668233
|
dhawkes36
|
3b00e634808c129e66563ab75eb49086a83d0a3d
| 2,856
|
cpp
|
C++
|
WitchEngine3/src/WE3/mesh/WEMeshInstance.cpp
|
jadnohra/World-Of-Football
|
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
|
[
"MIT"
] | 3
|
2018-12-02T14:09:22.000Z
|
2021-11-22T07:14:05.000Z
|
WitchEngine3/src/WE3/mesh/WEMeshInstance.cpp
|
jadnohra/World-Of-Football
|
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
|
[
"MIT"
] | 1
|
2018-12-03T22:54:38.000Z
|
2018-12-03T22:54:38.000Z
|
WitchEngine3/src/WE3/mesh/WEMeshInstance.cpp
|
jadnohra/World-Of-Football
|
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
|
[
"MIT"
] | 2
|
2020-09-22T21:04:14.000Z
|
2021-05-24T09:43:28.000Z
|
#include "WEMeshInstance.h"
namespace WE {
bool MeshInstance::init(Mesh& mesh, RenderLoadContext& renderLoadContext) {
return mesh.initInstance(*this, renderLoadContext);
}
bool MeshInstance::isInited() {
return mMesh.isValid();
}
/*
bool MeshInstance::hasSkeletonInstance() {
return mSkelInst.isValid();
}
*/
Mesh* MeshInstance::getMesh() {
return mMesh.ptr();
}
void MeshInstance::cloneTo(MeshInstance& clone, bool cloneMaterial) {
clone.mMesh = mMesh.ptr();
if (cloneMaterial) {
cloneMaterialInstanceArray(mMaterialInstances, clone.mMaterialInstances);
}
}
/*
void MeshInstance::useWorldMatrix(Matrix4x3Base* pExternalWorldMatrix) {
unsetWorldMatrix();
if (pExternalWorldMatrix != NULL) {
mWorldMatrix.set(pExternalWorldMatrix, Ptr_SoftRef);
} else {
Matrix4x3Base* pOwnMatrix;
MMemNew(pOwnMatrix, Matrix4x3Base);
mWorldMatrix.set(pOwnMatrix, Ptr_HardRef);
}
if (mSkelInst.isValid()) {
mSkelInst->useWorldMatrix(mWorldMatrix.ptr());
}
}
void MeshInstance::unsetWorldMatrix() {
mWorldMatrix.destroy();
}
bool MeshInstance::hasWorldMatrix() {
return mWorldMatrix.isValid();
}
bool MeshInstance::setWorldMatrix(Matrix4x3Base* pWorldMatrix, bool updateVolumes) {
if (pWorldMatrix != NULL) {
mWorldMatrix.dref() = *pWorldMatrix;
}
if (mSkelInst.isValid()) {
//signal matrix change
mSkelInst->setWorldMatrix(NULL);
if (updateVolumes) {
return mSkelInst->update();
}
}
return false;
}
bool MeshInstance::signalExtrernalWorldMatrixChanged(bool updateVolumes) {
if (mSkelInst.isValid()) {
//signal matrix change
mSkelInst->setWorldMatrix(NULL);
if (updateVolumes) {
return mSkelInst->update();
}
}
return false;
}
void MeshInstance::nonSkeletalSignalExtrernalWorldMatrixChanged() {
}
bool MeshInstance::skeletalSignalExtrernalWorldMatrixChanged(bool updateVolumes) {
//signal matrix change
mSkelInst->setWorldMatrix(NULL);
if (updateVolumes) {
return mSkelInst->update();
}
return false;
}
bool MeshInstance::createSkeletonInstance(Skeleton& skel) {
MMemNew(mSkelInst.ptrRef(), SkeletonInstance());
mSkelInst->bind(&skel);
if (mWorldMatrix.isValid()) {
mSkelInst->useWorldMatrix(mWorldMatrix.ptr());
}
return true;
}
SkeletonInstance* MeshInstance::getSkeletonInstance() {
return mSkelInst.ptr();
}
*/
/*
void MeshInstance::renderExtras(Renderer& renderer, bool renderSkelVolume, bool renderSkelBoneVolumes) {
if (mSkelInst.isValid()) {
if (renderSkelVolume) {
renderer.draw(mSkelInst->getLocalDynamicAAB(), mWorldMatrix.ptr(), &(RenderColor::kGreen));
}
if (renderSkelBoneVolumes) {
mSkelInst->renderBoundingBoxes(renderer);
}
}
}
*/
}
| 17.101796
| 105
| 0.686625
|
jadnohra
|
3b01bb6578e79315fcb1c382fa78278162bf3488
| 885
|
hpp
|
C++
|
code/include/common/Mutex.hpp
|
StuntHacks/infinite-dungeons
|
b462dd27c4e0f7285940e45d086b5d022fea23df
|
[
"MIT"
] | null | null | null |
code/include/common/Mutex.hpp
|
StuntHacks/infinite-dungeons
|
b462dd27c4e0f7285940e45d086b5d022fea23df
|
[
"MIT"
] | null | null | null |
code/include/common/Mutex.hpp
|
StuntHacks/infinite-dungeons
|
b462dd27c4e0f7285940e45d086b5d022fea23df
|
[
"MIT"
] | null | null | null |
/**
* @file common/Mutex.hpp
* @brief Defines the Mutex class
*/
#pragma once
#ifdef __SWITCH__
#include <sys/lock.h>
#else
#ifdef __PC__
#include <mutex>
#endif
#endif
namespace id {
/**
* @brief A mutex
*/
class Mutex {
public:
/**
* @brief Creates the mutex
*/
Mutex();
/**
* @brief Destructor
*
* This automatically unlocks the mutex
*/
~Mutex();
/**
* @brief Locks the mutex
*/
void lock();
/**
* @brief Unlocks the mutex
*/
void unlock();
private:
/* data */
#ifdef __SWITCH__
_LOCK_RECURSIVE_T m_mutex;
#else
#ifdef __PC__
std::recursive_mutex m_mutex;
#endif
#endif
};
} /* id */
| 16.388889
| 47
| 0.444068
|
StuntHacks
|
3b0498e0685a650933d0c9e4519fc67dc41c8d3b
| 4,840
|
cpp
|
C++
|
tank_demo.cpp
|
alerdenisov/eos-tank-demo
|
9ef62fc22e8998d091d09298b0ffbd321e1f8cc2
|
[
"MIT"
] | 13
|
2017-08-02T03:59:45.000Z
|
2021-04-20T04:12:40.000Z
|
tank_demo.cpp
|
philsong/eos-tank-demo
|
9ef62fc22e8998d091d09298b0ffbd321e1f8cc2
|
[
"MIT"
] | 1
|
2021-05-11T02:36:30.000Z
|
2021-05-11T02:36:30.000Z
|
tank_demo.cpp
|
philsong/eos-tank-demo
|
9ef62fc22e8998d091d09298b0ffbd321e1f8cc2
|
[
"MIT"
] | 5
|
2017-07-31T05:27:42.000Z
|
2019-03-30T09:58:07.000Z
|
// Copyright (c) 2017 Aler Denisov
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <tank_demo/tank_demo.hpp>
#include <tank_demo/checks.hpp>
#include <eoslib/print.hpp>
namespace TankDemo
{
using namespace eos;
/// When storing accounts, check for empty balance and remove account
void save_tank(AccountName owner, const Tank &tank)
{
/// value, scope
Tanks::store(tank, owner);
}
void move_tank(Tank &tank, int32_t new_x, int32_t new_y)
{
int64_t prev_hash = pos_to_hash(tank.x, tank.y);
Positions::remove(tank, prev_hash);
tank.x = new_x;
tank.y = new_y;
int64_t next_hash = pos_to_hash(new_x, new_y);
Positions::store(tank, next_hash);
}
void apply_spawn_tank(const Coordinate &coordinate)
{
requireAuth(coordinate.owner);
auto tank = get_tank(coordinate.owner);
require_true(tank.valid);
require_false(tank.in_game);
auto found = get_at_position(coordinate.x, coordinate.y);
require_false(found.valid);
tank.x = coordinate.x;
tank.y = coordinate.y;
tank.lives = INITIAL_LIVES;
tank.points = MAX_POINT_RECOVER;
int64_t hash = pos_to_hash(tank.x, tank.y);
Positions::store(tank, hash);
save_tank(coordinate.owner, tank);
}
void apply_move_tank(const Coordinate &coordinate)
{
requireAuth(coordinate.owner);
auto tank = get_tank(coordinate.owner);
require_ready(tank);
int32_t distance = get_distance(tank.x, tank.y, coordinate.x, coordinate.y);
require_not_less(int32_t(tank.points), distance);
auto found = get_at_position(coordinate.x, coordinate.y);
require_false(found.valid);
move_tank(tank, coordinate.x, coordinate.y);
tank.points -= distance;
save_tank(coordinate.owner, tank);
}
// execute fire transaction
void apply_fire(const Interact &interaction)
{
requireNotice(interaction.from, interaction.to);
requireAuth(interaction.from);
auto from = get_tank(interaction.from);
auto to = get_tank(interaction.to);
require_ready(from);
require_ready(to);
int32_t distance = get_distance(from.x, from.y, to.x, to.y);
// Check if tank have enough points
int32_t required_points = max(int32_t(1), distance - BASE_SHOT_DISTANCE);
require_not_more(required_points, int32_t(from.points));
from.points -= distance - BASE_SHOT_DISTANCE;
to.lives -= 1;
save_tank(interaction.from, from);
save_tank(interaction.to, to);
}
// execute share trx
void apply_share(const Interact &interaction)
{
requireNotice(interaction.from, interaction.to);
requireAuth(interaction.from);
auto from = get_tank(interaction.from);
auto to = get_tank(interaction.to);
require_ready(from);
require_ready(to);
// check if tank have enough points
require_not_less(from.points, uint32_t(1));
// TODO: check is distance is too far
int32_t distance = get_distance(from.x, from.y, to.x, to.y);
require_not_more(distance, int32_t(3));
from.points -= 1;
to.points += 1;
save_tank(interaction.from, from);
save_tank(interaction.to, to);
}
}
using namespace TankDemo;
extern "C" {
void init()
{
save_tank(N(tank), Tank(int32_t(0), int32_t(0)));
}
/// The apply method implements the dispatch of events to this contract
void apply(uint64_t code, uint64_t action)
{
if (code == N(tank))
{
if (action == N(spawn))
{
TankDemo::apply_spawn_tank(currentMessage<TankDemo::Coordinate>());
}
else if (action == N(move))
{
TankDemo::apply_move_tank(currentMessage<TankDemo::Coordinate>());
}
else if (action == N(fire))
{
TankDemo::apply_fire(currentMessage<TankDemo::Interact>());
}
else if (action == N(share))
{
TankDemo::apply_share(currentMessage<TankDemo::Interact>());
}
else if (action == N(info))
{
// not implemented yet
}
}
else if (code == N(judge))
{
// not implemented yet
}
}
}
| 26.888889
| 81
| 0.718595
|
alerdenisov
|
3b07a3124914a3223202fbd58b1008a8d750950a
| 6,514
|
cpp
|
C++
|
widgets/screenshotwidget.cpp
|
JLIT0/GBox
|
f5df851534bfb5cbdf0ae84d25e58a6cfdc69241
|
[
"Apache-2.0"
] | null | null | null |
widgets/screenshotwidget.cpp
|
JLIT0/GBox
|
f5df851534bfb5cbdf0ae84d25e58a6cfdc69241
|
[
"Apache-2.0"
] | null | null | null |
widgets/screenshotwidget.cpp
|
JLIT0/GBox
|
f5df851534bfb5cbdf0ae84d25e58a6cfdc69241
|
[
"Apache-2.0"
] | null | null | null |
/***********************************************************************
*Copyright 2010-20XX by 7ymekk
*
* 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.
*
* @author 7ymekk (7ymekk@gmail.com)
*
************************************************************************/
#include "screenshotwidget.h"
#include "ui_screenshotwidget.h"
#include <QMouseEvent>
#include <QFileDialog>
ScreenshotWidget::ScreenshotWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ScreenshotWidget)
{
ui->setupUi(this);
this->rotation = 0;
this->widthScreen = 320;
this->heightScreen = 480;
this->screenshot = QPixmap::fromImage(noScreenshotImage(this->widthScreen, this->heightScreen), Qt::AutoColor);
this->ui->labelRgb565->setPixmap(this->screenshot);
connect(this->ui->buttonSaveScreenshot, SIGNAL(clicked()), this, SLOT(saveScreenshot()));
connect(this->ui->buttonRefreshScreenshot, SIGNAL(clicked()), this, SLOT(refreshScreenshot()));
connect(this->ui->buttonRotateLeft, SIGNAL(clicked()), this, SLOT(rotateLeft()));
connect(this->ui->buttonRotateRight, SIGNAL(clicked()), this, SLOT(rotateRight()));
this->setLayout(ui->layoutScreenshot);
refreshScreenshot();
}
ScreenshotWidget::~ScreenshotWidget()
{
delete ui;
}
void ScreenshotWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void ScreenshotWidget::resizeEvent(QResizeEvent * event)
{
Q_UNUSED(event);
QSize scaledSize = this->screenshot.size();
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
if (!this->ui->labelRgb565->pixmap() || scaledSize != this->ui->labelRgb565->pixmap()->size())
updateScreenshotLabel();
}
void ScreenshotWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
this->rotation = 0;
QSize scaledSize = QSize(this->widthScreen, this->heightScreen);
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
QPixmap pix = QPixmap::fromImage(noScreenshotImage(scaledSize.width(), scaledSize.height()), Qt::AutoColor);
this->ui->labelRgb565->setPixmap(pix);
this->takeScreenshot();
}
}
void ScreenshotWidget::refreshScreenshot()
{
this->rotation = 0;
QSize scaledSize = QSize(this->widthScreen, this->heightScreen);
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
QPixmap pix = QPixmap::fromImage(noScreenshotImage(scaledSize.width(), scaledSize.height()), Qt::AutoColor);
this->ui->labelRgb565->setPixmap(pix);
takeScreenshot();
}
void ScreenshotWidget::rotateLeft()
{
QMatrix matrix;
QImage image;
image = this->screenshot.toImage();
this->rotation -= 90;
matrix.rotate(this->rotation);
image = image.transformed(matrix);
this->ui->labelRgb565->setPixmap(
QPixmap::fromImage(image, Qt::AutoColor).scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
void ScreenshotWidget::rotateRight()
{
QMatrix matrix;
QImage image;
image = this->screenshot.toImage();
this->rotation += 90;
matrix.rotate(this->rotation);
image = image.transformed(matrix);
this->ui->labelRgb565->setPixmap(
QPixmap::fromImage(image, Qt::AutoColor).scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
void ScreenshotWidget::saveScreenshot()
{
QFile plik;
plik.setFileName(QFileDialog::getSaveFileName(this, tr("Save File..."), "./screenshot.png", tr("Png file")+" (*.png)"));
if (plik.fileName().isEmpty())
return;
if (plik.open(QFile::WriteOnly))
{
QMatrix matrix;
matrix.rotate(this->rotation);
QImage image;
image = this->screenshot.toImage();
image = image.transformed(matrix);
image.save(&plik, "PNG");
plik.close();
}
}
void ScreenshotWidget::showScreenshot(QImage image, int width, int height)
{
this->rotation = 0;
QSize scaledSize = QSize(width, height);
scaledSize.scale(this->size(), Qt::KeepAspectRatio);
this->screenshot = QPixmap::fromImage(image, Qt::AutoColor);
this->ui->labelRgb565->setPixmap(this->screenshot.scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
disconnect(this, SLOT(showScreenshot(QImage,int,int)));
}
void ScreenshotWidget::takeScreenshot()
{
threadScreenshot.widthScreen = this->ui->labelRgb565->width();
threadScreenshot.heightScreen = this->ui->labelRgb565->height();
threadScreenshot.start();
connect(&threadScreenshot, SIGNAL(gotScreenshot(QImage, int, int)), this, SLOT(showScreenshot(QImage, int, int)));
}
void ScreenshotWidget::updateScreenshotLabel()
{
QMatrix matrix;
matrix.rotate(this->rotation);
QImage image;
image = this->screenshot.toImage();
image = image.transformed(matrix);
QSize scaledSize = image.size();
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
this->ui->labelRgb565->setPixmap(QPixmap::fromImage(image.scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation), Qt::AutoColor));
}
| 35.98895
| 125
| 0.600399
|
JLIT0
|
3b07a48c5e7b56564fc3984f19bd2ebf04f54b18
| 1,705
|
cpp
|
C++
|
main/libs/common/src/message.cpp
|
ttgc/ThunderSiege6-Chat
|
1a1601c2d18429baadc3b6d3d0f9b1354246c1f1
|
[
"MIT"
] | null | null | null |
main/libs/common/src/message.cpp
|
ttgc/ThunderSiege6-Chat
|
1a1601c2d18429baadc3b6d3d0f9b1354246c1f1
|
[
"MIT"
] | null | null | null |
main/libs/common/src/message.cpp
|
ttgc/ThunderSiege6-Chat
|
1a1601c2d18429baadc3b6d3d0f9b1354246c1f1
|
[
"MIT"
] | null | null | null |
#include "message.hpp"
namespace network
{
namespace message
{
size_t Message::s_maxsizeUsername = 24;
size_t Message::s_maxsizeMessage = 512;
Message::Message(
const std::string& username,
MessageType msgType,
Team playerTeam,
const std::string& message) noexcept :
m_message(message), m_type(msgType), m_team(playerTeam), m_player(username)
{}
std::optional<Message> Message::getMessageFromJson(const std::string & rawMessage) noexcept
{
nlohmann::json message = nlohmann::json::parse(rawMessage, nullptr, false);
if (message != nlohmann::detail::value_t::discarded &&
message.contains("username") && message.contains("msg_type") &&
message.contains("team") && message.contains("msg") &&
message.at("msg_type").is_number_unsigned() &&
message.at("team").is_number_unsigned() &&
(message.at("msg_type") == GLOBAL || message.at("msg_type") == TEAM) &&
(message.at("team") == TEAM_A || message.at("team") == TEAM_B))
{
return std::make_optional<Message>(std::move(Message(message)));
}
return std::nullopt;
}
nlohmann::json Message::getJsonMessage() const noexcept
{
nlohmann::json formatedMessage =
{
{"username", m_player},
{"msg_type", m_type},
{"team", m_team},
{"msg", m_message}
};
return formatedMessage;
}
bool Message::isCorrectlySized() const noexcept
{
return (m_player.size() <= s_maxsizeUsername) && (m_message.size() <= s_maxsizeMessage);
}
Message::Message(const nlohmann::json& message) noexcept :
Message(message.at("msg"), message.at("msg_type"), message.at("team"), message.at("username"))
{}
}
}
| 29.912281
| 98
| 0.646334
|
ttgc
|
3b086f8c712fea2e9ee0e96726386d77990daf57
| 1,191
|
cpp
|
C++
|
src/lib/ConcurrentLib/ConcurrentObjects.cpp
|
Korovasoft/Concurrent-GARTH
|
2f22c464ce30f743b45bbd6c18a8546bee69be93
|
[
"MIT"
] | null | null | null |
src/lib/ConcurrentLib/ConcurrentObjects.cpp
|
Korovasoft/Concurrent-GARTH
|
2f22c464ce30f743b45bbd6c18a8546bee69be93
|
[
"MIT"
] | null | null | null |
src/lib/ConcurrentLib/ConcurrentObjects.cpp
|
Korovasoft/Concurrent-GARTH
|
2f22c464ce30f743b45bbd6c18a8546bee69be93
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////
////////////////////////////////////////
//
// Copyright (C) 2014 Korovasoft, Inc.
//
// File:
// \file ConcurrentObjects.cpp
//
// Description:
// \brief ConcurrentObjects Library implementation.
//
// Author:
// \author J. Caleb Wherry
//
////////////////////////////////////////
////////////////////////////////////////
// Forward declarations:
////
// Local includes:
#include "ConcurrentObjects.h"
// Compiler includes:
#include <stdexcept>
#include <thread>
/// ConcurrentObjects namespace
namespace ConcurrentObjects
{
ConcurrentCounter::ConcurrentCounter()
{
currentCount = 0;
}
ConcurrentCounter::ConcurrentCounter(uint32_t _maxCount):
maxCount(_maxCount),
currentCount(0)
{
// Do nothing.
}
void ConcurrentCounter::increment()
{
// Check to make sure count doesn't go above maxCount. If so, throw error:
if ( (currentCount+1) <= maxCount)
{
currentCount++;
}
else
{
throw std::out_of_range("Can't count that high!");
}
}
uint32_t ConcurrentCounter::getCount()
{
return currentCount;
}
} // ConcurrentObjects namespace
| 17.26087
| 78
| 0.555835
|
Korovasoft
|
3b0a9c69a2c085265834fdfa3bd784d7609a2b6c
| 7,261
|
cpp
|
C++
|
esp/main/grabber/cfgpull.cpp
|
mincrmatt12/MSign
|
745bd04bc2b38952f5b35cf81f5924bd8f00452e
|
[
"MIT"
] | 5
|
2019-11-04T17:01:46.000Z
|
2020-06-18T07:07:34.000Z
|
esp/main/grabber/cfgpull.cpp
|
mincrmatt12/SignCode
|
745bd04bc2b38952f5b35cf81f5924bd8f00452e
|
[
"MIT"
] | null | null | null |
esp/main/grabber/cfgpull.cpp
|
mincrmatt12/SignCode
|
745bd04bc2b38952f5b35cf81f5924bd8f00452e
|
[
"MIT"
] | 2
|
2020-06-18T07:07:37.000Z
|
2020-10-14T04:41:12.000Z
|
#include "cfgpull.cfg.h"
#include "cfgpull.h"
#include "../dwhttp.h"
#include "esp_system.h"
#include <esp_log.h>
#ifndef SIM
#include <esp_ota_ops.h>
#include <sdkconfig.h>
#endif
#include <memory>
#include <bearssl_hmac.h>
#include <bearssl_hash.h>
#include "../sd.h"
#include "../common/util.h"
#include "../serial.h"
static const char * TAG = "cfgpull";
namespace cfgpull {
bool pull_single_file_for_update(dwhttp::Download &&resp, const char *target_file, uint16_t &crc_out) {
if (!resp.ok()) {
return false;
}
crc_out = 0;
FIL f;
f_open(&f, target_file, FA_WRITE | FA_CREATE_ALWAYS);
ESP_LOGD(TAG, "downloading %s", target_file);
size_t remain = resp.content_length();
uint8_t buf[512];
while (remain) {
size_t len = resp(buf, std::min<size_t>(512, remain));
if (!len) {
ESP_LOGW(TAG, "failed to dw update");
f_close(&f);
return false;
}
UINT bw;
crc_out = util::compute_crc(buf, len, crc_out);
if (f_write(&f, buf, len, &bw)) {
ESP_LOGW(TAG, "failed to write update");
f_close(&f);
return false;
}
remain -= len;
}
f_close(&f);
resp.make_nonclose();
return true;
}
}
void cfgpull::init() {
if (!enabled) ESP_LOGI(TAG, "cfgpull is not turned on");
}
bool cfgpull::loop() {
#ifdef CONFIG_DISABLE_CFGPULL
return true;
#endif
if (!enabled) return true;
// Check if endpoint url is configured
if (!pull_host) {
ESP_LOGE(TAG, "cfgpull is enabled but url is missing.");
return false;
}
bool new_config = false, new_system = false;
{
char metrics_string[256];
{
int free_mem = esp_get_free_heap_size();
int free_dram = heap_caps_get_free_size(MALLOC_CAP_8BIT);
snprintf(metrics_string, sizeof metrics_string, "mem_free %d; mem_free_dram %d", free_mem, free_dram);
}
const char *headers[][2] = {
#ifndef SIM
{"X-MSign-Metrics", metrics_string},
#endif
{nullptr, nullptr}
};
auto resp = dwhttp::download_with_callback(pull_host, "/a/versions", headers);
if (!resp.ok()) return false;
json::JSONParser jp([&](json::PathNode ** stack, uint8_t stack_ptr, const json::Value& jv){
if (stack_ptr != 2) return;
if (strcmp(stack[1]->name, "firm") == 0 && jv.type == jv.STR) {
#ifndef SIM
new_system = strcmp(
jv.str_val,
esp_ota_get_app_description()->version
) != 0;
if (new_system) ESP_LOGI(TAG, "detected new system version");
#endif
}
else if (strcmp(stack[1]->name, "config") == 0 && !only_firm) {
if (jv.int_val != version_id) {
new_config = true;
ESP_LOGI(TAG, "detected new config version");
}
}
});
if (!jp.parse(resp)) {
ESP_LOGW(TAG, "couldn't parse version json");
return false;
}
// If new updates are available, we should try to keep-alive
if (new_config || new_system) resp.make_nonclose();
else {
// No new updates, return now
return true;
}
}
// New updates found, authenticate with server.
std::unique_ptr<uint8_t []> authbuf;
{
auto resp = dwhttp::download_with_callback(pull_host, "/a/challenge");
if (!resp.ok()) return false;
if (resp.is_unknown_length()) return false;
// allocate resp buf with size for 5 "Chip", 1 separator, 64 hash nybbles and 1 terminator (71)
authbuf.reset(new uint8_t[resp.content_length() + 71]);
bzero(authbuf.get(), resp.content_length() + 71);
strcpy((char *)authbuf.get(), "Chip ");
size_t remain = resp.content_length();
uint8_t * place = authbuf.get() + 5;
while (remain) {
size_t amt = resp(place, remain);
if (!amt) return false;
place += amt;
remain -= amt;
}
ESP_LOGD(TAG, "got authstr %s", authbuf.get());
resp.make_nonclose();
// Perform hmac
authbuf[resp.content_length() + 5] = ':';
br_hmac_key_context kctx;
br_hmac_key_init(&kctx, &br_sha256_vtable, pull_secret, strlen(pull_secret));
br_hmac_context hctx;
br_hmac_init(&hctx, &kctx, 32);
br_hmac_update(&hctx, authbuf.get() + 5, resp.content_length());
// Output to buffer and convert backwards.
br_hmac_out(&hctx, authbuf.get() + resp.content_length() + 1 + 5);
// Convert to hex
for (ssize_t pos = 31; pos >= 0; --pos) {
const static char * hexdigits = "0123456789abcdef";
authbuf[resp.content_length() + 6 + pos * 2 + 1] = hexdigits[authbuf[5 + resp.content_length() + 1 + pos] % 0x10];
authbuf[resp.content_length() + 6 + pos * 2] = hexdigits[authbuf[5 + resp.content_length() + 1 + pos] >> 4];
}
ESP_LOGD(TAG, "signed authstr %s", authbuf.get());
}
// Perform config update first.
const char * pull_host_copy = pull_host; // if we overwrite config during this don't blow up.
const char * headers[][2] = {
{"Authorization", (char *)authbuf.get()},
{nullptr, nullptr}
};
if (new_config) {
auto resp = dwhttp::download_with_callback(pull_host_copy, "/a/conf.json", headers);
if (!resp.ok()) {
ESP_LOGW(TAG, "failed to dw conf");
return false;
}
resp.make_nonclose();
// Pull config.
FIL f;
f_open(&f, "0:/config.json.tmp", FA_CREATE_ALWAYS | FA_WRITE);
size_t remain = resp.content_length();
uint8_t buf[64];
while (remain) {
size_t len = resp(buf, std::min<size_t>(64, remain));
if (!len) {
ESP_LOGW(TAG, "failed to dw cfg");
f_close(&f);
return false;
}
UINT bw;
if (f_write(&f, buf, len, &bw)) {
ESP_LOGW(TAG, "failed to write cfg");
}
remain -= len;
}
f_close(&f);
f_unlink("0:/config.json.old");
f_rename("0:/config.json", "0:/config.json.old");
f_rename("0:/config.json.tmp", "0:/config.json");
if (!config::parse_config_from_sd()) {
ESP_LOGW(TAG, "new config failed to parse, reinstating old config");
f_unlink("0:/config.json.bad");
f_rename("0:/config.json", "0:/config.json.bad");
f_rename("0:/config.json.old", "0:/config.json");
config::parse_config_from_sd();
enabled = false; //stop parsing
return false;
}
// new config installed ok
ESP_LOGI(TAG, "new config pulled succesfully");
}
if (new_system) {
{
slots::WebuiStatus current_status;
current_status.flags = slots::WebuiStatus::RECEIVING_SYSUPDATE;
serial::interface.update_slot(slots::WEBUI_STATUS, current_status);
}
// download files
uint16_t esp_csum, stm_csum;
f_mkdir("0:/upd");
if (!pull_single_file_for_update(
dwhttp::download_with_callback(pull_host_copy, "/a/esp.bin", headers),
"/upd/esp.bin",
esp_csum
) || !pull_single_file_for_update(
dwhttp::download_with_callback(pull_host_copy, "/a/stm.bin", headers),
"/upd/stm.bin",
stm_csum
)) {
ESP_LOGE(TAG, "failed to download sysupgrade files, bail");
{
slots::WebuiStatus current_status;
current_status.flags = slots::WebuiStatus::LAST_RX_FAILED;
serial::interface.update_slot(slots::WEBUI_STATUS, current_status);
}
return false;
}
// write checksums
FIL f;
f_open(&f, "/upd/chck.sum", FA_WRITE | FA_CREATE_ALWAYS);
UINT bw;
f_write(&f, &esp_csum, 2, &bw);
f_write(&f, &stm_csum, 2, &bw);
f_close(&f);
// Set the update state for update
f_open(&f, "/upd/state", FA_WRITE | FA_CREATE_ALWAYS);
f_putc(0, &f);
f_close(&f);
ESP_LOGI(TAG, "finished pulling update, rebooting");
}
dwhttp::close_connection(pull_host_copy[0] == '_');
if (new_system) serial::interface.reset();
return true;
}
| 25.839858
| 117
| 0.656521
|
mincrmatt12
|
3b0ea8fbee263602def6f08e97a21b5a9796e3fc
| 993
|
cpp
|
C++
|
ambient-sandbox-application/demos/PlatformGame2D/LevelManager.cpp
|
prajwaldp/cpp-game-engine
|
df036f115ae45fda21e57d526d251b43ed6368c9
|
[
"MIT"
] | null | null | null |
ambient-sandbox-application/demos/PlatformGame2D/LevelManager.cpp
|
prajwaldp/cpp-game-engine
|
df036f115ae45fda21e57d526d251b43ed6368c9
|
[
"MIT"
] | null | null | null |
ambient-sandbox-application/demos/PlatformGame2D/LevelManager.cpp
|
prajwaldp/cpp-game-engine
|
df036f115ae45fda21e57d526d251b43ed6368c9
|
[
"MIT"
] | null | null | null |
//
// Created by Prajwal Prakash on 24/06/20.
//
#include "LevelManager.h"
#include <filesystem>
#include <fstream>
LevelManager::LevelManager(const char* assets_directory) : m_AssetsDirectory(assets_directory)
{
LoadLevels();
}
void LevelManager::LoadLevels()
{
for (const auto& entry : std::filesystem::directory_iterator(m_AssetsDirectory))
{
AM_INFO("Reading level from {}", entry.path().c_str());
std::string line; // to read the file contents line by line
std::ifstream level_file(entry.path());
// Initialize data for the level
std::string map;
uint32_t width = 0, height = 0;
while (std::getline(level_file, line))
{
map += line;
height++;
}
width = line.size();
Ambient::Ref<Level> level = std::make_shared<Level>();
level->Map = map;
level->Width = width;
level->Height = height;
m_Levels.push_back(level);
}
}
| 21.586957
| 94
| 0.59718
|
prajwaldp
|
3b13b6b256f7e9dd51deb0231598592148539d1c
| 23,624
|
cpp
|
C++
|
duds/hardware/interface/linux/GpioDevPort.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
duds/hardware/interface/linux/GpioDevPort.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
duds/hardware/interface/linux/GpioDevPort.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2018 Jeff Jackowski
*/
#include <boost/exception/errinfo_file_name.hpp>
#include <boost/exception/errinfo_errno.hpp>
#include <duds/hardware/interface/linux/GpioDevPort.hpp>
#include <duds/hardware/interface/PinConfiguration.hpp>
#include <linux/gpio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
namespace duds { namespace hardware { namespace interface { namespace linux {
/**
* Initializes a gpiohandle_request structure.
* @param req The gpiohandle_request structure to be initialized.
* @param consumer The consumer name to place inside the gpiohandle_request.
*/
static void InitGpioHandleReq(
gpiohandle_request &req,
const std::string &consumer
) {
memset(&req, 0, sizeof(gpiohandle_request));
strcpy(req.consumer_label, consumer.c_str());
}
/**
* Adds a GPIO line offset to a gpiohandle_request object.
* @param req The request object that will hold the offset.
* @param offset The offset to add. It will be placed at the end.
*/
static void AddOffset(gpiohandle_request &req, std::uint32_t offset) {
#ifndef NDEBUG
// check limit on number of lines
assert(req.lines < GPIOHANDLES_MAX);
// ensure the offset is not already present
for (int idx = req.lines - 1; idx >= 0; --idx) {
assert(req.lineoffsets[idx] != offset);
}
#endif
req.lineoffsets[req.lines++] = offset;
}
/**
* Finds the array index that corresponds to the given offset. Useful in cases
* where the two do not match, such as with IoGpioRequest.
* @param req The request object to search.
* @param offset The pin offset to find.
* @return The index into the lineoffsets array in @a req for
* @a offset, or -1 if the offset was not found.
*/
static int FindOffset(gpiohandle_request &req, std::uint32_t offset) {
for (int idx = req.lines - 1; idx >= 0; --idx) {
if (req.lineoffsets[idx] == offset) {
return idx;
}
}
return -1;
}
/**
* Removes a GPIO line offset from a gpiohandle_request object.
* @param req The request object that holds the offset.
* @param offset The offset to remove. The offset at the end will take its
* place.
* @return True if the item was found and removed, false otherwise.
*/
static bool RemoveOffset(gpiohandle_request &req, std::uint32_t offset) {
// non-empty request?
if (req.lines) {
// search for offset
for (int idx = req.lines - 1; idx >= 0; --idx) {
if (req.lineoffsets[idx] == offset) {
// move last offset into spot of offset to remove
req.lineoffsets[idx] = req.lineoffsets[req.lines - 1];
// also move output state value
req.default_values[idx] = req.default_values[req.lines - 1];
// remove last
--req.lines;
return true;
}
}
}
return false;
}
/**
* Closes the file descriptor in the request object if it appears to have a
* file, and then sets the descriptor to zero.
* @param req The request object to modify.
*/
static void CloseIfOpen(gpiohandle_request &req) {
if (req.fd) {
close(req.fd);
req.fd = 0;
}
}
/**
* Requests input states from the kernel.
* If the request for using input rather than output has not yet been made,
* it will be made here. This is because it is valid to have set an input
* state, lose the access object, then create a new access object for the same
* pins, and assume the pins are still inputs. The request to use them as
* inputs, however, must be made again to the kernel.
* @param chipFd The file descriptor for the GPIO device. Needed for the
* GPIO_GET_LINEHANDLE_IOCTL operation that will occur if any
* of the pins has not yet been configured as an input.
* @param result The input states.
* @param req The request object with the input pins.
*/
static void GetInput(int chipFd, gpiohandle_data &result, gpiohandle_request &req) {
assert(req.flags & GPIOHANDLE_REQUEST_INPUT);
assert(req.lines > 0);
if (!req.fd && (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0)) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
assert(req.fd);
if (ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &result) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLineValuesError() <<
boost::errinfo_errno(res)
);
}
}
/**
* Sets the output states for all the pins in the request object.
* If the request for using output rather than input has not yet been made,
* it will be made here. This is because it is valid to have set an output
* state, lose the access object, then create a new access object for the same
* pins, and assume the pins are still outputs. The request to use them as
* outputs, however, must be made again to the kernel.
* @internal
* @param chipFd The file descriptor for the GPIO device. Needed for the
* GPIO_GET_LINEHANDLE_IOCTL operation that will occur if any
* of the pins has not yet been configured as an output.
* @param req The request object with the output pins and states.
* The default_values field is used for the output states,
* even when the pins are already configured as outputs.
*/
static void SetOutput(int chipFd, gpiohandle_request &req) {
assert(req.flags & GPIOHANDLE_REQUEST_OUTPUT);
assert(req.lines > 0);
if (!req.fd) {
// obtain new line handle only when it didn't already exist
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
// else, the above ioctl function succeeded and the output is now set
} else {
// already have line handle
assert(req.fd);
if (ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &(req.default_values)) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevSetLineValuesError() <<
boost::errinfo_errno(res)
);
}
}
}
/**
* An abstraction for using gpiohandle_request object(s).
* @author Jeff Jackowski
*/
class GpioRequest {
public:
virtual ~GpioRequest() { };
/**
* Configures the pin at the given offset as an input.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
*/
virtual void inputOffset(int chipFd, std::uint32_t offset) = 0;
/**
* Configures the pin at the given offset as an output.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
* @param state The output state for the pin.
*/
virtual void outputOffset(int chipFd, std::uint32_t offset, bool state) = 0;
/**
* Read from all input pins.
* @param chipFd The file descriptor for the GPIO device.
* @param result The input states.
* @param offsets A pointer to the start of an array with the line
* offset values for identifying where the input source.
* @param length The number of line offsets.
*/
virtual void read(
int chipFd,
gpiohandle_data &result,
std::uint32_t *&offsets,
int &length
) = 0;
/**
* Configures pins as outputs and sets their output states.
* @param chipFd The file descriptor for the GPIO device.
*/
virtual void write(int chipFd) = 0;
/**
* Sets the output state of a single output pin.
* @pre The pin is already configured as an output.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
* @param state The output state for the pin.
*/
virtual void write(int chipFd, std::uint32_t offset, bool state) = 0;
/**
* Reads the input state of the indicated pin. Configures the pin as an
* input if not already an input.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
*/
virtual bool inputState(int chipFd, std::uint32_t offset) = 0;
/**
* Sets the output state of a single pin in advance of making the output
* request to the port. Use write(int) to output the data.
* @param offset The pin offset.
* @param state The output state to store for the pin.
*/
virtual void outputState(std::uint32_t offset, bool state) = 0;
};
/**
* Implements using a single gpiohandle_request object for working with a
* single pin.
* @author Jeff Jackowski
*/
class SingleGpioRequest : public GpioRequest {
/**
* The request object.
*/
gpiohandle_request req;
public:
SingleGpioRequest(const std::string &consumer, std::uint32_t offset) {
InitGpioHandleReq(req, consumer);
req.lineoffsets[0] = offset;
req.lines = 1;
}
virtual ~SingleGpioRequest() {
CloseIfOpen(req);
}
virtual void inputOffset(int chipFd, std::uint32_t offset) {
// offset must not change
assert(offset == req.lineoffsets[0]);
req.flags = GPIOHANDLE_REQUEST_INPUT;
CloseIfOpen(req);
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void outputOffset(int chipFd, std::uint32_t offset, bool state) {
// offset must not change
assert(offset == req.lineoffsets[0]);
req.flags = GPIOHANDLE_REQUEST_OUTPUT;
CloseIfOpen(req);
req.default_values[0] = state;
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void read(
int chipFd,
gpiohandle_data &result,
std::uint32_t *&offsets,
int &length
) {
GetInput(chipFd, result, req);
offsets = req.lineoffsets;
length = 1;
}
virtual void write(int chipFd) {
SetOutput(chipFd, req);
}
virtual void write(int chipFd, std::uint32_t offset, bool state) {
// offset must not change
assert(offset == req.lineoffsets[0]);
// early exit: already outputing the requested state
if (req.fd && (state == (req.default_values[0] > 0))) {
return;
}
// might not yet be an output
if (req.flags != GPIOHANDLE_REQUEST_OUTPUT) {
req.flags = GPIOHANDLE_REQUEST_OUTPUT;
CloseIfOpen(req);
}
req.default_values[0] = state;
SetOutput(chipFd, req);
}
virtual bool inputState(int chipFd, std::uint32_t offset) {
// offset must not change
assert(offset == req.lineoffsets[0]);
gpiohandle_data result;
// might not yet be an input
if (req.flags != GPIOHANDLE_REQUEST_INPUT) {
req.flags = GPIOHANDLE_REQUEST_INPUT;
CloseIfOpen(req);
}
GetInput(chipFd, result, req);
return result.values[0];
}
virtual void outputState(std::uint32_t offset, bool state) {
// offset must not change
assert(offset == req.lineoffsets[0]);
req.default_values[0] = state;
}
};
/**
* Implements using two gpiohandle_requests object for working with multiple
* pins.
* @author Jeff Jackowski
*/
class IoGpioRequest : public GpioRequest {
/**
* Input request.
*/
gpiohandle_request inReq;
/**
* Output request.
*/
gpiohandle_request outReq;
public:
IoGpioRequest(const std::string &consumer) {
InitGpioHandleReq(inReq, consumer);
InitGpioHandleReq(outReq, consumer);
inReq.flags = GPIOHANDLE_REQUEST_INPUT;
outReq.flags = GPIOHANDLE_REQUEST_OUTPUT;
}
virtual ~IoGpioRequest() {
CloseIfOpen(inReq);
CloseIfOpen(outReq);
}
void lastOutputState(bool state) {
outReq.default_values[outReq.lines - 1] = state;
}
/**
* Adds an offset for input use.
* @pre The offset is not in either the input or output set.
*/
void addInputOffset(std::uint32_t offset) {
AddOffset(inReq, offset);
}
/**
* Adds an offset for output use and sets the initial output state.
* @pre The offset is not in either the input or output set.
*/
void addOutputOffset(std::uint32_t offset, bool state) {
AddOffset(outReq, offset);
lastOutputState(state);
}
virtual void inputOffset(int chipFd, std::uint32_t offset) {
bool rem = RemoveOffset(outReq, offset);
assert(rem);
CloseIfOpen(outReq);
AddOffset(inReq, offset);
CloseIfOpen(inReq);
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &inReq) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void outputOffset(int chipFd, std::uint32_t offset, bool state) {
bool rem = RemoveOffset(inReq, offset);
assert(rem);
CloseIfOpen(inReq);
AddOffset(outReq, offset);
CloseIfOpen(outReq);
lastOutputState(state);
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &outReq) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void read(
int chipFd,
gpiohandle_data &result,
std::uint32_t *&offsets,
int &length
) {
GetInput(chipFd, result, inReq);
offsets = inReq.lineoffsets;
length = inReq.lines;
}
virtual void write(int chipFd) {
if (outReq.lines) {
SetOutput(chipFd, outReq);
}
}
virtual void write(int chipFd, std::uint32_t offset, bool state) {
int idx = FindOffset(outReq, offset);
assert(idx >= 0);
// early exit: already outputing the requested state
if (outReq.fd && (state == (outReq.default_values[idx] > 0))) {
return;
}
outReq.default_values[idx] = state;
SetOutput(chipFd, outReq);
}
virtual bool inputState(int chipFd, std::uint32_t offset) {
gpiohandle_data result;
GetInput(chipFd, result, inReq);
int idx = FindOffset(inReq, offset);
assert(idx >= 0);
return result.values[idx] > 0;
}
virtual void outputState(std::uint32_t offset, bool state) {
int idx = FindOffset(outReq, offset);
if (idx < 0) {
bool rem = RemoveOffset(inReq, offset);
// the pin must already be in a request object
assert(rem);
CloseIfOpen(inReq);
AddOffset(outReq, offset);
CloseIfOpen(outReq);
lastOutputState(state);
} else {
outReq.default_values[idx] = state;
}
}
};
// ---------------------------------------------------------------------------
GpioDevPort::GpioDevPort(
const std::string &path,
unsigned int firstid,
const std::string &username
) : DigitalPortIndependentPins(0, firstid), consumer(username), devpath(path) {
chipFd = open(path.c_str(), 0);
if (chipFd < 0) {
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path)
);
}
gpiochip_info cinfo;
if (ioctl(chipFd, GPIO_GET_CHIPINFO_IOCTL, &cinfo) < 0) {
int res = errno;
close(chipFd);
// could improve error reporting, but may not really matter
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path) << boost::errinfo_errno(res)
);
}
name = cinfo.name;
pins.resize(cinfo.lines);
for (std::uint32_t pidx = 0; pidx < cinfo.lines; ++pidx) {
initPin(pidx, pidx);
}
}
GpioDevPort::GpioDevPort(
const std::vector<unsigned int> &ids,
const std::string &path,
unsigned int firstid,
const std::string &username
) : DigitalPortIndependentPins(ids.size(), firstid), consumer(username),
devpath(path) {
chipFd = open(path.c_str(), 0);
if (chipFd < 0) {
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path)
);
}
gpiochip_info cinfo;
if (ioctl(chipFd, GPIO_GET_CHIPINFO_IOCTL, &cinfo) < 0) {
int res = errno;
close(chipFd);
// could improve error reporting, but may not really matter
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path) << boost::errinfo_errno(res)
);
}
name = cinfo.name;
std::vector<unsigned int>::const_iterator iter = ids.begin();
for (unsigned int pid = 0; iter != ids.end(); ++iter, ++pid) {
initPin(*iter, pid);
}
}
std::shared_ptr<GpioDevPort> GpioDevPort::makeConfiguredPort(
PinConfiguration &pc,
const std::string &name,
const std::string &defaultPath,
bool forceDefault
) {
// find the port's config object
const PinConfiguration::Port &port = pc.port(name);
// work out device file path
std::string path;
if (forceDefault || port.typeval.empty()) {
path = defaultPath;
} else {
path = port.typeval;
}
// enumerate the pins
std::vector<unsigned int> gpios;
unsigned int next = 0;
gpios.reserve(port.pins.size());
for (auto const &pin : port.pidIndex()) {
// pin IDs cannot be assigned arbitrary values
if ((pin.pid + port.idOffset) != pin.gid) {
DUDS_THROW_EXCEPTION(PortBadPinIdError() <<
PortPinId(pin.gid)
);
}
// need empty spots?
if (pin.pid > next) {
// add unavailable pins
gpios.insert(gpios.end(), pin.pid - next, -1);
}
// add available pin
gpios.push_back(pin.pid);
next = pin.pid + 1;
}
std::shared_ptr<GpioDevPort> sp = std::make_shared<GpioDevPort>(
gpios,
path,
port.idOffset
);
try {
pc.attachPort(sp, name);
} catch (PinError &pe) {
pe << boost::errinfo_file_name(path);
throw;
}
return sp;
}
GpioDevPort::~GpioDevPort() {
shutdown();
close(chipFd);
}
void GpioDevPort::initPin(std::uint32_t offset, unsigned int pid) {
if (offset == -1) {
// line cannot be used
pins[pid].markNonexistent();
return;
}
// prepare data for inquiry to kernel
gpioline_info linfo;
memset(&linfo, 0, sizeof(linfo)); // all examples do this; needed?
linfo.line_offset = offset;
// request data from the kernel; check for error
if (ioctl(chipFd, GPIO_GET_LINEINFO_IOCTL, &linfo) < 0) {
int res = errno;
close(chipFd);
DUDS_THROW_EXCEPTION(DigitalPortLacksPinError() <<
PinErrorId(globalId(offset)) << PinErrorPortId(offset) <<
boost::errinfo_errno(res) << boost::errinfo_file_name(devpath)
);
}
// used by kernel?
if (linfo.flags & GPIOLINE_FLAG_KERNEL) {
// line cannot be used
pins[pid].markNonexistent();
} else {
// set configuration to match reported status
if (linfo.flags & GPIOLINE_FLAG_IS_OUT) {
pins[pid].conf.options = DigitalPinConfig::DirOutput;
} else {
pins[pid].conf.options = DigitalPinConfig::DirInput;
}
if (linfo.flags & GPIOLINE_FLAG_OPEN_DRAIN) {
pins[pid].conf.options |= DigitalPinConfig::OutputDriveLow;
} else if (linfo.flags & GPIOLINE_FLAG_OPEN_SOURCE) {
pins[pid].conf.options |= DigitalPinConfig::OutputDriveHigh;
} else if (pins[pid].conf.options & DigitalPinConfig::DirOutput) {
pins[pid].conf.options |= DigitalPinConfig::OutputPushPull;
}
// no data on output currents
pins[pid].conf.minOutputCurrent = pins[pid].conf.maxOutputCurrent = 0;
// Unfortunately, the kernel reports on the current status of the line
// and not the line's capabilities. Report the line can do what the
// kernel supports, and hope this doesn't cause trouble.
pins[pid].cap.capabilities =
DigitalPinCap::Input |
DigitalPinCap::OutputPushPull /*|
DigitalPinCap::EventEdgeFalling | // theses are not yet supported
DigitalPinCap::EventEdgeRising |
DigitalPinCap::EventEdgeChange |
DigitalPinCap::InterruptOnEvent */;
// no data on output currents
pins[pid].cap.maxOutputCurrent = 0;
}
}
bool GpioDevPort::simultaneousOperations() const {
return true;
}
void GpioDevPort::madeAccess(DigitalPinAccess &acc) {
portData(acc).pointer = new SingleGpioRequest(consumer, acc.localId());
}
void GpioDevPort::madeAccess(DigitalPinSetAccess &acc) {
// create the request objects
IoGpioRequest *igr = new IoGpioRequest(consumer);
// fill stuff?
for (auto pid : acc.localIds()) {
const PinEntry &pe = pins[pid];
if (pe.conf.options & DigitalPinConfig::DirInput) {
//AddOffset(hreq->inReq, pid);
igr->addInputOffset(pid);
} else if (pe.conf.options & DigitalPinConfig::DirOutput) {
//AddOffset(hreq->outReq, pid);
igr->addOutputOffset(
pid,
(pe.conf.options & DigitalPinConfig::OutputState) > 0
);
}
assert(pe.conf.options & DigitalPinConfig::DirMask);
}
portData(acc).pointer = igr;
}
void GpioDevPort::retiredAccess(const DigitalPinAccess &acc) noexcept {
SingleGpioRequest *sgr;
portDataPtr(acc, &sgr);
delete sgr;
}
void GpioDevPort::retiredAccess(const DigitalPinSetAccess &acc) noexcept {
IoGpioRequest *igr;
portDataPtr(acc, &igr);
delete igr;
}
void GpioDevPort::configurePort(
unsigned int lid,
const DigitalPinConfig &cfg,
DigitalPinAccessBase::PortData *pdata
) try {
GpioRequest *gr = (GpioRequest*)pdata->pointer;
DigitalPinConfig &dpc = pins[lid].conf;
// change in config?
if (
(dpc.options & DigitalPinConfig::DirMask) !=
(cfg & DigitalPinConfig::DirMask)
) {
if (cfg & DigitalPinConfig::DirInput) {
gr->inputOffset(chipFd, lid);
} else if (cfg & DigitalPinConfig::DirOutput) {
gr->outputOffset(
chipFd,
lid,
dpc.options & DigitalPinConfig::OutputState
);
}
}
} catch (PinError &pe) {
pe << PinErrorId(globalId(lid)) << boost::errinfo_file_name(devpath);
throw;
}
bool GpioDevPort::inputImpl(
unsigned int gid,
DigitalPinAccessBase::PortData *pdata
) try {
GpioRequest *gr = (GpioRequest*)pdata->pointer;
int lid = localId(gid);
bool res = gr->inputState(chipFd, lid);
pins[lid].conf.options.setTo(DigitalPinConfig::InputState, res);
return res;
} catch (PinError &pe) {
pe << PinErrorId(gid) << boost::errinfo_file_name(devpath);
throw;
}
std::vector<bool> GpioDevPort::inputImpl(
const std::vector<unsigned int> &pvec,
DigitalPinAccessBase::PortData *pdata
) try {
GpioRequest *gr = (GpioRequest*)pdata->pointer;
gpiohandle_data result;
std::uint32_t *offsets;
int length;
gr->read(chipFd, result, offsets, length);
assert(length >= pvec.size());
// record input states
for (int idx = 0; idx < length; ++idx) {
pins[offsets[idx]].conf.options.setTo(
DigitalPinConfig::InputState,
result.values[idx] > 0
);
}
// return input states
std::vector<bool> outv(pvec.size());
int idx = 0;
for (const unsigned int &gid : pvec) {
outv[idx++] =
(pins[localId(gid)].conf.options & DigitalPinConfig::InputState) > 0;
}
return outv;
} catch (PinError &pe) {
pe << boost::errinfo_file_name(devpath);
throw;
}
void GpioDevPort::outputImpl(
unsigned int lid,
bool state,
DigitalPinAccessBase::PortData *pdata
) try {
// find the pin configuration
DigitalPinConfig &dpc = pins[lid].conf;
// get the request object to make modifications
GpioRequest *gr = (GpioRequest*)pdata->pointer;
// is output?
if (dpc.options & DigitalPinConfig::DirOutput) {
// set output state
gr->write(chipFd, lid, state);
}
// store new state; no change if error above
dpc.options.setTo(DigitalPinConfig::OutputState, state);
} catch (PinError &pe) {
pe << PinErrorId(globalId(lid)) << boost::errinfo_file_name(devpath);
throw;
}
void GpioDevPort::outputImpl(
const std::vector<unsigned int> &pvec,
const std::vector<bool> &state,
DigitalPinAccessBase::PortData *pdata
) try {
// get the request object to make modifications
GpioRequest *gr = (GpioRequest*)pdata->pointer;
// loop through all pins to alter
std::vector<unsigned int>::const_iterator piter = pvec.begin();
std::vector<bool>::const_iterator siter = state.begin();
int outs = 0;
for (; piter != pvec.end(); ++piter, ++siter) {
// configured for output? might be changing state ahead of config change
if (pins[*piter].conf.options & DigitalPinConfig::DirOutput) {
// configure the port data; no output happens yet
gr->outputState(*piter, *siter);
++outs;
}
// store new state
pins[*piter].conf.options.setTo(DigitalPinConfig::OutputState, *siter);
}
// send output if already in output state
if (outs) {
gr->write(chipFd);
}
} catch (PinError &pe) {
pe << boost::errinfo_file_name(devpath);
throw;
}
} } } } // namespaces
| 30.326059
| 84
| 0.696664
|
jjackowski
|
3b162794ea81a887c37746a19ad17f25cfe96a7d
| 8,986
|
cxx
|
C++
|
src/ptclib/textdata.cxx
|
suxinde2009/ptlib
|
3d185e55144b98aa46903d48468745ffd07b2a9d
|
[
"Beerware"
] | null | null | null |
src/ptclib/textdata.cxx
|
suxinde2009/ptlib
|
3d185e55144b98aa46903d48468745ffd07b2a9d
|
[
"Beerware"
] | null | null | null |
src/ptclib/textdata.cxx
|
suxinde2009/ptlib
|
3d185e55144b98aa46903d48468745ffd07b2a9d
|
[
"Beerware"
] | 1
|
2020-07-21T11:47:44.000Z
|
2020-07-21T11:47:44.000Z
|
/*
* textdata.cxx
*
* Text data stream parser
*
* Portable Tools Library
*
* Copyright (C) 2019 by Vox Lucida Pty. Ltd.
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Portable Tools Library.
*
* The Initial Developer of the Original Code is Vox Lucida Pty. Ltd.
*
* Contributor(s): Robert Jongbloed
* Blackboard, inc
*/
#include <ptlib.h>
#include <ptclib/textdata.h>
PTextDataFormat::PTextDataFormat()
{
}
PTextDataFormat::PTextDataFormat(const PStringArray & headings)
: m_headings(headings)
{
}
bool PTextDataFormat::ReadHeadings(PChannel & channel)
{
m_headings.RemoveAll();
for (;;) {
PVarType field(PVarType::VarDynamicString);
int result = ReadField(channel, field, false);
if (result < 0)
return false;
PString heading = field.AsString();
if (heading.IsEmpty())
return false;
m_headings.AppendString(heading);
if (result > 0)
return true;
}
}
bool PTextDataFormat::WriteHeadings(PChannel & channel)
{
if (!PAssert(!m_headings.IsEmpty(), PInvalidParameter))
return false;
PINDEX last = m_headings.GetSize() - 1;
for (PINDEX i = 0; i <= last; ++i) {
if (!WriteField(channel, m_headings[i], i == last))
return false;
}
return true;
}
bool PTextDataFormat::ReadRecord(PChannel & channel, PVarData::Record & data)
{
for (PINDEX i = 0; i < m_headings.GetSize(); ++i) {
PString heading = m_headings[i];
bool autoDetect = false;
PVarType * field = data.GetAt(heading);
if (field == NULL) {
field = new PVarType;
autoDetect = true;
}
int result = ReadField(channel, *field, autoDetect);
data.SetAt(heading, field);
if (result != 0)
return result > 0;
}
for (;;) {
PVarType dummy;
int result = ReadField(channel, dummy, false);
if (result != 0)
return result > 0;
}
}
bool PTextDataFormat::WriteRecord(PChannel & channel, const PVarData::Record & data)
{
if (!PAssert(!m_headings.IsEmpty(), PInvalidParameter))
return false;
PINDEX last = m_headings.GetSize() - 1;
for (PINDEX i = 0; i <= last; ++i) {
PVarType * field = data.GetAt((m_headings[i]));
if (!WriteField(channel, field != NULL ? *field : PVarType(), i == last))
return false;
}
return true;
}
PCommaSeparatedVariableFormat::PCommaSeparatedVariableFormat()
{
}
PCommaSeparatedVariableFormat::PCommaSeparatedVariableFormat(const PStringArray & headings)
: PTextDataFormat(headings)
{
}
int PCommaSeparatedVariableFormat::ReadField(PChannel & channel, PVarType & field, bool autoDetect)
{
bool inQuote = false;
bool wasQuoted = false;
bool escaped = false;
bool skipws = true;
PStringStream str;
while (channel.good()) {
int c = channel.get();
if (inQuote) {
if (c == '"')
inQuote = false;
else if (escaped) {
str << (char)c;
escaped = false;
}
else if (c == '\\')
escaped = true;
else
str << (char)c;
}
else {
if (c == '\r' || c == '\n' || c == ',') {
if (autoDetect && wasQuoted)
field.SetDynamicString(str);
else
field.FromString(str, autoDetect);
return c == ',' ? 0 : 1;
}
if (skipws && isblank(c))
continue;
skipws = false;
if (c == '"')
inQuote = wasQuoted = true;
else
str << (char)c;
}
}
return -1;
}
bool PCommaSeparatedVariableFormat::WriteField(PChannel & channel, const PVarType & field, bool endOfLine)
{
switch (field.GetType()) {
default:
channel << field;
break;
case PVarType::VarStaticString:
case PVarType::VarDynamicString:
case PVarType::VarStaticBinary :
case PVarType::VarDynamicBinary :
PString str = field.AsString();
if (!str.IsEmpty() && (str.FindOneOf(",\r\n") != P_MAX_INDEX || isspace(str[0]) || isspace(str[str.GetLength()-1])))
channel << str.ToLiteral();
else
channel << str;
}
if (endOfLine)
channel << endl;
else
channel << ',';
return channel.good();
}
PTabDelimitedFormat::PTabDelimitedFormat()
{
}
PTabDelimitedFormat::PTabDelimitedFormat(const PStringArray & headings)
: PTextDataFormat(headings)
{
}
int PTabDelimitedFormat::ReadField(PChannel & channel, PVarType & field, bool autoDetect)
{
PStringStream str;
while (channel.good()) {
int c = channel.get();
if (c == '\r' || c == '\n' || c == '\t') {
field.FromString(str, autoDetect);
return c == '\t' ? 0 : 1;
}
str << (char)c;
}
return -1;
}
bool PTabDelimitedFormat::WriteField(PChannel & channel, const PVarType & field, bool endOfLine)
{
channel << field;
if (endOfLine)
channel << endl;
else
channel << '\t';
return channel.good();
}
PTextDataFile::PTextDataFile(PTextDataFormatPtr format)
: m_format(format)
, m_formatting(false)
, m_needToWriteHeadings(true)
{
}
PTextDataFile::PTextDataFile(const PFilePath & name, OpenMode mode, OpenOptions opts, PTextDataFormatPtr format)
: m_format(format)
, m_formatting(false)
{
Open(name, mode, opts);
}
bool PTextDataFile::SetFormat(const PTextDataFormatPtr & format)
{
if (IsOpen() || format.IsNULL())
return false;
m_format = format;
return true;
}
bool PTextDataFile::ReadRecord(PVarData::Record & data)
{
if (CheckNotOpen())
return false;
data.RemoveAll();
m_formatting = true;
bool ok = m_format->ReadRecord(*this, data);
m_formatting = false;
return ok;
}
bool PTextDataFile::WriteRecord(const PVarData::Record & data)
{
if (CheckNotOpen())
return false;
PWaitAndSignal lock(m_writeMutex);
m_formatting = true;
if (m_needToWriteHeadings) {
if (m_format->GetHeadings().IsEmpty())
m_format->SetHeadings(data.GetKeys());
if (!m_format->WriteHeadings(*this))
return false;
m_needToWriteHeadings = false;
}
bool ok = m_format->WriteRecord(*this, data);
m_formatting = false;
return ok;
}
bool PTextDataFile::ReadObject(PVarData::Object & obj)
{
if (CheckNotOpen())
return false;
m_formatting = true;
bool ok = m_format->ReadRecord(*this, obj.GetMemberValues());
m_formatting = false;
return ok;
}
bool PTextDataFile::WriteObject(const PVarData::Object & obj)
{
if (CheckNotOpen())
return false;
PWaitAndSignal lock(m_writeMutex);
m_formatting = true;
if (m_needToWriteHeadings) {
m_format->SetHeadings(obj.GetMemberNames());
if (!m_format->WriteHeadings(*this))
return false;
m_needToWriteHeadings = false;
}
bool ok = m_format->WriteRecord(*this, obj.GetMemberValues());
m_formatting = false;
return ok;
}
bool PTextDataFile::InternalOpen(OpenMode mode, OpenOptions opts, PFileInfo::Permissions permissions)
{
if (!PAssert(mode != ReadWrite, PInvalidParameter))
return false;
if (m_format.IsNULL()) {
if (GetFilePath().GetType() == ".csv")
m_format = new PCommaSeparatedVariableFormat();
else if (GetFilePath().GetType() == ".txt" || GetFilePath().GetType() == ".tsv")
m_format = new PTabDelimitedFormat();
else
return false;
}
if (!PTextFile::InternalOpen(mode, opts, permissions))
return false;
if (mode == WriteOnly) {
m_needToWriteHeadings = true;
return true;
}
m_formatting = true;
bool ok = false;
if (m_format.IsNULL()) {
bool hadComma = false;
for (;;) {
char c;
if (!Read(&c, 1))
break;
if (c == '\t') {
SetPosition(0);
m_format = new PTabDelimitedFormat;
break;
}
if (c == '\n') {
SetPosition(0);
break;
}
if (c == ',')
hadComma = true;
}
if (m_format.IsNULL()) {
if (!hadComma)
return false;
m_format = new PCommaSeparatedVariableFormat();
}
}
else
ok = !m_format->GetHeadings().IsEmpty();
if (!ok)
ok = m_format->ReadHeadings(*this);
m_formatting = false;
return ok;
}
PBoolean PTextDataFile::Read(void * buf, PINDEX len)
{
return m_formatting && PTextFile::Read(buf, len);
}
int PTextDataFile::ReadChar()
{
return -1;
}
PBoolean PTextDataFile::ReadBlock(void *, PINDEX)
{
return false;
}
PString PTextDataFile::ReadString(PINDEX)
{
return PString::Empty();
}
PBoolean PTextDataFile::Write(const void * buf, PINDEX len)
{
return m_formatting && PTextFile::Write(buf, len);
}
PBoolean PTextDataFile::WriteChar(int)
{
return false;
}
PBoolean PTextDataFile::WriteString(const PString &)
{
return false;
}
| 20.284424
| 122
| 0.638883
|
suxinde2009
|
3b1700f1a6320e5bec8ea7b1325d8af1c105c40b
| 1,120
|
cpp
|
C++
|
LeetCode/665Non-decreasing Array.cpp
|
zhchuu/OJ-Solutions
|
09e1c18104db35d7c6919257ebaa0f170f54796c
|
[
"MIT"
] | null | null | null |
LeetCode/665Non-decreasing Array.cpp
|
zhchuu/OJ-Solutions
|
09e1c18104db35d7c6919257ebaa0f170f54796c
|
[
"MIT"
] | null | null | null |
LeetCode/665Non-decreasing Array.cpp
|
zhchuu/OJ-Solutions
|
09e1c18104db35d7c6919257ebaa0f170f54796c
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
bool isIncreasing(vector<int>& nums)
{
for (int i = 0; i < nums.size() - 1; i++) {
if (nums[i] > nums[i + 1])
return false;
}
return true;
}
bool checkPossibility(vector<int>& nums)
{
int modified = 0, i;
int temp;
vector<int>::iterator it;
for (i = 0; i < nums.size() - 1; i++) {
if (nums[i] > nums[i + 1])
{
temp = nums[i];
it = nums.begin() + i;
nums.erase(it);
if (isIncreasing(nums))
return true;
else {
nums.insert(nums.begin() + i, temp);
temp = nums[i + 1];
it = nums.begin() + i + 1;
nums.erase(it);
if (isIncreasing(nums))
return true;
else
return false;
}
}//if
}//for
return true;
}
int main()
{
vector<int> test0 = { 4,2,3 };
vector<int> test1 = { 4,3,2 };
vector<int> test2 = { 5,1,9 };
vector<int> test3 = { 4,5,1,6 };
vector<int> test4 = { 1,2,3 };
vector<int> t[5] = { test0,test1,test2,test3,test4 };
for (int i = 0; i < 5; i++)
{
if (checkPossibility(t[i])) {
printf("%d + true\n", i);
}
else {
printf("%d + false\n", i);
}
}
}
| 19.649123
| 54
| 0.546429
|
zhchuu
|
3b17e9e50f5e642166a51cf5a7d96726f77fd3ed
| 38,117
|
cpp
|
C++
|
src/library/renderbuffer.cpp
|
flubbe/swr
|
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
|
[
"MIT"
] | 1
|
2022-02-15T21:00:31.000Z
|
2022-02-15T21:00:31.000Z
|
src/library/renderbuffer.cpp
|
flubbe/swr
|
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
|
[
"MIT"
] | null | null | null |
src/library/renderbuffer.cpp
|
flubbe/swr
|
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
|
[
"MIT"
] | null | null | null |
/**
* swr - a software rasterizer
*
* frame buffer buffer implementation.
*
* \author Felix Lubbe
* \copyright Copyright (c) 2021
* \license Distributed under the MIT software license (see accompanying LICENSE.txt).
*/
/* user headers. */
#include "swr_internal.h"
namespace swr
{
namespace impl
{
/*
* helper lambdas.
* !!fixme: these are duplicated in fragment.cpp
*/
static auto to_uint32_mask = [](bool b) -> std::uint32_t
{
return ~(static_cast<std::uint32_t>(b) - 1);
};
static auto set_uniform_mask = [](bool mask[4], bool v)
{
mask[0] = mask[1] = mask[2] = mask[3] = v;
};
static auto apply_mask = [](bool mask[4], const auto additional_mask[4])
{
mask[0] &= static_cast<bool>(additional_mask[0]);
mask[1] &= static_cast<bool>(additional_mask[1]);
mask[2] &= static_cast<bool>(additional_mask[2]);
mask[3] &= static_cast<bool>(additional_mask[3]);
};
/*
* attachment_texture.
*/
bool attachment_texture::is_valid() const
{
if(tex_id == default_tex_id || tex == nullptr || info.data_ptr == nullptr)
{
return false;
}
if(level >= tex->data.data_ptrs.size())
{
return false;
}
if(tex_id >= global_context->texture_2d_storage.size())
{
return false;
}
if(!global_context->texture_2d_storage[tex_id])
{
return false;
}
return global_context->texture_2d_storage[tex_id].get() == tex && tex_id == tex->id && info.data_ptr == tex->data.data_ptrs[level];
}
#if defined(SWR_USE_MORTON_CODES) && 0
template<>
void scissor_clear_buffer(ml::vec4 clear_value, attachment_info<ml::vec4>& info, const utils::rect& scissor_box)
{
int x_min = std::min(std::max(0, scissor_box.x_min), info.width);
int x_max = std::max(0, std::min(scissor_box.x_max, info.width));
int y_min = std::min(std::max(0, scissor_box.y_max), info.height);
int y_max = std::max(0, std::min(scissor_box.y_min, info.height));
const auto row_size = x_max - x_min;
const auto skip = info.pitch - row_size;
auto ptr = info.data_ptr + y_min * info.pitch + x_min;
for(int y = y_min; y < y_max; ++y)
{
for(int i = 0; i < row_size; ++i)
{
*ptr++ = clear_value;
}
ptr += skip;
}
}
#elif 0
template<typename T>
static void scissor_clear_buffer_morton(T clear_value, attachment_info<T>& info, const utils::rect& scissor_box)
{
int x_min = std::min(std::max(0, scissor_box.x_min), info.width);
int x_max = std::max(0, std::min(scissor_box.x_max, info.width));
int y_min = std::min(std::max(info.height - scissor_box.y_max, 0), info.height);
int y_max = std::max(0, std::min(info.height - scissor_box.y_min, info.height));
for(int y = y_min; y < y_max; ++y)
{
for(int x = x_min; x < x_max; ++x)
{
*(info.data_ptr + libmorton::morton2D_32_encode(x, y)) = clear_value;
}
}
}
#endif
/*
* default framebuffer.
*/
void default_framebuffer::clear_color(uint32_t attachment, ml::vec4 clear_color)
{
if(attachment == 0)
{
auto& info = color_buffer.info;
utils::memset32(info.data_ptr, color_buffer.converter.to_pixel(clear_color), info.pitch * info.height);
}
}
void default_framebuffer::clear_color(uint32_t attachment, ml::vec4 clear_color, const utils::rect& rect)
{
if(attachment == 0)
{
auto clear_value = color_buffer.converter.to_pixel(clear_color);
int x_min = std::min(std::max(0, rect.x_min), color_buffer.info.width);
int x_max = std::max(0, std::min(rect.x_max, color_buffer.info.width));
int y_min = std::min(std::max(color_buffer.info.height - rect.y_max, 0), color_buffer.info.height);
int y_max = std::max(0, std::min(color_buffer.info.height - rect.y_min, color_buffer.info.height));
const auto row_size = (x_max - x_min) * sizeof(uint32_t);
auto ptr = reinterpret_cast<uint8_t*>(color_buffer.info.data_ptr) + y_min * color_buffer.info.pitch + x_min * sizeof(uint32_t);
for(int y = y_min; y < y_max; ++y)
{
utils::memset32(ptr, *reinterpret_cast<uint32_t*>(&clear_value), row_size);
ptr += color_buffer.info.pitch;
}
}
}
void default_framebuffer::clear_depth(ml::fixed_32_t clear_depth)
{
auto& info = depth_buffer.info;
if(info.data_ptr)
{
utils::memset32(reinterpret_cast<uint32_t*>(info.data_ptr), ml::unwrap(clear_depth), info.pitch * info.height);
}
}
void default_framebuffer::clear_depth(ml::fixed_32_t clear_depth, const utils::rect& rect)
{
int x_min = std::min(std::max(0, rect.x_min), depth_buffer.info.width);
int x_max = std::max(0, std::min(rect.x_max, depth_buffer.info.width));
int y_min = std::min(std::max(depth_buffer.info.height - rect.y_max, 0), depth_buffer.info.height);
int y_max = std::max(0, std::min(depth_buffer.info.height - rect.y_min, depth_buffer.info.height));
const auto row_size = (x_max - x_min) * sizeof(ml::fixed_32_t);
auto ptr = reinterpret_cast<uint8_t*>(depth_buffer.info.data_ptr) + y_min * depth_buffer.info.pitch + x_min * sizeof(ml::fixed_32_t);
for(int y = y_min; y < y_max; ++y)
{
utils::memset32(ptr, *reinterpret_cast<uint32_t*>(&clear_depth), row_size);
ptr += depth_buffer.info.pitch;
}
}
void default_framebuffer::merge_color(uint32_t attachment, int x, int y, const fragment_output& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment != 0)
{
return;
}
if(frag.write_flags & fragment_output::fof_write_color)
{
// convert color to output format.
uint32_t write_color = color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color));
// alpha blending.
uint32_t* color_buffer_ptr = color_buffer.info.data_ptr + y * color_buffer.info.width + x;
if(do_blend)
{
write_color = swr::output_merger::blend(color_buffer.converter, blend_src, blend_dst, write_color, *color_buffer_ptr);
}
// write color.
*color_buffer_ptr = write_color;
}
}
void default_framebuffer::merge_color_block(uint32_t attachment, int x, int y, const fragment_output_block& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment != 0)
{
return;
}
// generate write mask.
uint32_t color_write_mask[4] = {to_uint32_mask(frag.write_color[0]), to_uint32_mask(frag.write_color[1]), to_uint32_mask(frag.write_color[2]), to_uint32_mask(frag.write_color[3])};
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
if(frag.write_color[0] || frag.write_color[1] || frag.write_color[2] || frag.write_color[3])
{
// convert color to output format.
DECLARE_ALIGNED_ARRAY4(uint32_t, write_color) = {
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[0])),
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[1])),
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[2])),
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[3]))};
// alpha blending.
uint32_t* color_buffer_ptr[4] = {
color_buffer.info.data_ptr + coords[0].y * color_buffer.info.width + coords[0].x,
color_buffer.info.data_ptr + coords[1].y * color_buffer.info.width + coords[1].x,
color_buffer.info.data_ptr + coords[2].y * color_buffer.info.width + coords[2].x,
color_buffer.info.data_ptr + coords[3].y * color_buffer.info.width + coords[3].x};
DECLARE_ALIGNED_ARRAY4(uint32_t, color_buffer_values) = {
*color_buffer_ptr[0], *color_buffer_ptr[1], *color_buffer_ptr[2], *color_buffer_ptr[3]};
if(do_blend)
{
// note: when compiling with SSE/SIMD enabled, make sure that src/dest/out are aligned on 16-byte boundaries.
swr::output_merger::blend_block(color_buffer.converter, blend_src, blend_dst, write_color, color_buffer_values, write_color);
}
// write color.
*(color_buffer_ptr[0]) = (color_buffer_values[0] & ~color_write_mask[0]) | (write_color[0] & color_write_mask[0]);
*(color_buffer_ptr[1]) = (color_buffer_values[1] & ~color_write_mask[1]) | (write_color[1] & color_write_mask[1]);
*(color_buffer_ptr[2]) = (color_buffer_values[2] & ~color_write_mask[2]) | (write_color[2] & color_write_mask[2]);
*(color_buffer_ptr[3]) = (color_buffer_values[3] & ~color_write_mask[3]) | (write_color[3] & color_write_mask[3]);
}
}
void default_framebuffer::depth_compare_write(int x, int y, float depth_value, comparison_func depth_func, bool write_depth, bool& write_mask)
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
write_mask = false;
return;
}
write_mask = write_depth;
// if no depth buffer was created, accept.
if(!depth_buffer.info.data_ptr)
{
return;
}
// read and compare depth buffer.
ml::fixed_32_t* depth_buffer_ptr = depth_buffer.info.data_ptr + y * depth_buffer.info.width + x;
ml::fixed_32_t old_depth_value = *depth_buffer_ptr;
ml::fixed_32_t new_depth_value{depth_value};
// basic comparisons for depth test.
bool depth_compare[] = {
true, /* pass */
false, /* fail */
new_depth_value == old_depth_value, /* equal */
false, /* not_equal */
new_depth_value < old_depth_value, /* less */
false, /* less_equal */
false, /* greater */
false /* greater_equal */
};
// compound comparisons for depth test.
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
// generate write mask for this fragment.
write_mask &= depth_compare[static_cast<std::uint32_t>(depth_func)];
// write depth value.
uint32_t depth_write_mask = to_uint32_mask(write_depth && write_mask);
*depth_buffer_ptr = ml::wrap((ml::unwrap(*depth_buffer_ptr) & ~depth_write_mask) | (ml::unwrap(new_depth_value) & depth_write_mask));
}
void default_framebuffer::depth_compare_write_block(int x, int y, float depth_value[4], comparison_func depth_func, bool write_depth, bool write_mask[4])
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
set_uniform_mask(write_mask, false);
return;
}
// if no depth buffer was created, accept.
if(!depth_buffer.info.data_ptr)
{
// the write mask is initialized with "accept all".
return;
}
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
// read and compare depth buffer.
ml::fixed_32_t* depth_buffer_ptr[4] = {
depth_buffer.info.data_ptr + coords[0].y * depth_buffer.info.width + coords[0].x,
depth_buffer.info.data_ptr + coords[1].y * depth_buffer.info.width + coords[1].x,
depth_buffer.info.data_ptr + coords[2].y * depth_buffer.info.width + coords[2].x,
depth_buffer.info.data_ptr + coords[3].y * depth_buffer.info.width + coords[3].x};
ml::fixed_32_t old_depth_value[4] = {*depth_buffer_ptr[0], *depth_buffer_ptr[1], *depth_buffer_ptr[2], *depth_buffer_ptr[3]};
ml::fixed_32_t new_depth_value[4] = {depth_value[0], depth_value[1], depth_value[2], depth_value[3]};
// basic comparisons for depth test.
bool depth_compare[][4] = {
{true, true, true, true}, /* pass */
{false, false, false, false}, /* fail */
{new_depth_value[0] == old_depth_value[0], new_depth_value[1] == old_depth_value[1], new_depth_value[2] == old_depth_value[2], new_depth_value[3] == old_depth_value[3]}, /* equal */
{false, false, false, false}, /* not_equal */
{new_depth_value[0] < old_depth_value[0], new_depth_value[1] < old_depth_value[1], new_depth_value[2] < old_depth_value[2], new_depth_value[3] < old_depth_value[3]}, /* less */
{false, false, false, false}, /* less -<equal */
{false, false, false, false}, /* greater */
{false, false, false, false} /* greater_equal */
};
// compound comparisons for depth test.
for(int k = 0; k < 4; ++k)
{
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)][k] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
}
bool depth_mask[4] = {
depth_compare[static_cast<std::uint32_t>(depth_func)][0], depth_compare[static_cast<std::uint32_t>(depth_func)][1], depth_compare[static_cast<std::uint32_t>(depth_func)][2], depth_compare[static_cast<std::uint32_t>(depth_func)][3]};
apply_mask(write_mask, depth_mask);
// write depth.
uint32_t depth_write_mask[4] = {to_uint32_mask(write_mask[0] && write_depth), to_uint32_mask(write_mask[1] && write_depth), to_uint32_mask(write_mask[2] && write_depth), to_uint32_mask(write_mask[3] && write_depth)};
*(depth_buffer_ptr[0]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[0])) & ~depth_write_mask[0]) | (ml::unwrap(new_depth_value[0]) & depth_write_mask[0]));
*(depth_buffer_ptr[1]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[1])) & ~depth_write_mask[1]) | (ml::unwrap(new_depth_value[1]) & depth_write_mask[1]));
*(depth_buffer_ptr[2]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[2])) & ~depth_write_mask[2]) | (ml::unwrap(new_depth_value[2]) & depth_write_mask[2]));
*(depth_buffer_ptr[3]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[3])) & ~depth_write_mask[3]) | (ml::unwrap(new_depth_value[3]) & depth_write_mask[3]));
}
/*
* framebuffer_object
*/
void framebuffer_object::clear_color(uint32_t attachment, ml::vec4 clear_color)
{
if(attachment < color_attachments.size() && color_attachments[attachment])
{
// this also clears mipmaps, if present
auto& info = color_attachments[attachment]->info;
#ifdef SWR_USE_SIMD
utils::memset128(info.data_ptr, *reinterpret_cast<__m128i*>(&clear_color.data), info.pitch * info.height * sizeof(__m128));
#else /* SWR_USE_SIMD */
std::fill_n(info.data_ptr, info.pitch * info.height, clear_color);
#endif /* SWR_USE_SIMD */
}
}
void framebuffer_object::clear_color(uint32_t attachment, ml::vec4 clear_color, const utils::rect& rect)
{
if(attachment < color_attachments.size() && color_attachments[attachment])
{
#ifdef SWR_USE_MORTON_CODES
auto& info = color_attachments[attachment]->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(0, rect.y_min), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
for(int x = x_min; x < x_max; ++x)
{
for(int y = y_min; y < y_max; ++y)
{
*(info.data_ptr + libmorton::morton2D_32_encode(x, y)) = clear_color;
}
}
#else
auto& info = color_attachments[attachment]->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(0, rect.y_min), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
const auto row_size = x_max - x_min;
# ifdef SWR_USE_SIMD
auto ptr = info.data_ptr + y_min * info.pitch + x_min;
for(int y = y_min; y < y_max; ++y)
{
utils::memset128(ptr, *reinterpret_cast<__m128i*>(&clear_color.data), row_size * sizeof(__m128));
ptr += info.pitch;
}
# else /* SWR_USE_SIMD */
const auto skip = info.pitch - row_size;
auto ptr = info.data_ptr + y_min * info.pitch + x_min;
for(int y = y_min; y < y_max; ++y)
{
for(int i = 0; i < row_size; ++i)
{
*ptr++ = clear_color;
}
ptr += skip;
}
# endif /* SWR_USE_SIMD */
#endif /* SWR_USE_MORTON_CODES */
}
}
void framebuffer_object::clear_depth(ml::fixed_32_t clear_depth)
{
if(depth_attachment)
{
auto& info = depth_attachment->info;
utils::memset32(reinterpret_cast<uint32_t*>(info.data_ptr), ml::unwrap(clear_depth), info.pitch * info.height);
}
}
void framebuffer_object::clear_depth(ml::fixed_32_t clear_depth, const utils::rect& rect)
{
if(depth_attachment)
{
#ifdef SWR_USE_MORTON_CODES
auto& info = depth_attachment->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(rect.y_min, 0), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
for(int x = x_min; x < x_max; ++x)
{
for(int y = y_min; y < y_max; ++y)
{
*(info.data_ptr + libmorton::morton2D_32_encode(x, y)) = clear_depth;
}
}
#else
auto& info = depth_attachment->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(rect.y_min, 0), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
const auto row_size = (x_max - x_min) * sizeof(ml::fixed_32_t);
auto ptr = reinterpret_cast<uint8_t*>(info.data_ptr) + y_min * info.pitch + x_min * sizeof(ml::fixed_32_t);
for(int y = y_min; y < y_max; ++y)
{
utils::memset32(ptr, *reinterpret_cast<uint32_t*>(&clear_depth), row_size);
ptr += info.pitch;
}
#endif /* SWR_USE_MORTON_CODES */
}
}
void framebuffer_object::merge_color(uint32_t attachment, int x, int y, const fragment_output& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment > color_attachments.size() || !color_attachments[attachment])
{
return;
}
if(frag.write_flags & fragment_output::fof_write_color)
{
ml::vec4 write_color{ml::clamp_to_unit_interval(frag.color)};
ml::vec4* data_ptr = color_attachments[attachment]->info.data_ptr;
#ifndef SWR_USE_MORTON_CODES
int pitch = color_attachments[attachment]->info.pitch;
#endif
// alpha blending.
#ifdef SWR_USE_MORTON_CODES
ml::vec4* color_buffer_ptr = data_ptr + libmorton::morton2D_32_encode(x, y);
#else
ml::vec4* color_buffer_ptr = data_ptr + y * pitch + x;
#endif
if(do_blend)
{
write_color = swr::output_merger::blend(blend_src, blend_dst, write_color, *color_buffer_ptr);
}
// write color.
*color_buffer_ptr = write_color;
}
}
void framebuffer_object::merge_color_block(uint32_t attachment, int x, int y, const fragment_output_block& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment > color_attachments.size() || !color_attachments[attachment])
{
return;
}
if(frag.write_color[0] || frag.write_color[1] || frag.write_color[2] || frag.write_color[3])
{
// convert color to output format.
ml::vec4 write_color[4] = {
ml::clamp_to_unit_interval(frag.color[0]),
ml::clamp_to_unit_interval(frag.color[1]),
ml::clamp_to_unit_interval(frag.color[2]),
ml::clamp_to_unit_interval(frag.color[3])};
ml::vec4* data_ptr = color_attachments[attachment]->info.data_ptr;
#ifndef SWR_USE_MORTON_CODES
int pitch = color_attachments[attachment]->info.pitch;
#endif
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
// alpha blending.
#ifdef SWR_USE_MORTON_CODES
ml::vec4* color_buffer_ptrs[4] = {
data_ptr + libmorton::morton2D_32_encode(coords[0].x, coords[0].y),
data_ptr + libmorton::morton2D_32_encode(coords[1].x, coords[1].y),
data_ptr + libmorton::morton2D_32_encode(coords[2].x, coords[2].y),
data_ptr + libmorton::morton2D_32_encode(coords[3].x, coords[3].y)};
#else
ml::vec4* color_buffer_ptrs[4] = {
data_ptr + coords[0].y * pitch + coords[0].x,
data_ptr + coords[1].y * pitch + coords[1].x,
data_ptr + coords[2].y * pitch + coords[2].x,
data_ptr + coords[3].y * pitch + coords[3].x};
#endif
ml::vec4 color_buffer_values[4] = {
*color_buffer_ptrs[0], *color_buffer_ptrs[1], *color_buffer_ptrs[2], *color_buffer_ptrs[3]};
if(do_blend)
{
swr::output_merger::blend_block(blend_src, blend_dst, write_color, color_buffer_values, write_color);
}
// write color.
#define CONDITIONAL_WRITE(condition, write_target, write_source) \
if(condition) \
{ \
write_target = write_source; \
}
CONDITIONAL_WRITE(frag.write_color[0], *(color_buffer_ptrs[0]), write_color[0]);
CONDITIONAL_WRITE(frag.write_color[1], *(color_buffer_ptrs[1]), write_color[1]);
CONDITIONAL_WRITE(frag.write_color[2], *(color_buffer_ptrs[2]), write_color[2]);
CONDITIONAL_WRITE(frag.write_color[3], *(color_buffer_ptrs[3]), write_color[3]);
#undef CONDITIONAL_WRITE
}
}
//!!fixme: this is almost exactly the same as default_framebuffer::depth_compare_write.
void framebuffer_object::depth_compare_write(int x, int y, float depth_value, comparison_func depth_func, bool write_depth, bool& write_mask)
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
write_mask = false;
return;
}
write_mask = true;
// if no depth buffer was created, accept.
if(!depth_attachment || !depth_attachment->info.data_ptr)
{
return;
}
// read and compare depth buffer.
#ifdef SWR_USE_MORTON_CODES
ml::fixed_32_t* depth_buffer_ptr = depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(x, y);
#else
ml::fixed_32_t* depth_buffer_ptr = depth_attachment->info.data_ptr + y * depth_attachment->info.width + x;
#endif
ml::fixed_32_t old_depth_value = *depth_buffer_ptr;
ml::fixed_32_t new_depth_value{depth_value};
// basic comparisons for depth test.
bool depth_compare[] = {
true, /* pass */
false, /* fail */
new_depth_value == old_depth_value, /* equal */
false, /* not_equal */
new_depth_value < old_depth_value, /* less */
false, /* less_equal */
false, /* greater */
false /* greater_equal */
};
// compound comparisons for depth test.
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
// generate write mask for this fragment.
write_mask &= depth_compare[static_cast<std::uint32_t>(depth_func)];
// write depth value.
uint32_t depth_write_mask = to_uint32_mask(write_depth && write_mask);
*depth_buffer_ptr = ml::wrap((ml::unwrap(*depth_buffer_ptr) & ~depth_write_mask) | (ml::unwrap(new_depth_value) & depth_write_mask));
}
//!!fixme: this is almost exactly the same as default_framebuffer::depth_compare_write_block.
void framebuffer_object::depth_compare_write_block(int x, int y, float depth_value[4], comparison_func depth_func, bool write_depth, bool write_mask[4])
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
set_uniform_mask(write_mask, false);
return;
}
// if no depth buffer was created, accept.
if(!depth_attachment || !depth_attachment->info.data_ptr)
{
// the write mask is initialized with "accept all".
return;
}
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
// read and compare depth buffer.
#ifdef SWR_USE_MORTON_CODES
ml::fixed_32_t* depth_buffer_ptr[4] = {
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[0].x, coords[0].y),
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[1].x, coords[1].y),
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[2].x, coords[2].y),
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[3].x, coords[3].y)};
#else
ml::fixed_32_t* depth_buffer_ptr[4] = {
depth_attachment->info.data_ptr + coords[0].y * depth_attachment->info.width + coords[0].x,
depth_attachment->info.data_ptr + coords[1].y * depth_attachment->info.width + coords[1].x,
depth_attachment->info.data_ptr + coords[2].y * depth_attachment->info.width + coords[2].x,
depth_attachment->info.data_ptr + coords[3].y * depth_attachment->info.width + coords[3].x};
#endif
ml::fixed_32_t old_depth_value[4] = {*depth_buffer_ptr[0], *depth_buffer_ptr[1], *depth_buffer_ptr[2], *depth_buffer_ptr[3]};
ml::fixed_32_t new_depth_value[4] = {depth_value[0], depth_value[1], depth_value[2], depth_value[3]};
// basic comparisons for depth test.
bool depth_compare[][4] = {
{true, true, true, true}, /* pass */
{false, false, false, false}, /* fail */
{new_depth_value[0] == old_depth_value[0], new_depth_value[1] == old_depth_value[1], new_depth_value[2] == old_depth_value[2], new_depth_value[3] == old_depth_value[3]}, /* equal */
{false, false, false, false}, /* not_equal */
{new_depth_value[0] < old_depth_value[0], new_depth_value[1] < old_depth_value[1], new_depth_value[2] < old_depth_value[2], new_depth_value[3] < old_depth_value[3]}, /* less */
{false, false, false, false}, /* less -<equal */
{false, false, false, false}, /* greater */
{false, false, false, false} /* greater_equal */
};
// compound comparisons for depth test.
for(int k = 0; k < 4; ++k)
{
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)][k] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
}
bool depth_mask[4] = {
depth_compare[static_cast<std::uint32_t>(depth_func)][0], depth_compare[static_cast<std::uint32_t>(depth_func)][1], depth_compare[static_cast<std::uint32_t>(depth_func)][2], depth_compare[static_cast<std::uint32_t>(depth_func)][3]};
apply_mask(write_mask, depth_mask);
// write depth.
uint32_t depth_write_mask[4] = {to_uint32_mask(write_mask[0] && write_depth), to_uint32_mask(write_mask[1] && write_depth), to_uint32_mask(write_mask[2] && write_depth), to_uint32_mask(write_mask[3] && write_depth)};
*(depth_buffer_ptr[0]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[0])) & ~depth_write_mask[0]) | (ml::unwrap(new_depth_value[0]) & depth_write_mask[0]));
*(depth_buffer_ptr[1]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[1])) & ~depth_write_mask[1]) | (ml::unwrap(new_depth_value[1]) & depth_write_mask[1]));
*(depth_buffer_ptr[2]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[2])) & ~depth_write_mask[2]) | (ml::unwrap(new_depth_value[2]) & depth_write_mask[2]));
*(depth_buffer_ptr[3]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[3])) & ~depth_write_mask[3]) | (ml::unwrap(new_depth_value[3]) & depth_write_mask[3]));
}
} /* namespace impl */
/*
* framebuffer object interface.
*/
/** the default framebuffer has id 0. this constant is mostly here to make the code below more readable. */
constexpr uint32_t default_framebuffer_id = 0;
/** two more functions for handling the default_framebuffer_id case. */
static auto id_to_slot = [](std::uint32_t id) -> std::uint32_t
{ return id - 1; };
static auto slot_to_id = [](std::uint32_t slot) -> std::uint32_t
{ return slot + 1; };
uint32_t CreateFramebufferObject()
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
// set up a new framebuffer.
auto slot = context->framebuffer_objects.push({});
auto* new_fbo = &context->framebuffer_objects[slot];
new_fbo->reset(slot);
return slot_to_id(slot);
}
void ReleaseFramebufferObject(uint32_t id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// do not release default framebuffer.
return;
}
auto slot = id_to_slot(id);
if(slot < context->framebuffer_objects.size() && !context->framebuffer_objects.is_free(slot))
{
// check if we are bound to a target and reset the target if necessary.
if(context->states.draw_target == &context->framebuffer_objects[slot])
{
context->states.draw_target = &context->framebuffer;
}
// release framebuffer object.
context->framebuffer_objects[slot].reset();
context->framebuffer_objects.free(slot);
}
}
void BindFramebufferObject(framebuffer_target target, uint32_t id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// bind the default framebuffer.
if(target == framebuffer_target::draw || target == framebuffer_target::draw_read)
{
context->states.draw_target = &context->framebuffer;
}
if(target == framebuffer_target::read || target == framebuffer_target::draw_read)
{
/* unimplemented. */
}
return;
}
// check that the id is valid.
auto slot = id_to_slot(id);
if(slot >= context->framebuffer_objects.size() || context->framebuffer_objects.is_free(slot))
{
context->last_error = error::invalid_operation;
return;
}
if(target == framebuffer_target::draw || target == framebuffer_target::draw_read)
{
context->states.draw_target = &context->framebuffer_objects[slot];
}
if(target == framebuffer_target::read || target == framebuffer_target::draw_read)
{
/* unimplemented. */
}
}
void FramebufferTexture(uint32_t id, framebuffer_attachment attachment, uint32_t attachment_id, uint32_t level)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// textures cannot be bound to the default framebuffer.
context->last_error = error::invalid_value;
return;
}
int numeric_attachment = static_cast<int>(attachment);
if(numeric_attachment >= static_cast<int>(framebuffer_attachment::color_attachment_0) && numeric_attachment <= static_cast<int>(framebuffer_attachment::color_attachment_7))
{
// use texture as color buffer.
// get framebuffer object.
auto slot = id_to_slot(id);
if(slot >= context->framebuffer_objects.size() || context->framebuffer_objects.is_free(slot))
{
context->last_error = error::invalid_value;
return;
}
auto fbo = &context->framebuffer_objects[slot];
// get texture.
auto tex_id = attachment_id;
if(tex_id >= context->texture_2d_storage.size() || context->texture_2d_storage.is_free(tex_id))
{
context->last_error = error::invalid_value;
return;
}
// associate texture to fbo.
fbo->attach_texture(attachment, context->texture_2d_storage[tex_id].get(), level);
}
else
{
// unknown attachment.
context->last_error = error::invalid_value;
}
}
uint32_t CreateDepthRenderbuffer(uint32_t width, uint32_t height)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
auto slot = context->depth_attachments.push({});
context->depth_attachments[slot].allocate(width, height);
return slot;
}
void ReleaseDepthRenderbuffer(uint32_t id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id < context->depth_attachments.size() && !context->depth_attachments.is_free(id))
{
context->depth_attachments.free(id);
}
}
void FramebufferRenderbuffer(uint32_t id, framebuffer_attachment attachment, uint32_t attachment_id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// don't operate on the default framebuffer.
context->last_error = error::invalid_value;
return;
}
if(attachment != framebuffer_attachment::depth_attachment)
{
// currently only depth attachments are supported.
context->last_error = error::invalid_value;
return;
}
if(attachment_id >= context->depth_attachments.size() || context->depth_attachments.is_free(attachment_id))
{
context->last_error = error::invalid_value;
return;
}
auto slot = id_to_slot(id);
if(slot >= context->framebuffer_objects.size() || context->framebuffer_objects.is_free(slot))
{
context->last_error = error::invalid_value;
return;
}
auto& fbo = context->framebuffer_objects[slot];
fbo.attach_depth(&context->depth_attachments[attachment_id]);
}
} /* namespace swr */
| 42.541295
| 242
| 0.626859
|
flubbe
|
3b1857c8de1641ca1ae73003d9dddc9b264840c5
| 3,185
|
cpp
|
C++
|
src/gdx-cpp/audio/analysis/KissFFT.cpp
|
aevum/libgdx-cpp
|
88603a59af4d915259a841e13ce88f65c359f0df
|
[
"Apache-2.0"
] | 77
|
2015-01-28T17:21:49.000Z
|
2022-02-17T17:59:21.000Z
|
src/gdx-cpp/audio/analysis/KissFFT.cpp
|
aevum/libgdx-cpp
|
88603a59af4d915259a841e13ce88f65c359f0df
|
[
"Apache-2.0"
] | 5
|
2015-03-22T23:14:54.000Z
|
2020-09-18T13:26:03.000Z
|
src/gdx-cpp/audio/analysis/KissFFT.cpp
|
aevum/libgdx-cpp
|
88603a59af4d915259a841e13ce88f65c359f0df
|
[
"Apache-2.0"
] | 24
|
2015-02-12T04:34:37.000Z
|
2021-06-19T17:05:23.000Z
|
/*
Copyright 2011 Aevum Software aevum @ aevumlab.com
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.
@author Victor Vicente de Carvalho victor.carvalho@aevumlab.com
@author Ozires Bortolon de Faria ozires@aevumlab.com
*/
#include "KissFFT.hpp"
#include "kissfft/kiss_fftr.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <vector>
#define MAX_SHORT 32767.0f //TODO check this
using namespace gdx;
struct KissFFTO
{
kiss_fftr_cfg config;
kiss_fft_cpx* spectrum;
int numSamples;
};
void KissFFT::spectrum (std::vector<short>& samples, std::vector<float>& spectrumP) {
spectrum(handle, samples, spectrumP);
}
void KissFFT::dispose () {
destroy(handle);
}
void KissFFT::getRealPart (std::vector<short>& real) {
getRealPart(handle, real);
}
void KissFFT::getImagPart (std::vector<short>& imag) {
getImagPart(handle, imag);
}
static inline float scale( kiss_fft_scalar val )
{
if( val < 0 )
return val * ( 1 / 32768.0f );
else
return val * ( 1 / 32767.0f );
}
KissFFTO* KissFFT::create (int numSamples)
{
KissFFTO* fft = new KissFFTO();
fft->config = kiss_fftr_alloc(numSamples,0,NULL,NULL);
fft->spectrum = (kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx) * numSamples);
fft->numSamples = numSamples;
return fft;
}
void KissFFT::destroy(KissFFTO* fft)
{
free(fft->config);
free(fft->spectrum);
free(fft);
}
void KissFFT::getRealPart(KissFFTO* fft, std::vector<short>& target)
{
for( int i = 0; i < fft->numSamples / 2; i++ )
target[i] = fft->spectrum[i].r;
}
void KissFFT::getImagPart(KissFFTO* fft, std::vector<short>& target)
{
for( int i = 0; i < fft->numSamples / 2; i++ )
target[i] = fft->spectrum[i].i;
}
void KissFFT::spectrum(KissFFTO* fft, std::vector< short >& samples2, std::vector< float >& spectrum)
{
kiss_fft_scalar* samples = (kiss_fft_scalar*) &samples[0];
kiss_fftr( fft->config, samples, fft->spectrum );
int len = fft->numSamples / 2 + 1;
for( int i = 0; i < len; i++ )
{
float re = scale(fft->spectrum[i].r) * fft->numSamples;
float im = scale(fft->spectrum[i].i) * fft->numSamples;
if( i > 0 )
spectrum[i] = sqrtf(re*re + im*im) / (fft->numSamples / 2);
else
spectrum[i] = sqrtf(re*re + im*im) / (fft->numSamples);
}
}
| 27.456897
| 102
| 0.592465
|
aevum
|
3b189c776d46b50c7fc9efe23de9a9298b2b3b44
| 1,207
|
cpp
|
C++
|
0644-Maximum Average Subarray II/0644-Maximum Average Subarray II.cpp
|
zhuangli1987/LeetCode-1
|
e81788abf9e95e575140f32a58fe983abc97fa4a
|
[
"MIT"
] | 49
|
2018-05-05T02:53:10.000Z
|
2022-03-30T12:08:09.000Z
|
0601-0700/0644-Maximum Average Subarray II/0644-Maximum Average Subarray II.cpp
|
jolly-fellow/LeetCode
|
ab20b3ec137ed05fad1edda1c30db04ab355486f
|
[
"MIT"
] | 11
|
2017-12-15T22:31:44.000Z
|
2020-10-02T12:42:49.000Z
|
0601-0700/0644-Maximum Average Subarray II/0644-Maximum Average Subarray II.cpp
|
jolly-fellow/LeetCode
|
ab20b3ec137ed05fad1edda1c30db04ab355486f
|
[
"MIT"
] | 28
|
2017-12-05T10:56:51.000Z
|
2022-01-26T18:18:27.000Z
|
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int n = nums.size();
int minNum = INT_MAX, maxNum = INT_MIN;
for (int num : nums) {
minNum = min(minNum, num);
maxNum = max(maxNum, num);
}
double low = minNum, high = maxNum;
while (high - low > 10e-6) {
double mid = (low + high) / 2;
if (available(nums, k, mid)) {
low = mid;
}
else {
high = mid;
}
}
return low;
}
private:
bool available(vector<int>& nums, int k, double target) {
int n = nums.size();
double sum = 0;
for (int i = 0; i < k; ++i) {
sum += nums[i] - target;
}
if (sum >= 0) {
return true;
}
double premin = 0;
double presum = 0;
for (int i = k; i < n; ++i) {
sum += nums[i] - target;
presum += nums[i - k] - target;
premin = min(premin, presum);
if (sum - premin >= 0) {
return true;
}
}
return false;
}
};
| 25.145833
| 61
| 0.400994
|
zhuangli1987
|
3b19c39ea419dc6a928525f68a89e55b9e06fff5
| 1,549
|
cpp
|
C++
|
pihud/src/Event.cpp
|
maximaximal/piga
|
54530c208e59eaaf8d44c1f8d640f5ec028d4126
|
[
"Zlib"
] | 2
|
2015-01-07T18:36:39.000Z
|
2015-01-08T13:54:43.000Z
|
pihud/src/Event.cpp
|
maximaximal/piga
|
54530c208e59eaaf8d44c1f8d640f5ec028d4126
|
[
"Zlib"
] | null | null | null |
pihud/src/Event.cpp
|
maximaximal/piga
|
54530c208e59eaaf8d44c1f8d640f5ec028d4126
|
[
"Zlib"
] | null | null | null |
#include <pihud/Event.hpp>
namespace PiH
{
Event::Event()
{
type = EventType::NotSet;
}
Event::Event(const InputEvent &inputEvent, int playerID)
{
type = EventType::Input;
input = inputEvent;
this->playerID = playerID;
}
Event::Event(const FocusEvent &focusEvent, int playerID)
{
type = EventType::Focus;
focus = focusEvent;
this->playerID = playerID;
}
Event::Event(const PigaEvent &pigaEvent, int playerID)
{
type = EventType::Piga;
piga = pigaEvent;
this->playerID = playerID;
}
Event::Event(const piga::GameEvent &gameEvent, bool focusEvent)
{
playerID = gameEvent.playerID();
if(gameEvent.type() == piga::GameEvent::GameInput && !focusEvent)
{
PigaEvent pigaEvent(gameEvent.gameInput.control(), gameEvent.gameInput.state());
type = EventType::Piga;
piga = pigaEvent;
}
else if(gameEvent.type() == piga::GameEvent::GameInput)
{
if((gameEvent.gameInput.control() == piga::DOWN
|| gameEvent.gameInput.control() == piga::LEFT
|| gameEvent.gameInput.control() == piga::RIGHT
|| gameEvent.gameInput.control() == piga::UP)
&& focusEvent)
{
type = EventType::Focus;
FocusEvent focusEvent(gameEvent);
focus = focusEvent;
}
}
}
Event::~Event()
{
}
}
| 28.163636
| 92
| 0.534538
|
maximaximal
|
3b1ae204503de0594c7fadf3480b605dbfd9d0b9
| 5,731
|
cc
|
C++
|
aux/broker/tests/benchmark/broker-stream-benchmark.cc
|
zpx2012/zeek_3.0.8
|
7a912ebbdd0871838c7fb35538fef467279ec1fe
|
[
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 1
|
2021-03-06T19:51:07.000Z
|
2021-03-06T19:51:07.000Z
|
aux/broker/tests/benchmark/broker-stream-benchmark.cc
|
zpx2012/zeek_3.0.8
|
7a912ebbdd0871838c7fb35538fef467279ec1fe
|
[
"Apache-2.0",
"CC0-1.0",
"MIT"
] | null | null | null |
aux/broker/tests/benchmark/broker-stream-benchmark.cc
|
zpx2012/zeek_3.0.8
|
7a912ebbdd0871838c7fb35538fef467279ec1fe
|
[
"Apache-2.0",
"CC0-1.0",
"MIT"
] | null | null | null |
#include <cstdint>
#include <cstdlib>
#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <caf/atom.hpp>
#include <caf/config_option_adder.hpp>
#include <caf/downstream.hpp>
#include <caf/event_based_actor.hpp>
#include <caf/scoped_actor.hpp>
#include "broker/configuration.hh"
#include "broker/core_actor.hh"
#include "broker/data.hh"
#include "broker/endpoint.hh"
#include "broker/filter_type.hh"
#include "broker/topic.hh"
using std::cout;
using std::cerr;
using std::endl;
using namespace broker;
namespace {
class config : public configuration {
public:
uint16_t port = 0;
std::string host = "localhost";
caf::atom_value mode;
config() {
opt_group{custom_options_, "global"}
.add(mode, "mode,m", "one of 'sink', 'source', 'both', or 'fused'")
.add(port, "port,p", "sets the port for listening or peering")
.add(host, "host,o", "sets the peering with the sink");
}
};
std::atomic<size_t> global_count;
void sink_mode(broker::endpoint& ep, topic t) {
using namespace caf;
auto worker = ep.subscribe(
{t},
[](caf::unit_t&) {
// nop
},
[=](caf::unit_t&, std::vector<data_message>& xs) {
global_count += xs.size();
},
[=](caf::unit_t&, const caf::error&) {
// nop
}
);
scoped_actor self{ep.system()};
self->wait_for(worker);
}
void source_mode(broker::endpoint& ep, topic t) {
using namespace caf;
auto msg = make_data_message(t, "Lorem ipsum dolor sit amet.");
auto worker = ep.publish_all(
[](caf::unit_t&) {
// nop
},
[=](caf::unit_t&, downstream<data_message>& out, size_t num) {
for (size_t i = 0; i < num; ++i)
out.push(msg);
global_count += num;
},
[=](const caf::unit_t&) {
return false;
}
);
scoped_actor self{ep.system()};
self->wait_for(worker);
}
void sender(caf::event_based_actor* self, caf::actor core, broker::topic t) {
auto msg = std::make_pair(t, data{"Lorem ipsum dolor sit amet."});
self->make_source(
// Destination.
core,
// Initializer.
[](caf::unit_t&) {},
// Generator.
[=](caf::unit_t&, caf::downstream<std::pair<topic, data>>& out, size_t n) {
for (size_t i = 0; i < n; ++i)
out.push(msg);
},
// Done predicate.
[=](const caf::unit_t& msgs) { return false; });
}
caf::behavior receiver(caf::event_based_actor* self, caf::actor core,
broker::topic t) {
self->send(core, broker::atom::join::value,
broker::filter_type{std::move(t)});
return {[=](caf::stream<std::pair<topic, data>> in) {
return self->make_sink(
// Source.
in,
// Initializer.
[](caf::unit_t&) {
// nop
},
// Consumer.
[=](caf::unit_t&, std::vector<std::pair<topic, data>>& xs) {
global_count += xs.size();
},
// Cleanup.
[](caf::unit_t&, const caf::error&) {
// nop
}
);
}};
}
void rate_calculator() {
// Counts consecutive rates that are 0.
size_t zero_rates = 0;
// Keeps track of the message count in our last iteration.
size_t last_count = 0;
// Used to compute absolute timeouts.
auto t = std::chrono::steady_clock::now();
// Stop after 2s of no activity.
while (zero_rates < 2) {
t += std::chrono::seconds(1);
std::this_thread::sleep_until(t);
auto count = global_count.load();
auto rate = count - last_count;
std::cout << rate << " msgs/s\n";
last_count = count;
if (rate == 0)
++zero_rates;
}
}
} // namespace <anonymous>
int main(int argc, char** argv) {
config cfg;
cfg.parse(argc, argv);
if (cfg.cli_helptext_printed)
return EXIT_SUCCESS;
auto mode = cfg.mode;
auto port = cfg.port;
auto host = cfg.host;
topic foobar{"foo/bar"};
std::thread t{rate_calculator};
switch (caf::atom_uint(mode)) {
default:
std::cerr << "invalid mode: " << to_string(mode) << endl;
return EXIT_FAILURE;
case caf::atom_uint("source"): {
broker::endpoint ep{std::move(cfg)};
if (!ep.peer(host, port)) {
std::cerr << "cannot peer to node: " << to_string(host) << " on port "
<< port << endl;
return EXIT_FAILURE;
}
source_mode(ep, foobar);
break;
}
case caf::atom_uint("sink"): {
broker::endpoint ep{std::move(cfg)};
ep.listen({}, port);
sink_mode(ep, foobar);
break;
}
case caf::atom_uint("both"): {
broker::endpoint ep1{std::move(cfg)};
auto snk_port = ep1.listen({}, 0);
std::thread source_thread{[argc, argv, host, snk_port, foobar] {
config cfg2;
cfg2.parse(argc, argv);
broker::endpoint ep2{std::move(cfg2)};
if (!ep2.peer(host, snk_port)) {
std::cerr << "cannot peer to node: " << to_string(host) << " on port "
<< snk_port << endl;
return;
}
source_mode(ep2, foobar);
}};
sink_mode(ep1, foobar);
source_thread.join();
break;
}
case caf::atom_uint("fused"): {
caf::actor_system sys{cfg};
endpoint::clock clock{&sys, true};
filter_type filter{foobar};
auto core1 = sys.spawn(broker::core_actor, filter,
broker::broker_options{}, &clock);
auto core2 = sys.spawn(broker::core_actor, filter,
broker::broker_options{}, &clock);
anon_send(core1, atom::peer::value, core2);
sys.spawn(sender, core1, foobar);
sys.spawn(receiver, core2, foobar);
caf::scoped_actor self{sys};
self->wait_for(core1, core2);
}
}
t.join();
return EXIT_SUCCESS;
}
| 26.532407
| 80
| 0.585064
|
zpx2012
|
3b226b50358c2dc65cb80efd38d9658b043f2ac0
| 1,114
|
cpp
|
C++
|
utility/addressof.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | 47
|
2016-05-20T08:49:47.000Z
|
2022-01-03T01:17:07.000Z
|
utility/addressof.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | null | null | null |
utility/addressof.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | 37
|
2016-07-25T04:52:08.000Z
|
2022-02-14T03:55:08.000Z
|
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;
#include <boost/utility/addressof.hpp>
using namespace boost;
///////////////////////////////////////
void case1()
{
int i;
string s;
assert(&i == boost::addressof(i));
assert(&s == boost::addressof(s));
int a[10];
assert(&a == boost::addressof(a));
assert(a + 1 == boost::addressof(a[1]));
assert(&printf == boost::addressof(printf));
}
///////////////////////////////////////
class dont_do_this
{
public:
int x,y;
size_t operator&() const
{ return (size_t)&y; }
};
void case2()
{
dont_do_this d;
assert(&d != (size_t)boost::addressof(d));
assert(&d == (size_t)&d.y);
dont_do_this *p = boost::addressof(d);
p->x = 1;
}
///////////////////////////////////////
class danger_class
{
void operator&() const;
};
void case3()
{
danger_class d;
// cout << &d;
cout << boost::addressof(d);
}
///////////////////////////////////////
int main()
{
std::cout << "hello addressof" << std::endl;
case1();
case2();
case3();
}
| 15.914286
| 48
| 0.487433
|
MaxHonggg
|
3b26b2e687ade339b075dcd2ff136e1fb3236ecb
| 2,434
|
hpp
|
C++
|
gcpp/classes/opathspec.hpp
|
razzlefratz/MotleyTools
|
3c69c574351ce6f4b7e687c13278d4b6cbb200f3
|
[
"0BSD"
] | 2
|
2015-10-15T19:32:42.000Z
|
2021-12-20T15:56:04.000Z
|
gcpp/classes/opathspec.hpp
|
razzlefratz/MotleyTools
|
3c69c574351ce6f4b7e687c13278d4b6cbb200f3
|
[
"0BSD"
] | null | null | null |
gcpp/classes/opathspec.hpp
|
razzlefratz/MotleyTools
|
3c69c574351ce6f4b7e687c13278d4b6cbb200f3
|
[
"0BSD"
] | null | null | null |
/*====================================================================*
*
* opathspec.hpp - interface for the opathspec class.
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef oPATH_HEADER
#define oPATH_HEADER
/*====================================================================*
* system header files;
*--------------------------------------------------------------------*/
#include <sys/stat.h>
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../classes/stdafx.hpp"
#include "../classes/owildcard.hpp"
/*====================================================================*
*
*--------------------------------------------------------------------*/
class __declspec (dllexport) opathspec: private owildcard
{
public:
opathspec ();
virtual ~ opathspec ();
bool isdotdir (char const * filename);
bool exists (char const * pathname);
bool infolder (char fullname [], char const * wildcard, bool recurse);
bool instring (char fullname [], char const * pathname, char const * filename);
bool instring (char fullname [], char const * pathname, char const * filename, bool recurse);
bool invector (char fullname [], char const * pathname [], char const * filename);
bool invector (char fullname [], char const * pathname [], char const * filename, bool recurse);
char const * dirname (char const * filespec);
char const * basename (char const * filespec);
void fullpath (char fullname [], char const * filespec);
void makepath (char fullname [], char const * pathname, char const * filename);
void findpath (char const * fullname, char pathname [], char filename []);
void partpath (char const * fullname, char pathname [], char filename []);
void partfile (char const * filename, char basename [], char extender []);
private:
struct stat mstatinfo;
void splitpath (char * filespec);
void mergepath ();
char ** mstack;
unsigned mindex;
unsigned mstart;
unsigned mlevel;
unsigned mcount;
unsigned mlimit;
};
/*====================================================================*
*
*--------------------------------------------------------------------*/
#endif
| 34.28169
| 97
| 0.497124
|
razzlefratz
|
3b281d2749fc00e1bb7f10dea504edd642437cea
| 1,026
|
hpp
|
C++
|
src/lib/builders/interpretable.hpp
|
bunsanorg/bacs_system
|
22149ecfaac913b820dbda52933bf8ea9fecd723
|
[
"Apache-2.0"
] | null | null | null |
src/lib/builders/interpretable.hpp
|
bunsanorg/bacs_system
|
22149ecfaac913b820dbda52933bf8ea9fecd723
|
[
"Apache-2.0"
] | null | null | null |
src/lib/builders/interpretable.hpp
|
bunsanorg/bacs_system
|
22149ecfaac913b820dbda52933bf8ea9fecd723
|
[
"Apache-2.0"
] | null | null | null |
#include "compilable.hpp"
namespace bacs {
namespace system {
namespace builders {
class interpretable : public compilable {
protected:
name_type name(const bacs::process::Source &source) override;
};
class interpretable_executable : public compilable_executable {
public:
interpretable_executable(const ContainerPointer &container,
bunsan::tempfile &&tmpdir,
const compilable::name_type &name,
const boost::filesystem::path &executable,
const std::vector<std::string> &flags_ = {});
ProcessPointer create(const ProcessGroupPointer &process_group,
const ProcessArguments &arguments) override;
protected:
virtual std::vector<std::string> arguments() const;
virtual std::vector<std::string> flags() const;
private:
const boost::filesystem::path m_executable;
const std::vector<std::string> m_flags;
};
} // namespace builders
} // namespace system
} // namespace bacs
| 29.314286
| 72
| 0.662768
|
bunsanorg
|
3b2958e86930fc17a868e5f4663e908315b57621
| 28,856
|
cpp
|
C++
|
ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.cpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.cpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 17
|
2020-11-23T07:24:16.000Z
|
2022-03-28T10:29:06.000Z
|
ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.cpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 7
|
2017-04-24T08:28:43.000Z
|
2022-03-15T08:59:54.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2018 Sebastian Schlenkrich
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <sstream>
#include <ql/math/distributions/normaldistribution.hpp>
#include <ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.hpp>
namespace {
// we need to calculate the cumulative normal distribution function (and derivative)
// in various places
QuantLib::CumulativeNormalDistribution Phi;
// we need to convert numbers to strings for logging
template <typename T>
std::string to_string(T val) {
std::stringstream stream;
stream << val;
return stream.str();
}
}
namespace QuantLib {
// we have two constructors and want to make sure the setup is consistent
void VanillaLocalVolModel::initializeDeepInTheModelParameters() {
straddleATM_ = sigmaATM_ * sqrt(T_) * M_1_SQRTPI * M_SQRT_2 * 2.0;
if (useInitialMu_) mu_ = initialMu_;
else mu_ = -(Mm_[0] + Mp_[0]) / 4.0 * T_; // this should be exact for shifted log-normal models
alpha_ = 1.0;
nu_ = 0.0;
extrapolationStdevs_ = 10.0;
sigma0Tol_ = 1.0e-12;
S0Tol_ = 1.0e-12;
}
Real VanillaLocalVolModel::localVol(const bool isRightWing, const Size k, const Real S) {
// this is an unsafe method specifying the vol function sigma(S) on the individual segments
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
Real S0 = (k > 0) ? Sp_[k - 1] : S0_;
return sigma0 + Mp_[k] * (S - S0);
} else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
Real S0 = (k > 0) ? Sm_[k - 1] : S0_;
return sigma0 + Mm_[k] * (S - S0);
}
return 0.0; // this should never be reached
}
Real VanillaLocalVolModel::underlyingS(const bool isRightWing, const Size k, const Real x) {
// this is an unsafe method specifying the underlying level S(x) on the individual segments
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
Real x0 = (k > 0) ? Xp_[k - 1] : 0.0;
Real deltaS = (Mp_[k] == 0.0) ? (sigma0*(x - x0)) : (sigma0 / Mp_[k] * (exp(Mp_[k] * (x - x0)) - 1.0));
Real S0 = (k > 0) ? Sp_[k - 1] : S0_;
return S0 + deltaS;
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
Real x0 = (k > 0) ? Xm_[k - 1] : 0.0;
Real deltaS = (Mm_[k] == 0.0) ? (sigma0*(x - x0)) : (sigma0 / Mm_[k] * (exp(Mm_[k] * (x - x0)) - 1.0));
Real S0 = (k > 0) ? Sm_[k - 1] : S0_;
return S0 + deltaS;
}
return 0.0; // this should never be reached
}
Real VanillaLocalVolModel::underlyingX(const bool isRightWing, const Size k, const Real S) {
// this is an unsafe method specifying the underlying level x(S) on the individual segments
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 > 0.0, "sigma0 > 0.0 required");
Real x0 = (k > 0) ? Xp_[k - 1] : 0.0;
Real S0 = (k > 0) ? Sp_[k - 1] : S0_;
Real deltaX = (Mp_[k] == 0.0) ? ((S - S0) / sigma0) : (log(1.0 + Mp_[k] / sigma0*(S - S0)) / Mp_[k]);
return x0 + deltaX;
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 > 0.0, "sigma0 > 0.0 required");
Real x0 = (k > 0) ? Xm_[k - 1] : 0.0;
Real S0 = (k > 0) ? Sm_[k - 1] : S0_;
Real deltaX = (Mm_[k] == 0.0) ? ((S - S0) / sigma0) : (log(1.0 + Mm_[k] / sigma0*(S - S0)) / Mm_[k]);
return x0 + deltaX;
}
return 0.0; // this should never be reached
}
Real VanillaLocalVolModel::primitiveF(const bool isRightWing, const Size k, const Real x) {
// this is an unsafe method specifying the primitive function F(x) = \int [alpha S(x) + nu] p(x) dx
// on the individual segments
Real sigma0, x0, S0, m0;
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
x0 = (k > 0) ? Xp_[k - 1] : 0.0;
S0 = (k > 0) ? Sp_[k - 1] : S0_;
m0 = Mp_[k];
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
x0 = (k > 0) ? Xm_[k - 1] : 0.0;
S0 = (k > 0) ? Sm_[k - 1] : S0_;
m0 = Mm_[k];
}
Real y0 = (x0 - mu_) / sqrt(T_);
Real y1 = (x - mu_) / sqrt(T_);
Real h = m0 * sqrt(T_);
Real Ny = Phi(y1);
Real term1, term2;
if (m0 == 0.0) {
term1 = (S0 + nu_ / alpha_ - sigma0 * sqrt(T_) * y0) * Ny;
term2 = sigma0 * sqrt(T_) * Phi.derivative(y1); // use dN/dx = dN/dy / sqrt(T)
}
else {
Real NyMinush = Phi(y1 - h);
term1 = exp(h*h / 2.0 - h*y0)*sigma0 / m0 * NyMinush;
term2 = (sigma0 / m0 - (S0 + nu_ / alpha_)) * Ny;
}
return alpha_ * (term1 - term2);
}
Real VanillaLocalVolModel::primitiveFSquare(const bool isRightWing, const Size k, const Real x) {
// this is an unsafe method specifying the primitive function F(x) = \int [alpha S(x) + nu]^2 p(x) dx
// on the individual segments
Real sigma0, x0, S0, m0;
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
x0 = (k > 0) ? Xp_[k - 1] : 0.0;
S0 = (k > 0) ? Sp_[k - 1] : S0_;
m0 = Mp_[k];
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
x0 = (k > 0) ? Xm_[k - 1] : 0.0;
S0 = (k > 0) ? Sm_[k - 1] : S0_;
m0 = Mm_[k];
}
Real y0 = (x0 - mu_) / sqrt(T_);
Real y1 = (x - mu_) / sqrt(T_);
Real h = m0 * sqrt(T_);
Real Ny = Phi(y1);
Real sum = 0;
if (m0 == 0.0) {
Real K3 = S0 + nu_ / alpha_ - sigma0 * sqrt(T_) * y0;
Real term1 = (K3 * K3 + sigma0 * sigma0 * T_) * Ny;
Real term2 = 2.0 * sigma0 * sqrt(T_) * K3 + sigma0 * sigma0 * T_ * y1;
term2 *= Phi.derivative(y1); // use dN/dx = dN/dy / sqrt(T)
sum = term1 - term2;
}
else {
Real NyMinush = Phi(y1 - h);
Real NyMinus2h = Phi(y1 - 2.0*h);
Real K1 = sigma0 / m0 * exp(h*(h - y0));
Real K2 = S0 + nu_ / alpha_ - sigma0 / m0;
Real term1 = K2 * K2 * Ny;
Real term2 = 2.0 * K1 * K2 * exp(-h*h / 2.0) * NyMinush;
Real term3 = K1 * K1 * NyMinus2h;
sum = term1 + term2 + term3;
}
return alpha_ * alpha_ * sum;
}
void VanillaLocalVolModel::calculateSGrid() {
// this is an unsafe method to calculate the S-grid for a given x-grid
// it is intended as a preprocessing step in conjunction with smile interplation
// validity of the model is ensured by proceeding it with updateLocalVol()
for (Size k = 0; k < Xp_.size(); ++k) { // right wing calculations
Sp_[k] = underlyingS(true, k, Xp_[k]);
sigmaP_[k] = localVol(true, k, Sp_[k]);
}
for (Size k = 0; k < Sm_.size(); ++k) { // left wing calculations
Sm_[k] = underlyingS(false, k, Xm_[k]);
sigmaM_[k] = localVol(false, k, Sm_[k]);
}
}
void VanillaLocalVolModel::updateLocalVol() {
// use ODE solution to determine x-grid and sigma-grid taking into account constraints of
// positive local volatility and local vol extrapolation
for (Size k = 0; k < Sp_.size(); ++k) { // right wing calculations
Real x0 = (k > 0) ? Xp_[k - 1] : 0.0;
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 >= 0.0, "sigma0 >= 0.0 required.");
if ((k == Sp_.size() - 1)||(localVol(true, k, Sp_[k])<=0.0)||(underlyingX(true, k, Sp_[k])>upperBoundX())) { // right wing extrapolation, maybe better use some epsilon here
Real XRight = upperBoundX(); // mu might not yet be calibrated
QL_REQUIRE(XRight >= x0, "XRight >= x0 required.");
Xp_[k] = XRight;
Sp_[k] = underlyingS(true, k, XRight);
sigmaP_[k] = localVol(true, k, Sp_[k]);
if (k < Sp_.size() - 1) Mp_[k + 1] = Mp_[k]; // we need to make sure vol doesn't go up again
continue;
}
sigmaP_[k] = localVol(true, k, Sp_[k]);
QL_REQUIRE(sigmaP_[k] > 0.0, "sigmaP_[k] > 0.0 required.");
Xp_[k] = underlyingX(true, k, Sp_[k]);
}
for (Size k = 0; k < Sm_.size(); ++k) { // left wing calculations
Real x0 = (k > 0) ? Xm_[k - 1] : 0.0;
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 >= 0.0, "sigma0 >= 0.0 required.");
if ((k == Sm_.size() - 1)||(localVol(false, k, Sm_[k]) <= 0.0)||(underlyingX(false, k, Sm_[k])<lowerBoundX())) { // left wing extrapolation, maybe better use some epsilon here
Real XLeft = lowerBoundX(); // mu might not yet be calibrated
QL_REQUIRE(XLeft <= x0, "XLeft <= x0 required.");
Xm_[k] = XLeft;
Sm_[k] = underlyingS(false, k, XLeft);
sigmaM_[k] = localVol(false, k, Sm_[k]);
if (k < Sm_.size() - 1) Mm_[k + 1] = Mm_[k]; // we need to make sure vol doesn't go up again
continue;
}
sigmaM_[k] = localVol(false, k, Sm_[k]);
QL_REQUIRE(sigmaM_[k] > 0.0, "sigmaM_[k] > 0.0 required.");
Xm_[k] = underlyingX(false, k, Sm_[k]);
}
}
void VanillaLocalVolModel::calibrateATM() {
Real straddleVega = straddleATM_ / sigmaATM_;
Real forwardMinusStrike0, forwardMinusStrike1, straddleMinusATM0, straddleMinusATM1, dmu, dlogSigma0;
Real dfwd_dmu, dstr_dlogSigma0, logSigma0=log(sigma0_);
for (Size k = 0; k < maxCalibrationIters_; ++k) {
Real call = expectation(true, S0_);
Real put = expectation(false, S0_);
forwardMinusStrike1 = call - put;
straddleMinusATM1 = call + put - straddleATM_;
if (k > 0) { // perform line search
Real num = forwardMinusStrike0*(forwardMinusStrike1 - forwardMinusStrike0) +
straddleMinusATM0*(straddleMinusATM1 - straddleMinusATM0);
Real den = (forwardMinusStrike1 - forwardMinusStrike0)*(forwardMinusStrike1 - forwardMinusStrike0) +
(straddleMinusATM1 - straddleMinusATM0)*(straddleMinusATM1 - straddleMinusATM0);
Real lambda = -num / den;
Real eps = 1.0e-6; // see Griewank '86
if (lambda < -0.5 - eps) lambda = -0.5;
else if (lambda < -eps); // lambda = lambda;
else if (lambda < 0.0) lambda = -eps;
else if (lambda <= eps) lambda = eps;
else if (lambda <= 0.5 + eps); // lambda = lambda;
else lambda = 1.0;
if (lambda < 1.0) { // reject the step and calculate a new try
// x = x - dx + lambda dx = x + (lambda - 1.0) dx
mu_ += (lambda - 1.0) * dmu;
logSigma0 += (lambda - 1.0) * dlogSigma0;
dmu *= lambda;
dlogSigma0 *= lambda;
sigma0_ = exp(logSigma0);
updateLocalVol();
if (enableLogging_) logging_.push_back("k: " + to_string(k) +
"; C: " + to_string(call) +
"; P: " + to_string(put) +
"; S: " + to_string(straddleATM_) +
"; lambda: " + to_string(lambda) +
"; dmu: " + to_string(dmu) +
"; dlogSigma0: " + to_string(dlogSigma0));
continue; // don't update derivatives and step direction for rejected steps
}
}
if (k == 0) {
dfwd_dmu = sigma0_; // this is an estimate based on dS/dX at ATM
dstr_dlogSigma0 = straddleVega * sigma0_; // this is an estimate based on dsigmaATM / dsigma0 =~ 1
}
if (k>0) { // we use secant if available
// only update derivative if we had a step, otherwise use from previous iteration
// also avoid division by zero and zero derivative
Real eps = 1.0e-12; // we aim at beeing a bit more robust
if ((fabs(forwardMinusStrike1 - forwardMinusStrike0) > eps) && (fabs(dmu) > eps)) {
dfwd_dmu = (forwardMinusStrike1 - forwardMinusStrike0) / dmu;
}
if ((fabs(straddleMinusATM1 - straddleMinusATM0) > eps) && (fabs(dlogSigma0) > eps)) {
dstr_dlogSigma0 = (straddleMinusATM1 - straddleMinusATM0) / dlogSigma0;
}
}
dmu = -forwardMinusStrike1 / dfwd_dmu;
if (k < onlyForwardCalibrationIters_) dlogSigma0 = 0.0; // keep sigma0 fixed and only calibrate forward
else dlogSigma0 = -straddleMinusATM1 / dstr_dlogSigma0;
if (dmu <= -0.9*upperBoundX()) dmu = -0.5*upperBoundX(); // make sure 0 < eps < upperBoundX() in next update
if (dmu >= -0.9*lowerBoundX()) dmu = -0.5*lowerBoundX(); // make sure 0 > eps > lowerBoundX() in next update
// maybe some line search could improve convergence...
mu_ += dmu;
logSigma0 += dlogSigma0;
sigma0_ = exp(logSigma0); // ensure sigma0 > 0
updateLocalVol();
// prepare for next iteration
forwardMinusStrike0 = forwardMinusStrike1;
straddleMinusATM0 = straddleMinusATM1;
if (enableLogging_) logging_.push_back("k: " + to_string(k) +
"; C: " + to_string(call) +
"; P: " + to_string(put) +
"; S: " + to_string(straddleATM_) +
"; dfwd_dmu: " + to_string(dfwd_dmu) +
"; dstr_dlogSigma0: " + to_string(dstr_dlogSigma0) +
"; dmu: " + to_string(dmu) +
"; dlogSigma0: " + to_string(dlogSigma0));
if ((fabs(forwardMinusStrike0) < S0Tol_) && (fabs(sigma0_*dlogSigma0) < sigma0Tol_)) break;
}
}
void VanillaLocalVolModel::adjustATM() {
// reset adjusters in case this method is invoked twice
alpha_ = 1.0;
nu_ = 0.0;
Real call0 = expectation(true, S0_);
Real put0 = expectation(false, S0_);
nu_ = put0 - call0;
if (enableLogging_) logging_.push_back("C0: " + to_string(call0) + "; P0: " + to_string(put0) + "; nu: " + to_string(nu_));
Real call1 = expectation(true, S0_);
Real put1 = expectation(false, S0_);
alpha_ = straddleATM_ / (call1 + put1);
nu_ = alpha_*nu_ + (1.0 - alpha_)*S0_;
if (enableLogging_) logging_.push_back("C1: " + to_string(call1) + "; P1: " + to_string(put1) + "; alpha_: " + to_string(alpha_) + "; nu_: " + to_string(nu_));
}
// construct model based on S-grid
VanillaLocalVolModel::VanillaLocalVolModel(
const Time T,
const Real S0,
const Real sigmaATM,
const std::vector<Real>& Sp,
const std::vector<Real>& Sm,
const std::vector<Real>& Mp,
const std::vector<Real>& Mm,
// controls for calibration
const Size maxCalibrationIters,
const Size onlyForwardCalibrationIters,
const bool adjustATMFlag,
const bool enableLogging,
const bool useInitialMu,
const Real initialMu)
: T_(T), S0_(S0), sigmaATM_(sigmaATM), Sp_(Sp), Sm_(Sm), Mp_(Mp), Mm_(Mm), sigma0_(sigmaATM),
maxCalibrationIters_(maxCalibrationIters), onlyForwardCalibrationIters_(onlyForwardCalibrationIters),
adjustATM_(adjustATMFlag), useInitialMu_(useInitialMu), initialMu_(initialMu), enableLogging_(enableLogging) {
// some basic sanity checks come here to avoid the need for taking care of it later on
QL_REQUIRE(T_ > 0, "T_ > 0 required.");
QL_REQUIRE(sigmaATM_ > 0, "sigmaATM_ > 0 required.");
QL_REQUIRE(Sp_.size() > 0, "Sp_.size() > 0 required.");
QL_REQUIRE(Sm_.size() > 0, "Sm_.size() > 0 required.");
QL_REQUIRE(Mp_.size() == Sp_.size(), "Mp_.size() == Sp_.size() required.");
QL_REQUIRE(Mm_.size() == Sm_.size(), "Mm_.size() == Sm_.size() required.");
// check for monotonicity
QL_REQUIRE(Sp_[0] > S0_, "Sp_[0] > S0_ required.");
for (Size k=1; k<Sp_.size(); ++k) QL_REQUIRE(Sp_[k] > Sp_[k-1], "Sp_[k] > Sp_[k-1] required.");
QL_REQUIRE(Sm_[0] < S0_, "Sm_[0] < S0_ required.");
for (Size k = 1; k<Sm_.size(); ++k) QL_REQUIRE(Sm_[k] < Sm_[k-1], "Sm_[k] < Sm_[k-1] required.");
// now it makes sense to allocate memory
sigmaP_.resize(Sp_.size());
sigmaM_.resize(Sm_.size());
Xp_.resize(Sp_.size());
Xm_.resize(Sm_.size());
// initialize deep-in-the-model parameters
initializeDeepInTheModelParameters();
// now we may calculate local volatility
updateLocalVol();
calibrateATM();
if (adjustATM_) adjustATM();
}
// construct model based on x-grid
VanillaLocalVolModel::VanillaLocalVolModel(
const Time T,
const Real S0,
const Real sigmaATM,
const Real sigma0,
const std::vector<Real>& Xp,
const std::vector<Real>& Xm,
const std::vector<Real>& Mp,
const std::vector<Real>& Mm,
// controls for calibration
const Size maxCalibrationIters,
const Size onlyForwardCalibrationIters,
const bool adjustATMFlag,
const bool enableLogging,
const bool useInitialMu,
const Real initialMu)
: T_(T), S0_(S0), sigmaATM_(sigmaATM), Mp_(Mp), Mm_(Mm), sigma0_(sigma0), Xp_(Xp), Xm_(Xm),
maxCalibrationIters_(maxCalibrationIters), onlyForwardCalibrationIters_(onlyForwardCalibrationIters),
adjustATM_(adjustATMFlag), useInitialMu_(useInitialMu), initialMu_(initialMu), enableLogging_(enableLogging) {
// some basic sanity checks come here to avoid the need for taking care of it later on
QL_REQUIRE(T_ > 0, "T_ > 0 required.");
QL_REQUIRE(sigmaATM_ > 0, "sigmaATM_ > 0 required.");
QL_REQUIRE(sigma0_ > 0, "sigma0_ > 0 required.");
QL_REQUIRE(Xp_.size() > 0, "Xp_.size() > 0 required.");
QL_REQUIRE(Xm_.size() > 0, "Xm_.size() > 0 required.");
QL_REQUIRE(Mp_.size() == Xp_.size(), "Mp_.size() == Xp_.size() required.");
QL_REQUIRE(Mm_.size() == Xm_.size(), "Mm_.size() == Xm_.size() required.");
// check for monotonicity
QL_REQUIRE(Xp_[0] > 0.0, "Xp_[0] > 0.0 required.");
for (Size k = 1; k<Xp_.size(); ++k) QL_REQUIRE(Xp_[k] > Xp_[k - 1], "Xp_[k] > Xp_[k-1] required.");
QL_REQUIRE(Xm_[0] < 0.0, "Xm_[0] < 0.0 required.");
for (Size k = 1; k<Xm_.size(); ++k) QL_REQUIRE(Xm_[k] < Xm_[k - 1], "Xm_[k] < Xm_[k-1] required.");
// now it makes sense to allocate memory
sigmaP_.resize(Xp_.size());
sigmaM_.resize(Xm_.size());
Sp_.resize(Xp_.size());
Sm_.resize(Xm_.size());
// initialize deep-in-the-model parameters
initializeDeepInTheModelParameters();
// now we may calculate local volatility
calculateSGrid(); // we need this preprocessing step since we only input x instead of S
updateLocalVol();
calibrateATM();
if (adjustATM_) adjustATM();
}
// attributes in more convenient single-vector format
const std::vector<Real> VanillaLocalVolModel::underlyingX() {
std::vector<Real> X(Xm_.size() + Xp_.size() + 1);
for (Size k = 0; k < Xm_.size(); ++k) X[k] = Xm_[Xm_.size() - k - 1];
X[Xm_.size()] = 0.0;
for (Size k = 0; k < Xp_.size(); ++k) X[Xm_.size() + 1 + k] = Xp_[k];
return X;
}
const std::vector<Real> VanillaLocalVolModel::underlyingS() {
std::vector<Real> S(Sm_.size() + Sp_.size() + 1);
for (Size k = 0; k < Sm_.size(); ++k) S[k] = Sm_[Sm_.size() - k - 1];
S[Sm_.size()] = S0_;
for (Size k = 0; k < Sp_.size(); ++k) S[Sm_.size() + 1 + k] = Sp_[k];
return S;
}
const std::vector<Real> VanillaLocalVolModel::localVol() {
std::vector<Real> sigma(sigmaM_.size() + sigmaP_.size() + 1);
for (Size k = 0; k < sigmaM_.size(); ++k) sigma[k] = sigmaM_[sigmaM_.size() - k - 1];
sigma[sigmaM_.size()] = sigma0_;
for (Size k = 0; k < sigmaP_.size(); ++k) sigma[sigmaM_.size() + 1 + k] = sigmaP_[k];
return sigma;
}
const std::vector<Real> VanillaLocalVolModel::localVolSlope() {
std::vector<Real> m(Mm_.size() + Mp_.size() + 1);
for (Size k = 0; k < Mm_.size(); ++k) m[k] = Mm_[Mm_.size() - k - 1];
m[Mm_.size()] = 0.0; // undefined
for (Size k = 0; k < Mp_.size(); ++k) m[Mm_.size() + 1 + k] = Mp_[k];
return m;
}
// model function evaluations
const Real VanillaLocalVolModel::localVol(Real S) {
bool isRightWing = (S >= S0_) ? true : false;
Size idx = 0;
if (isRightWing) while ((idx < Sp_.size() - 1) && (Sp_[idx] < S)) ++idx;
else while ((idx < Sm_.size() - 1) && (Sm_[idx] > S)) ++idx;
return localVol(isRightWing, idx, S);
}
const Real VanillaLocalVolModel::underlyingS(Real x) {
bool isRightWing = (x >= 0.0) ? true : false;
Size idx = 0;
if (isRightWing) while ((idx < Xp_.size() - 1) && (Xp_[idx] < x)) ++idx;
else while ((idx < Xm_.size() - 1) && (Xm_[idx] > x)) ++idx;
return underlyingS(isRightWing, idx, x);
}
// calculating expectations - that is the actual purpose of that model
const Real VanillaLocalVolModel::expectation(bool isRightWing, Real strike) {
// calculate the forward price of an OTM option
Size idx = 0;
if (isRightWing) {
QL_REQUIRE(strike >= S0_, "strike >= S0_ required");
while ((idx < Sp_.size()) && (Sp_[idx] <= strike)) ++idx; // make sure strike < Sp_[idx]
if (idx == Sp_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xp_[idx - 1] : 0.0;
QL_REQUIRE((x0 <= strikeX) && (strikeX <= Xp_[idx]), "(x0 <= strikeX) && (strikeX <= Xp_[idx]) required");
Real intS = 0.0;
for (Size k = idx; k < Sp_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xp_[k - 1];
intS += (primitiveF(isRightWing, k, Xp_[k]) - primitiveF(isRightWing, k, xStart));
}
// we need to adjust for the strike integral
Real xEnd = Xp_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return intS - strike * intK;
}
else {
QL_REQUIRE(strike <= S0_, "strike <= S0_ required");
while ((idx < Sm_.size()) && (Sm_[idx] >= strike)) ++idx; // make sure Sm_[idx] < strke
if (idx == Sm_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xm_[idx - 1] : 0.0;
QL_REQUIRE((x0 >= strikeX) && (strikeX >= Xm_[idx]), "(x0 >= strikeX) && (strikeX >= Xm_[idx]) required");
Real intS = 0.0;
for (Size k = idx; k < Sm_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xm_[k - 1];
intS += (primitiveF(isRightWing, k, Xm_[k]) - primitiveF(isRightWing, k, xStart));
}
// we need to adjust for the strike integral
Real xEnd = Xm_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return intS - strike * intK;
}
}
const Real VanillaLocalVolModel::variance(bool isRightWing, Real strike) {
// calculate the forward price of an OTM power option with payoff 1_{S>K}(S-K)^2
Size idx = 0;
if (isRightWing) {
QL_REQUIRE(strike >= S0_, "strike >= S0_ required");
while ((idx < Sp_.size()) && (Sp_[idx] <= strike)) ++idx; // make sure strike < Sp_[idx]
if (idx == Sp_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xp_[idx - 1] : 0.0;
QL_REQUIRE((x0 <= strikeX) && (strikeX <= Xp_[idx]), "(x0 <= strikeX) && (strikeX <= Xp_[idx]) required");
Real intS=0.0, intS2 = 0.0;
for (Size k = idx; k < Sp_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xp_[k - 1];
intS += (primitiveF(isRightWing, k, Xp_[k]) - primitiveF(isRightWing, k, xStart));
intS2 += (primitiveFSquare(isRightWing, k, Xp_[k]) - primitiveFSquare(isRightWing, k, xStart));
}
// we need to adjust for the Vanilla and strike integral
Real xEnd = Xp_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return intS2 - 2.0 * strike * intS + strike * strike * intK;
}
else {
QL_REQUIRE(strike <= S0_, "strike <= S0_ required");
while ((idx < Sm_.size()) && (Sm_[idx] >= strike)) ++idx; // make sure Sm_[idx] < strke
if (idx == Sm_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xm_[idx - 1] : 0.0;
QL_REQUIRE((x0 >= strikeX) && (strikeX >= Xm_[idx]), "(x0 >= strikeX) && (strikeX >= Xm_[idx]) required");
Real intS = 0.0, intS2 = 0.0;
for (Size k = idx; k < Sm_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xm_[k - 1];
intS += (primitiveF(isRightWing, k, Xm_[k]) - primitiveF(isRightWing, k, xStart));
intS2 += (primitiveFSquare(isRightWing, k, Xm_[k]) - primitiveFSquare(isRightWing, k, xStart));
}
// we need to adjust for the strike integral
Real xEnd = Xm_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return -(intS2 - 2.0 * strike * intS + strike * strike * intK);
}
}
} // namespace QauntLib
| 50.802817
| 187
| 0.525818
|
urgu00
|
3b2aa11f7e5dfaf5db22d5b8c854b65e354fa357
| 1,758
|
cpp
|
C++
|
bzoj/1057.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | 3
|
2017-09-17T09:12:50.000Z
|
2018-04-06T01:18:17.000Z
|
bzoj/1057.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
bzoj/1057.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
// Copy from luogu1169
#include <iostream>
#include <algorithm>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
#include <cmath>
#include <math.h>
#include <vector>
#include <iostream>
#include <cstdio>
#include <ctime>
#include <set>
#include <map>
#include <fstream>
#include <bits/stdc++.h>
#define ll long long
#define oo 1<<30
#define ESP 1e-9
#define read(a) scanf("%d", &a)
#define writeln(a) printf("%d\n", a)
#define write(a) printf("%d", a)
#define mst(a, b) memset(a, b, sizeof a)
#define rep(a, b, c) for(int a = b; a < c; a ++)
#define reps(a, b, c) for(int a = b; a <= c; a ++)
#define repx(a, b, c) for(int a = b, a > c; a --)
#define repxs(a, b, c) for(int a = b; a >= c; a --)
#define MOD 1000000007
#define MAXN 805
using namespace std;
const int mxn=2005;
int n,m,ans1,ans2;
int h[mxn][mxn],l[mxn],r[mxn],s[mxn];
bool a[mxn][mxn];
inline void find(bool flag)
{
memset(h,0,sizeof h);
reps(i,1,n) reps(j,1,m) if(a[i][j]==flag) h[i][j]=h[i-1][j]+1;
reps( i,1,n)
{
int top=0;
s[top]=0;
reps( j,1,m)
{
while(h[i][s[top]]>=h[i][j] && top) top--;
l[j]=s[top]+1;
s[++top]=j;
}
top=0;s[0]=m+1;
repxs(j,m,1)
{
while(h[i][s[top]]>=h[i][j] && top) top--;
r[j]=s[top]-1;
s[++top]=j;
ans2=max(ans2,(r[j]-l[j]+1)*h[i][j]);
if(r[j]-l[j]+1>=h[i][j]) ans1=max(ans1,h[i][j]*h[i][j]);
}
}
}
int main (){
cin >> n >> m;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++){
cin >> a[i][j];
a[i][j] = (a[i][j] == (i % 2) ^ (j % 2));
}
find(0);
find(1);
cout << ans1 << "\n" << ans2;
return 0;
}
| 22.253165
| 68
| 0.497156
|
swwind
|
3b2ecb1ba6fc9611d8242b246c797a5c9d5173e0
| 431
|
hpp
|
C++
|
net/include/HttpProxyAuthenticate.hpp
|
wangsun1983/Obotcha
|
2464e53599305703f5150df72bf73579a39d8ef4
|
[
"MIT"
] | 27
|
2019-04-27T00:51:22.000Z
|
2022-03-30T04:05:44.000Z
|
net/include/HttpProxyAuthenticate.hpp
|
wangsun1983/Obotcha
|
2464e53599305703f5150df72bf73579a39d8ef4
|
[
"MIT"
] | 9
|
2020-05-03T12:17:50.000Z
|
2021-10-15T02:18:47.000Z
|
net/include/HttpProxyAuthenticate.hpp
|
wangsun1983/Obotcha
|
2464e53599305703f5150df72bf73579a39d8ef4
|
[
"MIT"
] | 1
|
2019-04-16T01:45:36.000Z
|
2019-04-16T01:45:36.000Z
|
#ifndef __OBOTCHA_HTTP_PROXY_AUTHENTICATE_HPP__
#define __OBOTCHA_HTTP_PROXY_AUTHENTICATE_HPP__
#include "Object.hpp"
#include "StrongPointer.hpp"
#include "String.hpp"
#include "ArrayList.hpp"
namespace obotcha {
DECLARE_CLASS(HttpProxyAuthenticate) {
public:
_HttpProxyAuthenticate();
_HttpProxyAuthenticate(String);
void import(String);
String toString();
String type;
String realm;
};
}
#endif
| 15.392857
| 47
| 0.756381
|
wangsun1983
|
3b3613bec8d7f4d9e6ab3d88e2b3b182ecbbde39
| 446
|
hpp
|
C++
|
materias ple/programacao orientada ao objeto/trabalhos praticos/tp-1/Codigo/Hpp/MenuMeca.hpp
|
marcusv77/universidade
|
723f9a2ac7b7c14c11ada751c6daa1bd1cd0c4df
|
[
"MIT"
] | null | null | null |
materias ple/programacao orientada ao objeto/trabalhos praticos/tp-1/Codigo/Hpp/MenuMeca.hpp
|
marcusv77/universidade
|
723f9a2ac7b7c14c11ada751c6daa1bd1cd0c4df
|
[
"MIT"
] | null | null | null |
materias ple/programacao orientada ao objeto/trabalhos praticos/tp-1/Codigo/Hpp/MenuMeca.hpp
|
marcusv77/universidade
|
723f9a2ac7b7c14c11ada751c6daa1bd1cd0c4df
|
[
"MIT"
] | null | null | null |
#ifndef MENUMECA_HPP
#define MENUMECA_HPP
#include<iostream>
#include<list>
#include"./Mecanico.hpp"
#include"./Vendedor.hpp"
#include"./Item.hpp"
#include"./MaodeObra.hpp"
#include"./Servico.hpp"
#include"./Ordem.hpp"
using namespace std;
void menuMeca(Mecanico* mecani);
void viewOrdems(Mecanico* mecani, Vendedor vend);
void adicionaServico(Mecanico* mecani, Vendedor vendi);
void cadastraServico(Mecanico* mecani, Vendedor vendi);
#endif
| 21.238095
| 55
| 0.769058
|
marcusv77
|
3b395423c34a79882924f9b7f060adbf82872c33
| 2,154
|
cpp
|
C++
|
Programs/QuickEd/Classes/UI/Properties/BoolPropertyDelegate.cpp
|
stinvi/dava.engine
|
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
|
[
"BSD-3-Clause"
] | 26
|
2018-09-03T08:48:22.000Z
|
2022-02-14T05:14:50.000Z
|
Programs/QuickEd/Classes/UI/Properties/BoolPropertyDelegate.cpp
|
ANHELL-blitz/dava.engine
|
ed83624326f000866e29166c7f4cccfed1bb41d4
|
[
"BSD-3-Clause"
] | null | null | null |
Programs/QuickEd/Classes/UI/Properties/BoolPropertyDelegate.cpp
|
ANHELL-blitz/dava.engine
|
ed83624326f000866e29166c7f4cccfed1bb41d4
|
[
"BSD-3-Clause"
] | 45
|
2018-05-11T06:47:17.000Z
|
2022-02-03T11:30:55.000Z
|
#include "BoolPropertyDelegate.h"
#include <QComboBox>
#include "DAVAEngine.h"
#include "PropertiesTreeItemDelegate.h"
#include "Utils/QtDavaConvertion.h"
BoolPropertyDelegate::BoolPropertyDelegate(PropertiesTreeItemDelegate* delegate)
: BasePropertyDelegate(delegate)
{
}
BoolPropertyDelegate::~BoolPropertyDelegate()
{
}
QWidget* BoolPropertyDelegate::createEditor(QWidget* parent, const PropertiesContext& context, const QStyleOptionViewItem& option, const QModelIndex& index)
{
QComboBox* comboBox = new QComboBox(parent);
comboBox->addItem(QVariant(false).toString(), false);
comboBox->addItem(QVariant(true).toString(), true);
comboBox->setObjectName(QString::fromUtf8("comboBox"));
connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnCurrentIndexChanged()));
return comboBox;
}
void BoolPropertyDelegate::setEditorData(QWidget* rawEditor, const QModelIndex& index) const
{
QComboBox* editor = rawEditor->findChild<QComboBox*>("comboBox");
editor->blockSignals(true);
DAVA::Any variant = index.data(Qt::EditRole).value<DAVA::Any>();
DVASSERT(variant.CanGet<bool>());
int comboIndex = editor->findData(QVariant(variant.Get<bool>()));
editor->setCurrentIndex(comboIndex);
editor->blockSignals(false);
BasePropertyDelegate::SetValueModified(editor, false);
}
bool BoolPropertyDelegate::setModelData(QWidget* rawEditor, QAbstractItemModel* model, const QModelIndex& index) const
{
if (BasePropertyDelegate::setModelData(rawEditor, model, index))
return true;
QComboBox* comboBox = rawEditor->findChild<QComboBox*>("comboBox");
DAVA::Any any(comboBox->itemData(comboBox->currentIndex()).toBool());
QVariant variant;
variant.setValue<DAVA::Any>(any);
return model->setData(index, variant, Qt::EditRole);
}
void BoolPropertyDelegate::OnCurrentIndexChanged()
{
QWidget* comboBox = qobject_cast<QWidget*>(sender());
if (!comboBox)
return;
QWidget* editor = comboBox->parentWidget();
if (!editor)
return;
BasePropertyDelegate::SetValueModified(editor, true);
itemDelegate->emitCommitData(editor);
}
| 31.676471
| 156
| 0.738162
|
stinvi
|
3b3e7f7492f7cda4e0c6f4a931e32e1ddcd04e79
| 239
|
cpp
|
C++
|
src/Rendering/Lighting/CompositeLight.cpp
|
Tristeon/Tristeon
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 32
|
2018-06-16T20:50:15.000Z
|
2022-03-26T16:57:15.000Z
|
src/Rendering/Lighting/CompositeLight.cpp
|
Tristeon/Tristeon2D
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 2
|
2018-10-07T17:41:39.000Z
|
2021-01-08T03:14:19.000Z
|
src/Rendering/Lighting/CompositeLight.cpp
|
Tristeon/Tristeon2D
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 9
|
2018-06-12T21:00:58.000Z
|
2021-01-08T02:18:30.000Z
|
#include "CompositeLight.h"
#include <Collector.h>
namespace Tristeon
{
CompositeLight::CompositeLight()
{
Collector<CompositeLight>::add(this);
}
CompositeLight::~CompositeLight()
{
Collector<CompositeLight>::remove(this);
}
}
| 15.933333
| 42
| 0.732218
|
Tristeon
|
3b3f290de42e2598a981357d8ebfeacff5adc4ce
| 1,420
|
cpp
|
C++
|
17-Hash-Tables/Source.cpp
|
InamTaj/data-structures
|
7a662a8e635402bab3481d69d8df9164499da6b4
|
[
"Apache-2.0"
] | 1
|
2019-06-24T11:34:23.000Z
|
2019-06-24T11:34:23.000Z
|
17-Hash-Tables/Source.cpp
|
InamTaj/data-structures
|
7a662a8e635402bab3481d69d8df9164499da6b4
|
[
"Apache-2.0"
] | null | null | null |
17-Hash-Tables/Source.cpp
|
InamTaj/data-structures
|
7a662a8e635402bab3481d69d8df9164499da6b4
|
[
"Apache-2.0"
] | 1
|
2020-11-23T03:28:52.000Z
|
2020-11-23T03:28:52.000Z
|
//Inamullah Taj - 1446
// OBJECTIVE: Implement a Class of Static Graph
#include "HashTableHeader.h"
#include <conio.h>
#include <iostream>
using namespace std;
void main()
{
char ext;
int choice, size, value;
cout<<"\t \t \t>>-> HASH TABLES <-<<\n\n";
cout<<"\n\t\tEnter Size of Table = "; cin>>size;
HashTable<int> mytable(size);
do
{
cout<<"\n\tWhat to do?\n1 -> Insert key\n2 -> Search Key\n3 -> Delete Key\n4 -> Show Table\n0 -> EXIT\n\t\tYour Choice = "; cin>>choice; cout<<endl;
if(choice==1)
{
cout<<"Enter Value to insert = "; cin>>value;
mytable.Insert(value);
}
else if(choice==2)
{
cout<<"Enter Value to search = "; cin>>value;
int status = mytable.Search(value);
if(status != 0)
{ cout<<"\n\tValue "<<value<<" is at Index "<<status; }
else if(status == 0)
{ cout<<"\n\tERROR:: Value not Found in Table!"; }
}
else if(choice==3)
{
cout<<"Enter Value to Delete = "; cin>>value;
int stat = mytable.GetKey(value);
if(stat!=0)
{ cout<<"\n\tValue "<<value<<" Deleted from Table!"; }
else
{ cout<<"\n\tERROR:: Value not Found in Table!"; }
}
else if (choice==4)
{
mytable.ShowTable();
}
else if (choice==0)
{ break; }
else
{ cout<<"\n\tERROR:: Wrong Choice! Try Again.."; }
cout<<"\n\n\t\t\tENTER to Continue | ESc to Exit.."; ext = _getch();
}
while(ext!=27);
}
| 26.792453
| 151
| 0.569014
|
InamTaj
|
3b41ac4e3177c9af23d31d8e0ba47349f8bf678d
| 2,507
|
cpp
|
C++
|
tqli2.cpp
|
iglpdc/tiny_dmrg
|
2679f7d72f19377c7ec2d1381e05f63398177bf8
|
[
"MIT"
] | 10
|
2015-02-11T03:07:51.000Z
|
2022-03-10T09:14:02.000Z
|
tqli2.cpp
|
npatel37/tiny_dmrg
|
2679f7d72f19377c7ec2d1381e05f63398177bf8
|
[
"MIT"
] | null | null | null |
tqli2.cpp
|
npatel37/tiny_dmrg
|
2679f7d72f19377c7ec2d1381e05f63398177bf8
|
[
"MIT"
] | 6
|
2015-03-05T22:49:45.000Z
|
2019-11-17T08:55:41.000Z
|
/**
* @file tqli2.cpp
*
* @brief Implementation for the tqli2 function using blitz arrays
*
* @author Roger Melko
* @author Ivan Gonzalez
* @date $Date$
*
* $Revision$
*/
#include <cmath>
#include <iomanip>
#include "blitz/array.h"
#include "tqli2.h"
#define SIGN(a,b) ((b)<0 ? -fabs(a) : fabs(a))
/**
* @brief A function to diagonalize a tridiagonal matrix
*
* @param d an array with the elements in the diagonal of the matrix
* @param e an array with the elements in the off-diagonal of the matrix
* @param n an int with the size of the array d
* @param z an matrix with the eigenvectors of the diagonal matrix
* @param Evects an int to control whether you calculate the eigenvectors
* or not
*
* @return an int with code to check success (1) or failure (0). (Note the
* evil use of the flag.)
*
* Diagonalizes a tridiagonal matrix: d[] is input as the diagonal elements,
* e[] as the off-diagonal. If the eigenvalues of the tridiagonal matrix
* are wanted, input z as the identity matrix. If the eigenvalues of the
* original matrix reduced by tred2 are desired, input z as the matrix
* output by tred2. The kth column of z returns the normalized eigenvectors,
* corresponding to the eigenvalues output in d[k].
* April 2005, Roger Melko, modified from Numerical Recipies in C v.2
* Modified from www.df.unipi.it/~moruzzi/
* Feb 23 2005: modified to use Blitz++ arrays
*/
int tqli2(blitz::Array<double,1>& d, blitz::Array<double,1>& e, int n,
blitz::Array<double,2>& z, const int Evects)
{
int m,l,iter,i,k;
double s,r,p,g,f,dd,c,b;
for (l=0;l<n;l++) {
iter=0;
do {
for (m=l;m<n-1;m++) {
dd=fabs(d(m))+fabs(d(m+1));
if (fabs(e(m))+dd == dd) break;
}
if (m!=l) {
if (iter++ == 30) {
std::cout <<"Too many iterations in tqli() \n";
return 0;
}
g=(d(l+1)-d(l))/(2.0*e(l));
r=sqrt((g*g)+1.0);
g=d(m)-d(l)+e(l)/(g+SIGN(r,g));
s=c=1.0;
p=0.0;
for (i=m-1;i>=l;i--) {
f=s*e(i);
b=c*e(i);
if (fabs(f) >= fabs(g)) {
c=g/f;r=sqrt((c*c)+1.0);
e(i+1)=f*r;
c *= (s=1.0/r);
}
else {
s=f/g;r=sqrt((s*s)+1.0);
e(i+1)=g*r;
s *= (c=1.0/r);
}
g=d(i+1)-p;
r=(d(i)-g)*s+2.0*c*b;
p=s*r;
d(i+1)=g+p;
g=c*r-b;
/*EVECTS*/
if (Evects == 1) {
for (k=0;k<n;k++) {
f=z(k,i+1);
z(k,i+1)=s*z(k,i)+c*f;
z(k,i)=c*z(k,i)-s*f;
}
}//Evects
}
d(l)=d(l)-p;
e(l)=g;
e(m)=0.0;
}
} while (m!=l);
}
return 1;
}
//end tqli2.cpp
| 25.07
| 77
| 0.578381
|
iglpdc
|
3b42d88f49debe20d42ab1933f021c6361e0b810
| 1,266
|
hpp
|
C++
|
include/copr/sequence/fft.hpp
|
orisano/copr
|
3c1018edcc20e0f855ec614b2ddf579f8f81cd72
|
[
"MIT"
] | null | null | null |
include/copr/sequence/fft.hpp
|
orisano/copr
|
3c1018edcc20e0f855ec614b2ddf579f8f81cd72
|
[
"MIT"
] | null | null | null |
include/copr/sequence/fft.hpp
|
orisano/copr
|
3c1018edcc20e0f855ec614b2ddf579f8f81cd72
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cassert>
#include <cmath>
#include <complex>
#include <vector>
template <typename T>
inline std::complex<T> cmul(const std::complex<T>& a, const std::complex<T>& b) {
return std::complex<T>(a.real() * b.real() - a.imag() * b.imag(),
a.real() * b.imag() + a.imag() * b.real());
}
template <typename T>
void fft(std::vector<std::complex<T>>& a, int sign = +1) {
const int N = a.size();
assert(N == (N & -N));
const T theta = 8 * sign * std::atan(1.0) / N;
for (int i = 0, j = 1; j < N - 1; ++j) {
for (int k = N >> 1; k > (i ^= k);) k >>= 1;
if (j < i) std::swap(a[i], a[j]);
}
for (int m, mh = 1; (m = mh << 1) <= N; mh = m) {
int irev = 0;
for (int i = 0; i < N; i += m) {
auto w = std::exp(std::complex<T>(0, theta * irev));
for (int k = N >> 2; k > (irev ^= k);) k >>= 1;
for (int j = i; j < mh + i; ++j) {
int k = j + mh;
auto x = a[j] - a[k];
a[j] += a[k];
a[k] = cmul(w, x);
}
}
}
}
template <typename T>
void ifft(std::vector<std::complex<T>>& a) {
const int N = a.size();
assert(N == (N & -N));
fft(a, -1);
const T inv = 1.0 / N;
for (int i = 0; i < N; ++i) {
a[i] *= inv;
}
}
| 25.32
| 81
| 0.460506
|
orisano
|
3b4581ebe1400cc04822f68b1ab6ed506e54ce8e
| 3,586
|
cpp
|
C++
|
timer/Utility/CollisionUtilities.cpp
|
MaticVrtacnik/ProceduralnaAnimacija
|
bc47ccc721d1bedb31ed5949eb740892f094897a
|
[
"MIT"
] | null | null | null |
timer/Utility/CollisionUtilities.cpp
|
MaticVrtacnik/ProceduralnaAnimacija
|
bc47ccc721d1bedb31ed5949eb740892f094897a
|
[
"MIT"
] | null | null | null |
timer/Utility/CollisionUtilities.cpp
|
MaticVrtacnik/ProceduralnaAnimacija
|
bc47ccc721d1bedb31ed5949eb740892f094897a
|
[
"MIT"
] | null | null | null |
/*
MIT License
Copyright (c) 2019 MaticVrtacnik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "CollisionUtilities.hpp"
#include <utility>
#include <glm\gtc\type_ptr.hpp>
#include <BulletCollision\CollisionShapes\btCollisionShape.h>
#include "../Define/PrintDefines.hpp"
namespace Engine{
namespace Physics{
btVector3 convertVec3(const glm::vec3 &vector){
return btVector3(vector.x, vector.y, vector.z);
}
btVector3 convertVec3(glm::vec3 &&vector){
return btVector3(std::move(vector.x), std::move(vector.y), std::move(vector.z));
}
glm::vec3 convertVec3(const btVector3 &vector){
return glm::vec3(vector.getX(), vector.getY(), vector.getZ());
}
/*glm::vec3 convertVec3(btVector3 &&vector){
return glm::vec3(std::move(vector)); //TODO FIXXXXXX
}*/
btQuaternion convertQuat(const glm::quat &quaternion){
return btQuaternion(
quaternion.x, quaternion.y,
quaternion.z, quaternion.w
);
}
btQuaternion convertQuat(glm::quat &&quaternion){
return btQuaternion(
std::move(quaternion.x), std::move(quaternion.y),
std::move(quaternion.z), std::move(quaternion.w)
);
}
glm::quat convertQuat(const btQuaternion &quaternion){
return glm::quat(quaternion.w(), quaternion.x(), quaternion.y(), quaternion.z());
}
/*
glm::quat convertQuat(btQuaternion &&quaternion){
return glm::quat(
quaternion.w(), quaternion.x(),
quaternion.y(), quaternion.z()
);
}
*/
btTransform convertMat4(const glm::mat4 &transform){
/*if (glm::length(glm::vec3(transform[0])) != 1.0f)
WARNING("BulletPhysics Matrix X-axis scale not 1.0");
if (glm::length(glm::vec3(transform[1])) != 1.0f)
WARNING("BulletPhysics Matrix Y-axis scale not 1.0");
if (glm::length(glm::vec3(transform[2])) != 1.0f)
WARNING("BulletPhysics Matrix Z-axis scale not 1.0");*/
btTransform _transform = btTransform::getIdentity();
_transform.setFromOpenGLMatrix(glm::value_ptr(transform));
return _transform;
}
glm::mat4 convertMat4(const btTransform &transform){
glm::mat4 _transform;
transform.getOpenGLMatrix(glm::value_ptr(_transform));
return _transform;
}
glm::vec3 getBodyScale(btRigidBody &body){
btVector3 _aabbMin, _aabbMax;
body.getAabb(_aabbMin, _aabbMax);
return glm::abs(Physics::convertVec3(_aabbMax - _aabbMin));
}
glm::mat2x3 getBoundingBox(btCollisionShape *collisionShape){
btVector3 _aabbMin, _aabbMax;
collisionShape->getAabb(btTransform::getIdentity(), _aabbMin, _aabbMax);
return glm::mat2x3(convertVec3(_aabbMin), convertVec3(_aabbMax));
}
}
}
| 29.393443
| 84
| 0.726715
|
MaticVrtacnik
|
8dc922b8b29873463fb27cc57301a26a9b2ba1f3
| 21,764
|
cc
|
C++
|
ggadget/clutter/view_actor_binder.cc
|
meego-netbook-ux/google-gadgets-meego
|
89af89796bca073e95f44d43c9d81407caabedf0
|
[
"Apache-2.0"
] | null | null | null |
ggadget/clutter/view_actor_binder.cc
|
meego-netbook-ux/google-gadgets-meego
|
89af89796bca073e95f44d43c9d81407caabedf0
|
[
"Apache-2.0"
] | null | null | null |
ggadget/clutter/view_actor_binder.cc
|
meego-netbook-ux/google-gadgets-meego
|
89af89796bca073e95f44d43c9d81407caabedf0
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Portions:
Copyright 2008-2010 Intel Corp.
Authors:
Iain Holmes <iain@linux.intel.com>
Roger WANG <roger.wang@intel.com>
*/
#include <algorithm>
#include <string>
#include <vector>
#include <cairo.h>
#include <clutter/clutter.h>
#include "view_actor_binder.h"
#include <ggadget/common.h>
#include <ggadget/logger.h>
#include <ggadget/event.h>
#include <ggadget/main_loop_interface.h>
#include <ggadget/view_interface.h>
#include <ggadget/view_host_interface.h>
#include <ggadget/clip_region.h>
#include <ggadget/math_utils.h>
#include <ggadget/string_utils.h>
#include "cairo_canvas.h"
#include "cairo_graphics.h"
#include "key_convert.h"
#include "utilities.h"
#define GRAB_POINTER_EXPLICITLY
namespace ggadget {
namespace clutter {
// A small motion threshold to prevent a click with tiny mouse move from being
// treated as window move or resize.
static const double kDragThreshold = 3;
// Minimal interval between self draws.
static const unsigned int kSelfDrawInterval = 40;
class ViewActorBinder::Impl {
public:
Impl(ViewInterface *view,
ViewHostInterface *host, ClutterActor *actor)
: view_(view),
host_(host),
actor_(actor),
handlers_(new gulong[kEventHandlersNum]),
on_zoom_connection_(NULL),
dbl_click_(false),
focused_(false),
button_pressed_(false),
#ifdef GRAB_POINTER_EXPLICITLY
pointer_grabbed_(false),
#endif
zoom_(1.0),
mouse_down_x_(-1),
mouse_down_y_(-1),
mouse_down_hittest_(ViewInterface::HT_CLIENT),
self_draw_(false),
self_draw_timer_(0),
last_self_draw_time_(0),
freeze_updates_(false) {
ASSERT(view);
ASSERT(host);
g_object_ref(G_OBJECT(actor_));
for (size_t i = 0; i < kEventHandlersNum; ++i) {
handlers_[i] = g_signal_connect(G_OBJECT(actor_),
kEventHandlers[i].event,
kEventHandlers[i].handler,
this);
}
CairoGraphics *gfx= down_cast<CairoGraphics *>(view_->GetGraphics());
ASSERT(gfx);
zoom_ = gfx->GetZoom();
on_zoom_connection_ = gfx->ConnectOnZoom(NewSlot(this, &Impl::OnZoom));
}
~Impl() {
view_ = NULL;
if (self_draw_timer_) {
g_source_remove(self_draw_timer_);
self_draw_timer_ = 0;
}
for (size_t i = 0; i < kEventHandlersNum; ++i) {
if (handlers_[i] > 0)
g_signal_handler_disconnect(G_OBJECT(actor_), handlers_[i]);
else
DLOG("Handler %s was not connected.", kEventHandlers[i].event);
}
delete[] handlers_;
handlers_ = NULL;
if (on_zoom_connection_) {
on_zoom_connection_->Disconnect();
on_zoom_connection_ = NULL;
}
g_object_unref(G_OBJECT(actor_));
}
void OnZoom(double zoom) {
zoom_ = zoom;
}
static gboolean ButtonPressHandler(ClutterActor *actor,
ClutterButtonEvent *event,
gpointer user_data) {
DLOG("ButtonPressHandler.");
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
impl->button_pressed_ = true;
impl->host_->ShowTooltip("");
if (!impl->focused_) {
impl->focused_ = true;
SimpleEvent e(Event::EVENT_FOCUS_IN);
// Ignore the result.
impl->view_->OnOtherEvent(e);
}
// This will break I suppose if there's more than one stage
clutter_stage_set_key_focus (CLUTTER_STAGE(clutter_stage_get_default()),
actor);
int mod = ConvertClutterModifierToModifier(event->modifier_state);
int button = event->button == 1 ? MouseEvent::BUTTON_LEFT :
event->button == 2 ? MouseEvent::BUTTON_MIDDLE :
event->button == 3 ? MouseEvent::BUTTON_RIGHT :
MouseEvent::BUTTON_NONE;
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, event->x,
event->y,
&actor_x, &actor_y);
Event::Type type = Event::EVENT_INVALID;
if (event->click_count == 1) {
type = Event::EVENT_MOUSE_DOWN;
impl->mouse_down_x_ = actor_x;
impl->mouse_down_y_ = actor_y;
} else if (event->click_count == 2) {
impl->dbl_click_ = true;
if (button == MouseEvent::BUTTON_LEFT)
type = Event::EVENT_MOUSE_DBLCLICK;
else if (button == MouseEvent::BUTTON_RIGHT)
type = Event::EVENT_MOUSE_RDBLCLICK;
}
if (button != MouseEvent::BUTTON_NONE && type != Event::EVENT_INVALID) {
MouseEvent e(type, (actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod, event);
result = impl->view_->OnMouseEvent(e);
impl->mouse_down_hittest_ = impl->view_->GetHitTest();
// If the View's hittest represents a special button, then handle it
// here.
if (result == EVENT_RESULT_UNHANDLED &&
button == MouseEvent::BUTTON_LEFT &&
type == Event::EVENT_MOUSE_DOWN) {
if (impl->mouse_down_hittest_ == ViewInterface::HT_MENU) {
impl->host_->ShowContextMenu(button);
} else if (impl->mouse_down_hittest_ == ViewInterface::HT_CLOSE) {
impl->host_->CloseView();
}
result = EVENT_RESULT_HANDLED;
}
}
return result != EVENT_RESULT_UNHANDLED;
}
static gboolean ButtonReleaseHandler(ClutterActor *actor,
ClutterButtonEvent *event,
gpointer user_data) {
DLOG("ButtonReleaseHandler.");
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
EventResult result2 = EVENT_RESULT_UNHANDLED;
if (impl->button_pressed_ == false)
return false;
impl->button_pressed_ = false;
impl->host_->ShowTooltip("");
#ifdef GRAB_POINTER_EXPLICITLY
if (impl->pointer_grabbed_) {
clutter_ungrab_pointer();
impl->pointer_grabbed_ = false;
}
#endif
int mod = ConvertClutterModifierToModifier(event->modifier_state);
int button = event->button == 1 ? MouseEvent::BUTTON_LEFT :
event->button == 2 ? MouseEvent::BUTTON_MIDDLE :
event->button == 3 ? MouseEvent::BUTTON_RIGHT :
MouseEvent::BUTTON_NONE;
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
if (button != MouseEvent::BUTTON_NONE) {
MouseEvent e(Event::EVENT_MOUSE_UP,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod, event);
result = impl->view_->OnMouseEvent(e);
if (!impl->dbl_click_) {
MouseEvent e2(button == MouseEvent::BUTTON_LEFT ?
Event::EVENT_MOUSE_CLICK : Event::EVENT_MOUSE_RCLICK,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod);
result2 = impl->view_->OnMouseEvent(e2);
} else {
impl->dbl_click_ = false;
}
}
impl->mouse_down_x_ = -1;
impl->mouse_down_y_ = -1;
impl->mouse_down_hittest_ = ViewInterface::HT_CLIENT;
return result != EVENT_RESULT_UNHANDLED ||
result2 != EVENT_RESULT_UNHANDLED;
}
static gboolean KeyPressHandler(ClutterActor *actor,
ClutterKeyEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
EventResult result2 = EVENT_RESULT_UNHANDLED;
impl->host_->ShowTooltip("");
int mod = ConvertClutterModifierToModifier(event->modifier_state);
unsigned int key_code = ConvertClutterKeyvalToKeyCode(event->keyval);
if (key_code) {
KeyboardEvent e(Event::EVENT_KEY_DOWN, key_code, mod, event);
result = impl->view_->OnKeyEvent(e);
} else {
LOG("Unknown key: 0x%x", event->keyval);
}
guint32 key_char = 0;
if ((event->modifier_state & (CLUTTER_CONTROL_MASK | CLUTTER_MOD1_MASK)) == 0) {
if (key_code == KeyboardEvent::KEY_ESCAPE ||
key_code == KeyboardEvent::KEY_RETURN ||
key_code == KeyboardEvent::KEY_BACK ||
key_code == KeyboardEvent::KEY_TAB) {
// gdk_keyval_to_unicode doesn't support the above keys.
key_char = key_code;
} else {
key_char = clutter_keysym_to_unicode(event->keyval);
}
} else if ((event->modifier_state & CLUTTER_CONTROL_MASK) &&
key_code >= 'A' && key_code <= 'Z') {
// Convert CTRL+(A to Z) to key press code for compatibility.
key_char = key_code - 'A' + 1;
}
if (key_char) {
// Send the char code in KEY_PRESS event.
KeyboardEvent e2(Event::EVENT_KEY_PRESS, key_char, mod, event);
result2 = impl->view_->OnKeyEvent(e2);
}
return result != EVENT_RESULT_UNHANDLED ||
result2 != EVENT_RESULT_UNHANDLED;
}
static gboolean KeyReleaseHandler(ClutterActor *actor,
ClutterKeyEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
int mod = ConvertClutterModifierToModifier(event->modifier_state);
unsigned int key_code = ConvertClutterKeyvalToKeyCode(event->keyval);
if (key_code) {
KeyboardEvent e(Event::EVENT_KEY_UP, key_code, mod, event);
result = impl->view_->OnKeyEvent(e);
} else {
LOG("Unknown key: 0x%x", event->keyval);
}
return result != EVENT_RESULT_UNHANDLED;
}
void Redraw() {
if (freeze_updates_)
return;
view_->Layout ();
cairo_t *cr = NULL;
const ClipRegion *view_region = view_->GetClipRegion();
size_t count = view_region->GetRectangleCount();
DLOG(" == actor update region == ");
view_region->PrintLog();
if (count) {
Rectangle rect, union_rect;
for (size_t i = 0; i < count; ++i) {
rect = view_region->GetRectangle(i);
if (zoom_ != 1.0) {
rect.Zoom(zoom_);
rect.Integerize(true);
}
union_rect.Union (rect);
}
cr = clutter_cairo_texture_create_region (CLUTTER_CAIRO_TEXTURE(actor_),
union_rect.x, union_rect.y,
union_rect.w, union_rect.h);
}else{
cr = clutter_cairo_texture_create (CLUTTER_CAIRO_TEXTURE(actor_));
}
if (!cr)
return;
cairo_operator_t op = cairo_get_operator(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
cairo_paint(cr);
cairo_set_operator(cr, op);
CairoCanvas *canvas = new CairoCanvas(cr,
view_->GetGraphics()->GetZoom(),
view_->GetWidth(),
view_->GetHeight());
DLOG ("redraw");
view_->Draw(canvas);
canvas->Destroy();
cairo_destroy(cr);
}
static gboolean MotionNotifyHandler(ClutterActor *actor,
ClutterMotionEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
int button = ConvertClutterModifierToButton(event->modifier_state);
int mod = ConvertClutterModifierToModifier(event->modifier_state);
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_MOVE,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod);
#ifdef GRAB_POINTER_EXPLICITLY
if (button != MouseEvent::BUTTON_NONE && !impl->pointer_grabbed_) {
// Grab the cursor to prevent losing events.
clutter_grab_pointer(actor);
impl->pointer_grabbed_ = true;
}
#endif
EventResult result = impl->view_->OnMouseEvent(e);
if (result == EVENT_RESULT_UNHANDLED && button != MouseEvent::BUTTON_NONE &&
impl->mouse_down_x_ >= 0 && impl->mouse_down_y_ >= 0 &&
(std::abs((actor_x) - impl->mouse_down_x_) > kDragThreshold ||
std::abs((actor_y) - impl->mouse_down_y_) > kDragThreshold ||
impl->mouse_down_hittest_ != ViewInterface::HT_CLIENT)) {
impl->button_pressed_ = false;
// Send fake mouse up event to the view so that we can start to drag
// the window. Note: no mouse click event is sent in this case, to prevent
// unwanted action after window move.
MouseEvent e(Event::EVENT_MOUSE_UP,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod);
// Ignore the result of this fake event.
impl->view_->OnMouseEvent(e);
ViewInterface::HitTest hittest = impl->mouse_down_hittest_;
bool resize_drag = false;
// Determine the resize drag edge.
if (hittest == ViewInterface::HT_LEFT ||
hittest == ViewInterface::HT_RIGHT ||
hittest == ViewInterface::HT_TOP ||
hittest == ViewInterface::HT_BOTTOM ||
hittest == ViewInterface::HT_TOPLEFT ||
hittest == ViewInterface::HT_TOPRIGHT ||
hittest == ViewInterface::HT_BOTTOMLEFT ||
hittest == ViewInterface::HT_BOTTOMRIGHT) {
resize_drag = true;
}
#ifdef GRAB_POINTER_EXPLICITLY
// ungrab the pointer before starting move/resize drag.
if (impl->pointer_grabbed_) {
clutter_ungrab_pointer();
impl->pointer_grabbed_ = false;
}
#endif
impl->mouse_down_stage_x_ = event->x;
impl->mouse_down_stage_y_ = event->y;
if (resize_drag) {
impl->host_->BeginResizeDrag(button, hittest);
} else {
impl->host_->BeginMoveDrag(button);
}
impl->mouse_down_x_ = -1;
impl->mouse_down_y_ = -1;
impl->mouse_down_hittest_ = ViewInterface::HT_CLIENT;
impl->mouse_down_stage_x_ = 0;
impl->mouse_down_stage_y_ = 0;
}
return result != EVENT_RESULT_UNHANDLED;
}
static gboolean ScrollHandler(ClutterActor *actor,
ClutterScrollEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
int delta_x = 0, delta_y = 0;
if (event->direction == CLUTTER_SCROLL_UP) {
delta_y = MouseEvent::kWheelDelta;
} else if (event->direction == CLUTTER_SCROLL_DOWN) {
delta_y = -MouseEvent::kWheelDelta;
} else if (event->direction == CLUTTER_SCROLL_LEFT) {
delta_x = MouseEvent::kWheelDelta;
} else if (event->direction == CLUTTER_SCROLL_RIGHT) {
delta_x = -MouseEvent::kWheelDelta;
}
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, event->x,
event->y,
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_WHEEL,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
delta_x, delta_y,
ConvertClutterModifierToButton(event->modifier_state),
ConvertClutterModifierToModifier(event->modifier_state));
return impl->view_->OnMouseEvent(e) != EVENT_RESULT_UNHANDLED;
}
static gboolean LeaveNotifyHandler(ClutterActor *actor,
ClutterCrossingEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
// Don't send mouse out event if the mouse is grabbed.
if (impl->button_pressed_)
return FALSE;
impl->host_->ShowTooltip("");
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_OUT,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_, 0, 0,
MouseEvent::BUTTON_NONE,
Event::MOD_NONE);
return impl->view_->OnMouseEvent(e) != EVENT_RESULT_UNHANDLED;
}
static gboolean EnterNotifyHandler(ClutterActor *actor,
ClutterCrossingEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
impl->host_->ShowTooltip("");
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_OVER,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_, 0, 0,
MouseEvent::BUTTON_NONE,
Event::MOD_NONE);
return impl->view_->OnMouseEvent(e) != EVENT_RESULT_UNHANDLED;
}
static gboolean FocusInHandler(ClutterActor *actor,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
if (!impl->focused_) {
impl->focused_ = true;
SimpleEvent e(Event::EVENT_FOCUS_IN);
return impl->view_->OnOtherEvent(e) != EVENT_RESULT_UNHANDLED;
}
return FALSE;
}
static gboolean FocusOutHandler(ClutterActor *actor,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
if (impl->focused_) {
impl->focused_ = false;
SimpleEvent e(Event::EVENT_FOCUS_OUT);
#ifdef GRAB_POINTER_EXPLICITLY
// Ungrab the pointer if the focus is lost.
if (impl->pointer_grabbed_) {
clutter_ungrab_pointer();
impl->pointer_grabbed_ = false;
}
#endif
return impl->view_->OnOtherEvent(e) != EVENT_RESULT_UNHANDLED;
}
return FALSE;
}
static gboolean SelfDrawHandler(gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
impl->self_draw_timer_ = 0;
impl->Redraw();
return FALSE;
}
ViewInterface *view_;
ViewHostInterface *host_;
ClutterActor *actor_;
gulong *handlers_;
Connection *on_zoom_connection_;
bool dbl_click_;
bool focused_;
bool button_pressed_;
#ifdef GRAB_POINTER_EXPLICITLY
bool pointer_grabbed_;
#endif
double zoom_;
double mouse_down_x_;
double mouse_down_y_;
int mouse_down_stage_x_;
int mouse_down_stage_y_;
ViewInterface::HitTest mouse_down_hittest_;
bool self_draw_;
guint self_draw_timer_;
uint64_t last_self_draw_time_;
bool freeze_updates_;
struct EventHandlerInfo {
const char *event;
void (*handler)(void);
};
static EventHandlerInfo kEventHandlers[];
static const size_t kEventHandlersNum;
};
ViewActorBinder::Impl::EventHandlerInfo
ViewActorBinder::Impl::kEventHandlers[] = {
{ "button-press-event", G_CALLBACK(ButtonPressHandler) },
{ "button-release-event", G_CALLBACK(ButtonReleaseHandler) },
{ "enter-event", G_CALLBACK(EnterNotifyHandler) },
/* { "expose-event", G_CALLBACK(ExposeHandler) },*/
{ "key-focus-in", G_CALLBACK(FocusInHandler) },
{ "key-focus-out", G_CALLBACK(FocusOutHandler) },
{ "key-press-event", G_CALLBACK(KeyPressHandler) },
{ "key-release-event", G_CALLBACK(KeyReleaseHandler) },
{ "leave-event", G_CALLBACK(LeaveNotifyHandler) },
{ "motion-event", G_CALLBACK(MotionNotifyHandler) },
{ "scroll-event", G_CALLBACK(ScrollHandler) },
};
const size_t ViewActorBinder::Impl::kEventHandlersNum =
arraysize(ViewActorBinder::Impl::kEventHandlers);
ViewActorBinder::ViewActorBinder(ViewInterface *view,
ViewHostInterface *host, ClutterActor *actor)
: impl_(new Impl(view, host, actor)) {
}
ViewActorBinder::~ViewActorBinder() {
delete impl_;
impl_ = NULL;
}
void ViewActorBinder::Redraw() {
impl_->Redraw();
}
void ViewActorBinder::QueueDraw() {
if (!impl_->self_draw_timer_) {
uint64_t current_time = GetCurrentTime();
if (current_time - impl_->last_self_draw_time_ >= kSelfDrawInterval) {
impl_->self_draw_timer_ =
g_idle_add_full(CLUTTER_PRIORITY_REDRAW, Impl::SelfDrawHandler,
impl_, NULL);
} else {
impl_->self_draw_timer_ =
g_timeout_add(kSelfDrawInterval -
(current_time - impl_->last_self_draw_time_),
Impl::SelfDrawHandler, impl_);
}
}
}
int ViewActorBinder::GetPointerX() {
return impl_->mouse_down_stage_x_;
}
int ViewActorBinder::GetPointerY() {
return impl_->mouse_down_stage_y_;
}
void ViewActorBinder::FreezeUpdates() {
impl_->freeze_updates_ = true;
}
void ViewActorBinder::ThawUpdates() {
impl_->freeze_updates_ = false;
}
} // namespace clutter
} // namespace ggadget
| 33.32925
| 84
| 0.612617
|
meego-netbook-ux
|
8dcce9bc595ba11809680515c9373c5e627702dc
| 54,578
|
cpp
|
C++
|
Examples/AEGP/Artie/Artie.cpp
|
richardlalancette/AfterEffectsExperimentations
|
5eae44e81c867ee44d00f88aaefaef578f7c3de7
|
[
"MIT"
] | 2
|
2021-10-09T03:47:42.000Z
|
2022-02-06T06:34:31.000Z
|
Examples/AEGP/Artie/Artie.cpp
|
richardlalancette/AfterEffectsExperimentations
|
5eae44e81c867ee44d00f88aaefaef578f7c3de7
|
[
"MIT"
] | null | null | null |
Examples/AEGP/Artie/Artie.cpp
|
richardlalancette/AfterEffectsExperimentations
|
5eae44e81c867ee44d00f88aaefaef578f7c3de7
|
[
"MIT"
] | null | null | null |
/*******************************************************************/
/* */
/* ADOBE CONFIDENTIAL */
/* _ _ _ _ _ _ _ _ _ _ _ _ _ */
/* */
/* Copyright 2007 Adobe Systems Incorporated */
/* All Rights Reserved. */
/* */
/* NOTICE: All information contained herein is, and remains the */
/* property of Adobe Systems Incorporated and its suppliers, if */
/* any. The intellectual and technical concepts contained */
/* herein are proprietary to Adobe Systems Incorporated and its */
/* suppliers and may be covered by U.S. and Foreign Patents, */
/* patents in process, and are protected by trade secret or */
/* copyright law. Dissemination of this information or */
/* reproduction of this material is strictly forbidden unless */
/* prior written permission is obtained from Adobe Systems */
/* Incorporated. */
/* */
/*******************************************************************/
#include "Artie.h"
static AEGP_PluginID S_aegp_plugin_id;
static SPBasicSuite *S_sp_basic_suiteP;
static A_Err
Artie_DisposeLights(
const PR_InData *in_dataP,
AEGP_MemHandle lightsH)
{
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
return suites.MemorySuite1()->AEGP_FreeMemHandle(lightsH);
}
static A_Err
Artie_GetPlaneEquation(
Artie_Poly *polyP,
A_FpLong *aFP,
A_FpLong *bFP,
A_FpLong *cFP,
A_FpLong *dFP)
{
A_Err err = A_Err_NONE;
A_FpLong sum_x = 0,
sum_y = 0,
sum_z = 0;
for (A_long iL = 0; iL < 4; iL++) {
sum_x += polyP->vertsA[iL].coord.P[0];
sum_y += polyP->vertsA[iL].coord.P[1];
sum_z += polyP->vertsA[iL].coord.P[2];
}
sum_x *= 0.25;
sum_y *= 0.25;
sum_z *= 0.25;
*aFP = polyP->normal.V[0];
*bFP = polyP->normal.V[1];
*cFP = polyP->normal.V[2];
*dFP = -(sum_x * (*aFP) + sum_y * (*bFP) + sum_z * (*cFP));
return err;
}
static A_Err
Artie_RayIntersectPlane(
Artie_Poly *polyP,
Ray *rayP,
A_FpLong *tPF)
{
A_Err err = A_Err_NONE;
A_FpLong topF = 0.0,
bottomF = 0.0,
aFP = 0.0,
bFP = 0.0,
cFP = 0.0,
dFP = 0.0;
VectorType4D dir;
ERR(Artie_GetPlaneEquation(polyP, &aFP, &bFP, &cFP, &dFP));
if (!err) {
dir = Pdiff(rayP->P1, rayP->P0);
bottomF = aFP * dir.V[0] +bFP * dir.V[1] + cFP * dir.V[2];
if (bottomF){
topF = -(dFP + aFP*rayP->P0.P[0] + bFP*rayP->P0.P[1] + cFP*rayP->P0.P[2]);
*tPF = topF / bottomF;
} else {
*tPF = Artie_MISS;
}
}
return err;
}
static A_Err
Artie_RayIntersectLayer(
Artie_Poly *polyP,
Ray *rayP,
A_FpLong *tPF,
A_FpLong *uPF,
A_FpLong *vPF)
{
A_Err err = A_Err_NONE;
A_FpLong u0F = 0.0,
v0F = 0.0,
u1F = 0.0,
v1F = 0.0,
u2F = 0.0,
v2F = 0.0,
alphaF = 0.0,
betaF = 0.0,
gammaF = 0.0;
A_Boolean insideB = FALSE;
A_long i1L = 0,
i2 = 0,
kL = 0;
PointType4D P;
VectorType4D dir;
*uPF = *vPF = -1;
ERR(Artie_RayIntersectPlane(polyP, rayP, tPF));
if ( *tPF != Artie_MISS) {
// find uv-coords
dir = Pdiff(rayP->P1, rayP->P0);
P.P[0] = rayP->P0.P[0] + dir.V[0] * *tPF;
P.P[1] = rayP->P0.P[1] + dir.V[1] * *tPF;
P.P[2] = rayP->P0.P[2] + dir.V[2] * *tPF;
if (0 == polyP->dominant) {
i1L = 1;
i2 = 2;
} else if ( 1 == polyP->dominant) {
i1L = 0;
i2 = 2;
} else {
i1L = 0;
i2 = 1;
}
u0F = P.P[i1L] - polyP->vertsA[0].coord.P[i1L];
v0F = P.P[i2] - polyP->vertsA[0].coord.P[i2];
kL = 2;
do{
u1F = polyP->vertsA[kL-1].coord.P[i1L] - polyP->vertsA[0].coord.P[i1L];
v1F = polyP->vertsA[kL-1].coord.P[i2] - polyP->vertsA[0].coord.P[i2];
u2F = polyP->vertsA[kL ].coord.P[i1L] - polyP->vertsA[0].coord.P[i1L];
v2F = polyP->vertsA[kL ].coord.P[i2] - polyP->vertsA[0].coord.P[i2];
if (u1F == 0){
betaF = u0F/u2F;
if (betaF >= 0.0 && betaF <= 1.0){
alphaF = (v0F - betaF*v2F)/v1F;
insideB = ((alphaF>=0.) && (alphaF + betaF) <= 1);
}
} else {
betaF = (v0F * u1F - u0F * v1F)/(v2F * u1F - u2F * v1F);
if (betaF >= 0. && betaF <= 1.) {
alphaF = (u0F - betaF*u2F) / u1F;
insideB = ((alphaF >= 0.) && (alphaF + betaF) <= 1);
}
}
} while (!insideB && (++kL < 4));
if (insideB){
gammaF = 1.0 - alphaF - betaF;
*uPF = gammaF * polyP->vertsA[0].txtur[0] + alphaF * polyP->vertsA[kL-1].txtur[0] + betaF * polyP->vertsA[kL].txtur[0];
*vPF = gammaF * polyP->vertsA[0].txtur[1] + alphaF * polyP->vertsA[kL-1].txtur[1] + betaF * polyP->vertsA[kL].txtur[1];
} else {
*tPF = Artie_MISS;
}
}
return err;
}
static A_Err
Artie_FillIntersection(
Ray *rayP,
Artie_Poly *polyP,
A_FpLong t,
A_FpLong u,
A_FpLong v,
Intersection *intersectionP)
{
A_Err err = A_Err_NONE;
AEGP_SuiteHandler suites(S_sp_basic_suiteP);
AEGP_WorldSuite2 *wsP = suites.WorldSuite2();
A_long widthL = 0,
heightL = 0;
A_u_long rowbytesLu = 0;
PF_Pixel8* baseP = NULL;
ERR(wsP->AEGP_GetSize(polyP->texture, &widthL, &heightL));
ERR(wsP->AEGP_GetBaseAddr8(polyP->texture, &baseP));
ERR(wsP->AEGP_GetRowBytes(polyP->texture, &rowbytesLu));
if ( t != Artie_MISS) {
intersectionP->hitB = TRUE;
intersectionP->intersect_point_coord_on_ray = t;
// build reflected ray
VectorType4D dir, reflected_dir;
A_FpLong dotF;
dir = Pdiff(rayP->P1, rayP->P0);
dotF = Dot4D(dir, polyP->normal);
reflected_dir = Vadd(polyP->normal, Vscale(-2.0, dir));
intersectionP->ray.P0 = PVadd(rayP->P0, Vscale(t, dir));
intersectionP->ray.P0 = PVadd(intersectionP->ray.P0, Vscale(0.0001, reflected_dir));
intersectionP->ray.P1 = PVadd(intersectionP->ray.P0, reflected_dir);
intersectionP->ray.depth = rayP->depth + 1;
intersectionP->ray.contribution = rayP->contribution * polyP->material.ksF;
intersectionP->reflectance_percentF = polyP->material.ksF;
if ( u >= 0 && v >= 0 && u <= 1 && v <= 1) {
A_long iL = static_cast<A_long>(u * (widthL-1));
A_long j = static_cast<A_long>(v * (heightL-1));
PF_Pixel8 *pP = baseP + iL;
intersectionP->color_struck_surface = *(PF_Pixel *)((char *)pP + j * rowbytesLu);
}
}
return err;
}
static
Intersection
SceneIntersection(
Artie_Scene *sceneP,
Ray *rayP)
{
A_Err err = A_Err_NONE;
Intersection returned_I,
I[Artie_MAX_POLYGONS];
A_FpLong u = 0.0,
v = 0.0;
returned_I.hitB = FALSE;
returned_I.intersect_point_coord_on_ray = Artie_MISS;
returned_I.reflectance_percentF = 0.0;
for(A_long iL = 0; iL < sceneP->num_polysL; ++iL){
I[iL].hitB = 0;
err = Artie_RayIntersectLayer(&sceneP->polygons[iL], rayP, &I[iL].intersect_point_coord_on_ray, &u, &v);
if (!err && I[iL].intersect_point_coord_on_ray != Artie_MISS){
I[iL].hitB = 1;
}
}
if (!err) {
for(A_long iL = 0; iL < sceneP->num_polysL; iL++) {
if (I[iL].hitB) {
if (I[iL].intersect_point_coord_on_ray < returned_I.intersect_point_coord_on_ray && I[iL].intersect_point_coord_on_ray > 0){
err = Artie_FillIntersection( rayP,
&sceneP->polygons[iL],
I[iL].intersect_point_coord_on_ray,
u,
v,
&returned_I);
}
}
}
}
return returned_I;
}
static A_Err
Artie_DoInstanceDialog(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_DialogResult *resultP) /* << */
{
A_Err err = A_Err_NONE;
in_dataP->msg_func(0, "Add any options for your Artisan here.");
*resultP = PR_DialogResult_NO_CHANGE;
return err;
}
/* allocate flat handle and write flatten instance data into it */
static A_Err
Artie_FlattenInstance(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_FlatHandle *flatPH) /* << */
{
return A_Err_NONE;
}
/* dispose of render data */
static A_Err
Artie_FrameSetdown(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_RenderContextH render_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_RenderDataH render_dataH) /* << */
{
return A_Err_NONE;
}
/* Called immediately before rendering; allocate any render data here */
static A_Err
Artie_FrameSetup(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_RenderContextH render_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_RenderDataH *render_dataPH) /* << */
{
return A_Err_NONE;
}
static A_Err
Artie_GlobalDoAbout(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_GlobalDataH global_dataH) /* <> */
{
A_Err err = A_Err_NONE;
in_dataP->msg_func(err, "Artie the Artisan.");
return err;
}
static A_Err
Artie_GlobalSetdown(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_GlobalDataH global_dataH) /* <> */ // must be disposed by plugin
{
return A_Err_NONE;
}
/* allocate global data here. */
static A_Err
Artie_GlobalSetup(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_GlobalDataH *global_dataPH) /* << */
{
return A_Err_NONE;
}
/* create instance data, using flat_data if supplied */
static A_Err
Artie_SetupInstance(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* >> */
PR_InstanceFlags flags,
PR_FlatHandle flat_dataH0, /* >> */
PR_InstanceDataH *instance_dataPH) /* << */
{
return A_Err_NONE;
}
/* deallocate your instance data */
static A_Err
Artie_SetdownInstance(
const PR_InData *in_dataP, /* >> */
const PR_GlobalContextH global_contextH, /* >> */
const PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* >> */
PR_InstanceDataH instance_dataH) /* >> */ // must be disposed by plugin
{
return A_Err_NONE;
}
static A_Err
Artie_Query(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_QueryContextH query_contextH, /* <> */
PR_QueryType query_type, /* >> */
PR_GlobalDataH global_data, /* >> */
PR_InstanceDataH instance_dataH) /* >> */
{
return A_Err_NONE;
}
static A_Err
Artie_DeathHook(
AEGP_GlobalRefcon plugin_refconP,
AEGP_DeathRefcon refconP)
{
return A_Err_NONE;
}
static A_Err
Artie_BuildLight(
const PR_InData *in_dataP, /* >> */
PR_RenderContextH render_contextH, /* >> */
AEGP_LayerH layerH, /* >> */
Artie_Light *lightP) /* <> */
{
A_Err err = A_Err_NONE;
A_Time comp_time, comp_time_step;
AEGP_StreamVal stream_val;
Artie_Light light;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.LightSuite2()->AEGP_GetLightType(layerH, &lightP->type));
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue(layerH,
AEGP_LayerStream_COLOR,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
light.color.alpha = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.alphaF + 0.5);
light.color.red = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.redF + 0.5);
light.color.green = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.greenF + 0.5);
light.color.blue = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.blueF + 0.5);
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_INTENSITY,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
if (!err){
light.intensityF = stream_val.one_d;
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_CASTS_SHADOWS,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
light.casts_shadowsB = (stream_val.one_d != 0.0);
}
// Normalize intensity
if (!err){
lightP->intensityF *= 0.01;
light.direction.x = 0;
light.direction.y = 0;
light.direction.z = 1;
light.position.x = 0;
light.position.y = 0;
light.position.z = 0;
// GetLightAttenuation was also unimplemented and only returned this constant.
light.attenuation.x = 1;
light.attenuation.y = 0;
light.attenuation.z = 0;
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_CONE_ANGLE,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
light.cone_angleF = stream_val.one_d;
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_CONE_FEATHER,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
light.spot_exponentF = stream_val.one_d;
ERR(suites.LayerSuite5()->AEGP_GetLayerToWorldXform( layerH,
&comp_time,
&light.light_to_world_matrix));
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_SHADOW_DARKNESS,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
light.shadow_densityF = stream_val.one_d;
if (!err) {
light.shadow_densityF *= 0.01;
}
if (!err && light.type != AEGP_LightType_PARALLEL) {
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_SHADOW_DIFFUSION,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
light.radiusF = stream_val.one_d;
}
}
return err;
}
static A_Err
Artie_BuildLights(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle *lightsPH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
A_long layers_to_renderL = 0;
Artie_Light *lightP = NULL;
A_Boolean is_activeB = FALSE;
AEGP_LayerH layerH = NULL;;
A_Time comp_time = {0, 1},
comp_time_step = {0, 1};
AEGP_CompH compH = NULL;
AEGP_ObjectType layer_type = AEGP_ObjectType_NONE;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( S_aegp_plugin_id,
"Light Data",
sizeof(Artie_Light),
AEGP_MemFlag_CLEAR,
lightsPH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*lightsPH, reinterpret_cast<void**>(&lightP)));
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(suites.LayerSuite5()->AEGP_GetCompNumLayers(compH, &layers_to_renderL));
for (A_long iL = 0; !err && iL < layers_to_renderL && iL < Artie_MAX_LIGHTS; iL++){
ERR(suites.LayerSuite5()->AEGP_GetCompLayerByIndex(compH, iL, &layerH));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.LayerSuite5()->AEGP_IsVideoActive(layerH,
AEGP_LTimeMode_CompTime,
&comp_time,
&is_activeB));
ERR(suites.LayerSuite5()->AEGP_GetLayerObjectType(layerH, &layer_type));
if (!err && (AEGP_ObjectType_LIGHT == layer_type) && is_activeB){
err = Artie_BuildLight(in_dataP, render_contextH, layerH, lightP);
}
if (!err){
lightP->num_lightsL++;
}
}
if (lightP){
ERR(suites.MemorySuite1()->AEGP_UnlockMemHandle(*lightsPH));
}
if (lightsPH){
ERR2(Artie_DisposeLights(in_dataP, *lightsPH));
}
return err;
}
static A_Err
Artie_CompositeImage(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_LayerQuality quality,
AEGP_WorldH *srcP,
AEGP_WorldH *dstP)
{
A_Err err = A_Err_NONE;
PF_CompositeMode comp_mode;
PF_Quality pf_quality = PF_Quality_HI;
PF_Pixel8 *src_pixelsP = NULL;
PF_Pixel8 *dst_pixelsP = NULL;
PF_EffectWorld src_effect_world;
PF_EffectWorld dst_effect_world;
A_long src_widthL = 0,
src_heightL = 0,
dst_widthL = 0,
dst_heightL = 0;
A_Rect src_rect = {0, 0, 0, 0};
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
A_u_long src_rowbytesLu = 0,
dst_rowbytesLu = 0;
PF_Pixel8 *src_baseP = 0,
*dst_baseP = 0;
ERR(suites.WorldSuite3()->AEGP_GetSize(*srcP, &src_widthL, &src_heightL));
ERR(suites.WorldSuite3()->AEGP_GetSize(*dstP, &dst_widthL, &dst_heightL));
src_rect.bottom = static_cast<A_short>(src_heightL);
src_rect.right = static_cast<A_short>(src_widthL);
comp_mode.xfer = PF_Xfer_IN_FRONT;
comp_mode.rand_seed = 3141;
comp_mode.opacity = 255;
comp_mode.rgb_only = FALSE;
ERR(suites.WorldSuite3()->AEGP_FillOutPFEffectWorld(*srcP, &src_effect_world));
ERR(suites.WorldSuite3()->AEGP_FillOutPFEffectWorld(*dstP, &dst_effect_world));
ERR(suites.CompositeSuite2()->AEGP_TransferRect(pf_quality,
PF_MF_Alpha_STRAIGHT,
PF_Field_FRAME,
&src_rect,
&src_effect_world,
&comp_mode,
NULL,
NULL,
dst_widthL,
dst_heightL,
&dst_effect_world));
return err;
}
static PF_Pixel
Raytrace(
const PR_InData *in_dataP,
Artie_Scene *sceneP,
Ray *rayP)
{
Intersection I;
VectorType4D Nhat,Rvec, Rrefl;
Ray RefRay;
PF_Pixel cFP, crefl;
A_FpLong cosThetaI;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (rayP->contribution < Artie_RAYTRACE_THRESHOLD){
cFP.red = 0;
cFP.green = 0;
cFP.blue = 0;
cFP.alpha = 0;
return cFP;
}
if (rayP->depth > Artie_MAX_RAY_DEPTH) {
cFP.red = 0;
cFP.green = 0;
cFP.blue = 0;
cFP.alpha = 0;
return cFP;
}
I = SceneIntersection(sceneP, rayP);
if (I.hitB){
cFP.red = I.color_struck_surface.red;
cFP.green = I.color_struck_surface.green;
cFP.blue = I.color_struck_surface.blue;
cFP.alpha = I.color_struck_surface.alpha;
Nhat = Normalize(suites.ANSICallbacksSuite1()->sqrt, Pdiff(I.ray.P1, I.ray.P0));
Rvec = Normalize(suites.ANSICallbacksSuite1()->sqrt, Pdiff(rayP->P1, rayP->P0));
/* Compute the direction of the reflected ray */
cosThetaI = -Dot4D(Rvec, Nhat);
Rrefl = Vadd(Rvec, Vscale(2.0 * cosThetaI, Nhat));
if (I.reflectance_percentF){
/* Cast aFP reflected ray */
RefRay = CreateRay(I.ray.P0, PVadd(I.ray.P0, Rrefl));
RefRay.contribution = rayP->contribution * I.reflectance_percentF;
RefRay.depth = rayP->depth + 1;
crefl = Raytrace(in_dataP, sceneP, &RefRay);
cFP.red += (A_u_char)(I.reflectance_percentF * crefl.red);
cFP.green += (A_u_char)(I.reflectance_percentF * crefl.green);
cFP.blue += (A_u_char)(I.reflectance_percentF * crefl.blue);
}
} else {
cFP.red = 0;
cFP.green = 0;
cFP.blue = 0;
cFP.alpha = 0;
}
return cFP;
}
static
PF_Pixel ThrowRay(
const PR_InData *in_dataP,
Artie_Scene *sceneP,
A_FpLong xF,
A_FpLong yF,
A_FpLong zF)
{
Ray R;
PointType4D P0, P1;
P0.P[X] = 0;
P0.P[Y] = 0;
P0.P[Z] = 0;
P0.P[W] = 1;
P1.P[X] = xF;
P1.P[Y] = yF;
P1.P[Z] = zF;
P1.P[W] = 1;
R = CreateRay(P0, P1);
R.contribution = 1.0;
R.depth = 0;
return Raytrace(in_dataP, sceneP, &R);
}
static A_Err
Artie_SampleImage(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
Artie_Scene *sceneP,
Artie_Camera *cameraP,
AEGP_WorldH *rwP)
{
A_Err err = A_Err_NONE;
A_FpLong x = 0,
y = 0,
z = cameraP->focal_lengthF;
PF_Pixel8 *pixelP = NULL,
*baseP = NULL;
A_long widthL = 0,
heightL = 0;
A_u_long rowbytesLu = 0;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.WorldSuite2()->AEGP_GetSize(*rwP, &widthL, &heightL));
ERR(suites.WorldSuite2()->AEGP_GetBaseAddr8(*rwP, &baseP));
ERR(suites.WorldSuite2()->AEGP_GetRowBytes(*rwP, &rowbytesLu));
if (z < 0){
z *= -1;
}
for (A_long iL = 0; iL < heightL; iL++) {
y = -heightL/2.0 + iL + 0.5;
pixelP = (PF_Pixel8*)( (char *)baseP + iL * rowbytesLu);
for (A_long jL = 0; jL < widthL; jL++){
x = -widthL / 2.0 + jL + 0.5;
*pixelP++ = ThrowRay( in_dataP, sceneP, x, y, z);
}
}
return err;
}
static A_Err
Artie_TransformPolygon(
Artie_Poly *polyP,
const A_Matrix4 *xformP)
{
A_Err err = A_Err_NONE;
A_Matrix4 inverse,
normal_xformP;
for(A_long iL = 0; iL < 4; iL++) {
ERR(TransformPoint4(&polyP->vertsA[iL].coord, xformP, &polyP->vertsA[iL].coord));
}
ERR(InverseMatrix4(xformP, &inverse));
ERR(TransposeMatrix4(&inverse, &normal_xformP));
ERR(TransformVector4(&polyP->normal, &normal_xformP, &polyP->normal));
if (!err){
// find dominant axis;
polyP->dominant = 2;
if (ABS(polyP->normal.V[0]) > ABS(polyP->normal.V[1])) {
if (ABS(polyP->normal.V[0]) > ABS(polyP->normal.V[2])) {
polyP->dominant = 0;
} else {
polyP->dominant = 2;
}
} else if (ABS(polyP->normal.V[1]) > ABS(polyP->normal.V[2])) {
polyP->dominant = 1;
} else {
polyP->dominant = 2;
}
}
return err;
}
static A_Err
Artie_TransformScene(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
Artie_Scene *sceneP,
Artie_Camera *cameraP)
{
A_Err err = A_Err_NONE;
A_Matrix4 composite,
up_sample,
world,
view,
down_sample;
ERR(ScaleMatrix4( cameraP->dsf.xS, cameraP->dsf.yS, 1.0, &up_sample));
ERR(ScaleMatrix4( 1.0 / cameraP->dsf.xS, 1.0 / cameraP->dsf.yS, 1.0, &down_sample));
if (!err){
view = cameraP->view_matrix;
}
for(A_long iL = 0; iL < sceneP->num_polysL; iL++) {
world = sceneP->polygons[iL].world_matrix;
ERR(MultiplyMatrix4(&up_sample, &world, &composite));
ERR(MultiplyMatrix4(&composite, &view, &composite));
ERR(MultiplyMatrix4(&composite, &down_sample, &composite));
ERR(Artie_TransformPolygon(&sceneP->polygons[iL], &composite));
}
return err;
}
static A_Err
Artie_Paint(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle sceneH,
AEGP_MemHandle cameraH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
Artie_Camera *cameraP = NULL;
AEGP_WorldH render_world;
AEGP_WorldH dst;
AEGP_CompH compH = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
A_long widthL = 0,
heightL = 0;
AEGP_ItemH comp_itemH = NULL;
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(sceneH, reinterpret_cast<void**>(&sceneP)));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(cameraH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(suites.CompSuite4()->AEGP_GetItemFromComp(compH, &comp_itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemDimensions(comp_itemH, &widthL, &heightL));
ERR(suites.CanvasSuite5()->AEGP_GetCompDestinationBuffer(render_contextH, compH, &dst));
ERR(suites.WorldSuite2()->AEGP_New( S_aegp_plugin_id,
AEGP_WorldType_8,
widthL,
heightL,
&render_world));
ERR(Artie_TransformScene( in_dataP,
render_contextH,
sceneP,
cameraP));
ERR(Artie_SampleImage( in_dataP,
render_contextH,
sceneP,
cameraP,
&render_world));
ERR(Artie_CompositeImage( in_dataP,
render_contextH,
0,
&render_world,
&dst));
if (dst){
ERR2(suites.WorldSuite2()->AEGP_Dispose(render_world));
}
if (sceneP){
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(sceneH));
}
if (cameraP){
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(cameraH));
}
return err;
}
static A_Err
Artie_CreateListOfLayerContexts(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
A_long *num_layersPL,
Artie_LayerContexts *layer_contexts)
{
A_Err err = A_Err_NONE;
AEGP_RenderLayerContextH layer_contextH = NULL;
A_long local_layers_to_renderL = 0;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
AEGP_CanvasSuite5 *csP = suites.CanvasSuite5();
*num_layersPL = 0;
err = csP->AEGP_GetNumLayersToRender(render_contextH, &local_layers_to_renderL);
if (!err) {
for(A_long iL = 0; (!err && (iL < local_layers_to_renderL) && (iL < Artie_MAX_POLYGONS)); iL++){
ERR(csP->AEGP_GetNthLayerContextToRender(render_contextH, iL, &layer_contextH));
if (!err){
layer_contexts->layer_contexts[iL] = layer_contextH;
layer_contexts->count++;
}
}
*num_layersPL = local_layers_to_renderL;
}
return err;
}
static A_Err
Artie_GetSourceLayerSize(
const PR_InData *in_dataP, /* >> */
PR_RenderContextH render_contextH, /* >> */
AEGP_LayerH layerH, /* >> */
A_FpLong *widthPF, /* << */
A_FpLong *heightPF, /* << */
AEGP_DownsampleFactor *dsfP)
{
A_Err err = A_Err_NONE;
AEGP_ItemH source_itemH = NULL;
AEGP_DownsampleFactor dsf = {1, 1};
A_long widthL = 0,
heightL = 0;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (widthPF == NULL ||
heightPF == NULL ||
dsfP == NULL){
err = A_Err_PARAMETER;
}
if (!err){
if (widthPF){
*widthPF = 0.0;
}
if (heightPF){
*heightPF = 0.0;
}
if (dsfP) {
dsfP->xS =
dsfP->yS = 1;
}
// This doesn't return a valid item if the layer is a text layer
// Use AEGP_GetCompRenderTime, AEGP_GetRenderLayerBounds, AEGP_GetRenderDownsampleFactor instead?
ERR(suites.LayerSuite5()->AEGP_GetLayerSourceItem(layerH, &source_itemH));
if (!err && source_itemH){
err = suites.ItemSuite6()->AEGP_GetItemDimensions(source_itemH, &widthL, &heightL);
if (!err){
*widthPF = widthL / (A_FpLong)dsf.xS;
*heightPF = heightL / (A_FpLong)dsf.yS;
ERR(suites.CanvasSuite5()->AEGP_GetRenderDownsampleFactor(render_contextH, &dsf));
if (!err && dsfP){
*dsfP = dsf;
}
}
}
}
return err;
}
static A_Err
Artie_DisposePolygonTexture(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
Artie_Poly *polygonP)
{
A_Err err = A_Err_NONE;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
AEGP_CanvasSuite5 *canP = suites.CanvasSuite5();
if (polygonP->texture){
err = canP->AEGP_DisposeTexture(render_contextH, polygonP->layer_contextH, polygonP->texture);
}
return err;
}
/**
** get the pixels and the vertices
** if quality = wireframe, just get the dimensions
**
** we wait until this routine to get the layer dimension as its height and width
** may change with buffer expanding effects applied.
**/
static A_Err
Artie_GetPolygonTexture(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_RenderHints render_hints,
A_Boolean *is_visiblePB,
Artie_Poly *polygonP)
{
A_Err err = A_Err_NONE;
A_FpLong widthF = 0.0, heightF = 0.0;
AEGP_DownsampleFactor dsf = {1, 1};
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
*is_visiblePB = FALSE;
if (!polygonP->texture){
// no texture map yet
// if we're in wireframe, there is no texture.
// we still need the dimensions, so we'll get the layers source dimensions and use that.
// we'll also need to correct for the comp down sampling as all textures have this correction
if ( polygonP->aegp_quality == AEGP_LayerQual_WIREFRAME){
ERR(Artie_GetSourceLayerSize( in_dataP,
render_contextH,
polygonP->layerH,
&widthF,
&heightF,
&dsf));
if (!err){
polygonP->origin.x = 0;
polygonP->origin.y = 0;
}
} else {
ERR(suites.CanvasSuite5()->AEGP_RenderTexture( render_contextH,
polygonP->layer_contextH,
AEGP_RenderHints_NONE,
NULL,
NULL,
NULL,
&polygonP->texture));
}
if (!err && polygonP->texture) {
*is_visiblePB = TRUE;
}
if (!err && *is_visiblePB){
A_FpLong widthL = 0,
heightL = 0;
err = Artie_GetSourceLayerSize( in_dataP,
render_contextH,
polygonP->layerH,
&widthL,
&heightL,
&dsf);
if (!err){
polygonP->origin.x /= (A_FpLong)dsf.xS;
polygonP->origin.y /= (A_FpLong)dsf.yS;
}
}
// construct the polygon vertices in local ( pixel) space.
if (!err && *is_visiblePB) {
A_long widthL = 0, heightL = 0;
ERR(suites.WorldSuite2()->AEGP_GetSize(polygonP->texture, &widthL, &heightL));
widthF = static_cast<A_FpLong>(widthL);
heightF = static_cast<A_FpLong>(heightL);
// counterclockwise specification -- for texture map
//vertex 0
polygonP->vertsA[0].coord.P[0] = -polygonP->origin.x;
polygonP->vertsA[0].coord.P[1] = -polygonP->origin.y;
polygonP->vertsA[0].coord.P[2] = 0;
polygonP->vertsA[0].coord.P[3] = 1;
polygonP->vertsA[0].txtur[0] = 0.0;
polygonP->vertsA[0].txtur[1] = 0.0;
polygonP->vertsA[0].txtur[2] = 1;
// vertex 1
polygonP->vertsA[1].coord.P[0] = -polygonP->origin.x;
polygonP->vertsA[1].coord.P[1] = heightF - polygonP->origin.y;
polygonP->vertsA[1].coord.P[2] = 0.0;
polygonP->vertsA[1].coord.P[3] = 1;
polygonP->vertsA[1].txtur[0] = 0.0;
polygonP->vertsA[1].txtur[1] = 1.0;
polygonP->vertsA[1].txtur[2] = 1;
//vertex 2
polygonP->vertsA[2].coord.P[0] = widthF - polygonP->origin.x ;
polygonP->vertsA[2].coord.P[1] = heightF - polygonP->origin.y ;
polygonP->vertsA[2].coord.P[2] = 0;
polygonP->vertsA[2].coord.P[3] = 1;
polygonP->vertsA[2].txtur[0] = 1.0;
polygonP->vertsA[2].txtur[1] = 1.0;
polygonP->vertsA[2].txtur[2] = 1;
// vertex 3
polygonP->vertsA[3].coord.P[0] = (widthF - polygonP->origin.x);
polygonP->vertsA[3].coord.P[1] = -polygonP->origin.y;
polygonP->vertsA[3].coord.P[2] = 0;
polygonP->vertsA[3].coord.P[3] = 1;
polygonP->vertsA[3].txtur[0] = 1.0;
polygonP->vertsA[3].txtur[1] = 0.0;
polygonP->vertsA[3].txtur[2] = 1;
}
}
return err;
}
static A_Err
Artie_BuildPolygon(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_RenderLayerContextH layer_contextH,
AEGP_LayerH layerH,
A_Matrix4 *xform,
A_FpLong widthF,
A_FpLong heightF,
PF_CompositeMode *composite_mode,
Artie_Material *material,
AEGP_TrackMatte *track_matte,
AEGP_LayerQuality *aegp_quality,
Artie_Poly *polygonP) /* <> */
{
A_Err err = A_Err_NONE;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
AEFX_CLR_STRUCT(*polygonP);
polygonP->aegp_quality = *aegp_quality;
polygonP->layerH = layerH;
polygonP->layer_contextH = layer_contextH;
polygonP->normal.V[X] = 0;
polygonP->normal.V[Y] = 0;
polygonP->normal.V[Z] = -1;
polygonP->normal.V[W] = 0;
polygonP->material = *material;
polygonP->world_matrix = *xform;
// fill in vertices and texture map
err = Artie_GetPolygonTexture( in_dataP,
render_contextH,
AEGP_RenderHints_NONE,
&polygonP->is_visibleB,
polygonP);
return err;
}
static A_Err
Artie_AddPolygonToScene(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
A_long indexL,
AEGP_RenderLayerContextH layer_contextH,
AEGP_LayerH layerH,
AEGP_MemHandle sceneH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
PF_CompositeMode composite_mode;
AEGP_TrackMatte track_matte;
A_Matrix4 xform;
AEGP_LayerQuality aegp_quality;
AEGP_LayerFlags layer_flags;
AEGP_LayerTransferMode layer_transfer_mode;
Artie_Poly poly;
A_FpLong opacityF = 0.0,
widthF = 0.0,
heightF = 0.0;
A_long seedL = 0;
Artie_Material material;
A_Time comp_time = {0,1},
comp_time_step = {0,1};
AEGP_StreamVal stream_val;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(sceneH, reinterpret_cast<void**>(&sceneP)));
ERR(suites.LayerSuite5()->AEGP_GetLayerFlags(layerH, &layer_flags));
ERR(suites.LayerSuite5()->AEGP_GetLayerTransferMode(layerH, &layer_transfer_mode));
ERR(suites.LayerSuite5()->AEGP_GetLayerQuality(layerH, &aegp_quality));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.LayerSuite5()->AEGP_GetLayerToWorldXform(layerH, &comp_time, &xform));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.CanvasSuite5()->AEGP_GetRenderOpacity(render_contextH, layer_contextH, &comp_time, &opacityF));
ERR(suites.LayerSuite5()->AEGP_GetLayerDancingRandValue(layerH, &comp_time, &seedL));
if (!err) {
composite_mode.xfer = layer_transfer_mode.mode;
composite_mode.rand_seed = seedL;
composite_mode.opacity = (unsigned char) (255.0 * opacityF / 100.0 + 0.5);
composite_mode.rgb_only = (layer_transfer_mode.flags & AEGP_TransferFlag_PRESERVE_ALPHA) != 0;
track_matte = layer_transfer_mode.track_matte;
}
// get polygon material
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue(layerH,
AEGP_LayerStream_AMBIENT_COEFF,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
if (!err){
material.kaF = stream_val.one_d;
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_DIFFUSE_COEFF,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
material.kdF = stream_val.one_d;
}
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_SPECULAR_INTENSITY,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
// Normalize coeffs
if (!err) {
material.ksF = stream_val.one_d;
material.kaF *= 0.01;
material.kdF *= 0.01;
material.ksF *= 0.01;
}
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue(layerH,
AEGP_LayerStream_SPECULAR_SHININESS,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
if (!err) {
material.specularF = stream_val.one_d;
AEGP_DownsampleFactor dsf = {1,1};
err = Artie_GetSourceLayerSize( in_dataP,
render_contextH,
layerH,
&widthF,
&heightF,
&dsf);
}
ERR(Artie_BuildPolygon( in_dataP,
render_contextH,
layer_contextH,
layerH,
&xform,
widthF,
heightF,
&composite_mode,
&material,
&track_matte,
&aegp_quality,
&poly));
if (!err) {
sceneP->polygons[indexL] = poly;
sceneP->num_polysL++;
}
if (sceneP) {
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(sceneH));
}
return err;
}
static A_Err
Artie_DisposeScene(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle sceneH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (sceneH) {
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(sceneH, reinterpret_cast<void**>(&sceneP)));
if (!err) {
for(A_long iL = 0; iL< sceneP->num_polysL; iL++){
ERR(Artie_DisposePolygonTexture(in_dataP, render_contextH, &sceneP->polygons[iL]));
}
}
ERR2(suites.MemorySuite1()->AEGP_FreeMemHandle(sceneH));
}
return err;
}
static A_Err
Artie_BuildScene(
const PR_InData *in_dataP,
Artie_LayerContexts layer_contexts,
PR_RenderContextH render_contextH,
AEGP_MemHandle *scenePH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
AEGP_LayerH layerH = NULL;
AEGP_CompH compH = NULL;
AEGP_ItemH source_itemH = NULL;
AEGP_ItemFlags item_flags = 0;
A_long layers_to_renderL = 0;
AEGP_MemHandle lightsH = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( in_dataP->aegp_plug_id,
"Scene Data",
sizeof(Artie_Scene),
AEGP_MemFlag_CLEAR,
scenePH));
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(Artie_CreateListOfLayerContexts(in_dataP,
render_contextH,
&layers_to_renderL,
&layer_contexts));
ERR(Artie_BuildLights(in_dataP, render_contextH, &lightsH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*scenePH, reinterpret_cast<void**>(&sceneP)));
for(A_long iL = 0; iL < layers_to_renderL; iL++){
ERR(suites.CanvasSuite5()->AEGP_GetLayerFromLayerContext( render_contextH,
layer_contexts.layer_contexts[iL],
&layerH));
ERR(suites.LayerSuite5()->AEGP_GetLayerSourceItem(layerH, &source_itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemFlags(source_itemH, &item_flags));
if (item_flags & AEGP_ItemFlag_HAS_VIDEO){
ERR(Artie_AddPolygonToScene( in_dataP,
render_contextH,
iL,
layer_contexts.layer_contexts[iL],
layerH,
*scenePH));
}
}
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(*scenePH));
return err;
}
static A_Err
Artie_DisposeCamera(
const PR_InData *in_dataP,
AEGP_MemHandle cameraH)
{
A_Err err = A_Err_NONE;
Artie_Camera *cameraP = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (!cameraH) {
err = PF_Err_UNRECOGNIZED_PARAM_TYPE;
in_dataP->msg_func(err, "Trying to dispose NULL camera");
}
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(cameraH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.MemorySuite1()->AEGP_FreeMemHandle(cameraH));
return err;
}
static A_Err
Artie_CreateDefaultCamera(
const PR_InData *in_dataP,
AEGP_CompH compH,
AEGP_DownsampleFactor *dsfP,
AEGP_MemHandle *cameraPH)
{
A_Err err = A_Err_NONE;
Artie_Camera *cameraP = NULL;
AEGP_ItemH itemH = NULL;
A_long widthL = 0,
heightL = 0;
A_FpLong comp_origin_xF = 0.0,
comp_origin_yF = 0.0,
min_dimensionF = 0.0;
A_Matrix4 matrix;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
*cameraPH = NULL;
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( in_dataP->aegp_plug_id,
"Camera Data",
sizeof(Artie_Camera),
AEGP_MemFlag_CLEAR,
cameraPH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*cameraPH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.CompSuite4()->AEGP_GetItemFromComp(compH, &itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemDimensions(itemH, &widthL, &heightL));
// comp origin is the middle of the comp in x and y, and z = 0.
if (!err){
comp_origin_xF = widthL / 2.0;
comp_origin_yF = heightL / 2.0;
min_dimensionF = MIN(comp_origin_xF, comp_origin_yF);
A_FpLong tanF = suites.ANSICallbacksSuite1()->tan(0.5 * Artie_DEFAULT_FIELD_OF_VIEW);
cameraP->type = AEGP_CameraType_PERSPECTIVE;
cameraP->res_xLu = static_cast<A_u_long>(widthL);
cameraP->res_yLu = static_cast<A_u_long>(heightL);
cameraP->focal_lengthF = min_dimensionF / tanF;
cameraP->dsf = *dsfP;
ERR(IdentityMatrix4(&matrix));
ERR(TranslateMatrix4(comp_origin_xF,
comp_origin_yF,
-cameraP->focal_lengthF,
&matrix));
ERR(InverseMatrix4(&matrix, &cameraP->view_matrix));
ERR(suites.MemorySuite1()->AEGP_UnlockMemHandle(*cameraPH));
}
return err;
}
static A_Err
Artie_CreateLayerCamera(
const PR_InData *in_dataP,
AEGP_CompH compH,
AEGP_DownsampleFactor *dsfP,
A_Time comp_time,
A_Rect *roiRP0,
AEGP_LayerH camera_layerH,
AEGP_MemHandle *cameraPH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Camera *cameraP = NULL;
AEGP_ItemH itemH = NULL;
A_long widthL = 0,
heightL = 0;
A_Ratio pix_aspectR = {1,1};
A_FpLong comp_origin_xF = 0.0,
comp_origin_yF = 0.0;
A_Matrix4 matrix;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
*cameraPH = NULL;
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( in_dataP->aegp_plug_id,
"Camera Data",
sizeof(Artie_Camera),
AEGP_MemFlag_CLEAR,
cameraPH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*cameraPH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.CompSuite4()->AEGP_GetItemFromComp(compH, &itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemDimensions(itemH, &widthL, &heightL));
ERR(suites.ItemSuite6()->AEGP_GetItemPixelAspectRatio(itemH, &pix_aspectR));
// comp origin is the middle of the comp in x and y, and z = 0.
if (!err) {
comp_origin_xF = widthL / 2.0;
comp_origin_yF = heightL / 2.0;
cameraP->view_aspect_ratioF = widthL / heightL;
cameraP->pixel_aspect_ratioF = pix_aspectR.num / pix_aspectR.den;
cameraP->dsf = *dsfP;
}
ERR(suites.LayerSuite5()->AEGP_GetLayerToWorldXform(camera_layerH, &comp_time, &matrix));
ERR(InverseMatrix4(&matrix, &cameraP->view_matrix));
ERR(suites.CameraSuite2()->AEGP_GetCameraType(camera_layerH, &cameraP->type));
if (!err) {
cameraP->res_xLu = (unsigned long) widthL;
cameraP->res_yLu = (unsigned long) heightL;
cameraP->dsf = *dsfP;
if (roiRP0){
cameraP->roiR = *roiRP0;
}
}
if (cameraP){
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(*cameraPH));
}
if (*cameraPH){
ERR2(Artie_DisposeCamera(in_dataP, *cameraPH));
*cameraPH = NULL;
}
return err;
}
static A_Err
Artie_BuildCamera(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle *cameraPH)
{
A_Err err = A_Err_NONE;
AEGP_LayerH camera_layerH = NULL;
A_Time render_time = {0,1},
time_step = {0,1};
AEGP_DownsampleFactor dsf = {1,1};
AEGP_CompH compH = NULL;
A_LegacyRect roiLR = {0,0,0,0};
A_Rect roiR = {0,0,0,0};
*cameraPH = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(suites.CanvasSuite5()->AEGP_GetRenderDownsampleFactor(render_contextH, &dsf));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &render_time, &time_step));
ERR(suites.CameraSuite2()->AEGP_GetCamera(render_contextH, &render_time, &camera_layerH));
ERR(suites.CanvasSuite5()->AEGP_GetROI(render_contextH, &roiLR));
if (!err && !camera_layerH){
ERR(Artie_CreateDefaultCamera(in_dataP, compH, &dsf, cameraPH));
} else {
roiR.top = roiLR.top;
roiR.left = roiLR.left;
roiR.right = roiLR.right;
roiR.bottom = roiLR.bottom;
ERR(Artie_CreateLayerCamera( in_dataP,
compH,
&dsf,
render_time,
&roiR,
camera_layerH,
cameraPH));
}
return err;
}
static A_Err
Artie_Render(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_RenderContextH render_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_RenderDataH render_dataH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
AEGP_MemHandle cameraH = NULL;
AEGP_MemHandle sceneH = NULL;
Artie_LayerContexts layer_contexts;
AEFX_CLR_STRUCT(layer_contexts);
ERR(Artie_BuildCamera(in_dataP, render_contextH, &cameraH));
if (cameraH){
ERR(Artie_BuildScene(in_dataP, layer_contexts, render_contextH, &sceneH));
if (sceneH){
ERR(Artie_Paint(in_dataP, render_contextH, sceneH, cameraH));
ERR2(Artie_DisposeScene(in_dataP, render_contextH, sceneH));
ERR2(Artie_DisposeCamera(in_dataP, cameraH));
}
}
return err;
}
A_Err
EntryPointFunc(
struct SPBasicSuite *pica_basicP, /* >> */
A_long major_versionL, /* >> */
A_long minor_versionL, /* >> */
AEGP_PluginID aegp_plugin_id, /* >> */
AEGP_GlobalRefcon *plugin_refconP) /* << */
{
A_Err err = A_Err_NONE;
A_Version api_version;
A_Version artisan_version;
char match_nameA[PR_PUBLIC_MATCH_NAME_LEN];
char artisan_nameA[PR_PUBLIC_ARTISAN_NAME_LEN];
PR_ArtisanEntryPoints entry_funcs;
AEGP_SuiteHandler suites(pica_basicP);
api_version.majorS = PR_ARTISAN_API_VERSION_MAJOR;
api_version.minorS = PR_ARTISAN_API_VERSION_MINOR;
artisan_version.majorS = Artie_MAJOR_VERSION;
artisan_version.minorS = Artie_MAJOR_VERSION;
S_aegp_plugin_id = aegp_plugin_id;
S_sp_basic_suiteP = pica_basicP;
suites.ANSICallbacksSuite1()->strcpy(match_nameA, Artie_ARTISAN_MATCH_NAME);
suites.ANSICallbacksSuite1()->strcpy(artisan_nameA, Artie_ARTISAN_NAME);
// 0 at the end of the name means optional function
// only render_func is not optional.
try {
entry_funcs.do_instance_dialog_func0 = Artie_DoInstanceDialog;
entry_funcs.flatten_instance_func0 = Artie_FlattenInstance;
entry_funcs.frame_setdown_func0 = Artie_FrameSetdown;
entry_funcs.frame_setup_func0 = Artie_FrameSetup;
entry_funcs.global_do_about_func0 = Artie_GlobalDoAbout;
entry_funcs.global_setdown_func0 = Artie_GlobalSetdown;
entry_funcs.global_setup_func0 = Artie_GlobalSetup;
entry_funcs.render_func = Artie_Render;
entry_funcs.setup_instance_func0 = Artie_SetupInstance;
entry_funcs.setdown_instance_func0 = Artie_SetdownInstance;
entry_funcs.query_func0 = Artie_Query;
#ifdef DEBUG
ERR(suites.MemorySuite1()->AEGP_SetMemReportingOn(TRUE));
#endif
ERR(suites.RegisterSuite5()->AEGP_RegisterArtisan( api_version,
artisan_version,
aegp_plugin_id,
plugin_refconP,
match_nameA,
artisan_nameA,
&entry_funcs));
ERR(suites.RegisterSuite5()->AEGP_RegisterDeathHook( S_aegp_plugin_id,
Artie_DeathHook,
NULL));
} catch (A_Err &thrown_err){
err = thrown_err;
}
return err;
}
/* Everything below this line is specific to Artie's implementation, and
has little to do with the Artisan interface. Hopefully, your plug-in
does something more exciting than basic raytracing.
*/
static void
NormalizePoint(
PointType4D *P1)
{
register double *p = P1->P;
register double w = p[W];
if (w != 1.0){
/* We are assuming that the order in P is: X, Y, Z, W */
*p++ /= w;
*p++ /= w;
*p++ /= w;
*p = 1.0;
}
}
static VectorType4D
Normalize(
A_FpLong (*sqrt)(A_FpLong),
VectorType4D v)
{
VectorType4D vout;
A_FpLong l = sqrt( v.V[0]*v.V[0] + v.V[1]*v.V[1] + v.V[2]*v.V[2]);
if (l < Artie_EPSILON){
vout = v;
} else {
vout.V[0] = v.V[0]/l;
vout.V[1] = v.V[1]/l;
vout.V[2] = v.V[2]/l;
vout.V[3] = 0.0;
}
return vout;
}
/* Return the vector V=P1-P0. */
static VectorType4D
Pdiff(
PointType4D P1,
PointType4D P0)
{
VectorType4D V;
NormalizePoint(&P0);
NormalizePoint(&P1);
V.V[0] = P1.P[0] - P0.P[0];
V.V[1] = P1.P[1] - P0.P[1];
V.V[2] = P1.P[2] - P0.P[2];
V.V[3] = 0.0;
return V;
}
/* Return the vector s*V. */
static VectorType4D
Vscale(
PF_FpLong sF,
VectorType4D V)
{
V.V[X] *= sF;
V.V[Y] *= sF;
V.V[Z] *= sF;
V.V[W] = 0.0;
return V;
}
/* Return the vector V1+V1. */
VectorType4D
Vadd(
VectorType4D V1,
VectorType4D V2)
{
VectorType4D V;
V.V[X] = V1.V[X] + V2.V[X];
V.V[Y] = V1.V[Y] + V2.V[Y];
V.V[Z] = V1.V[Z] + V2.V[Z];
V.V[W] = 0.0;
return V;
}
/* Return the point P+V. */
PointType4D
PVadd(
PointType4D P,
VectorType4D V)
{
PointType4D p;
NormalizePoint(&P);
p.P[X] = P.P[X] + V.V[X];
p.P[Y] = P.P[Y] + V.V[Y];
p.P[Z] = P.P[Z] + V.V[Z];
p.P[W] = 1.0;
return p;
}
/* Return the negative of vector V */
VectorType4D
Vneg(
VectorType4D V)
{
V.V[X] = -V.V[X];
V.V[Y] = -V.V[Y];
V.V[Z] = -V.V[Z];
/* since V is aFP vector, V.V[W] is always 0. */
return V;
}
A_FpLong
Dot4D(
VectorType4D v1F,
VectorType4D v2F)
{
return v1F.V[0] * v2F.V[0] + v1F.V[1] * v2F.V[1] + v1F.V[2] * v2F.V[2];
}
A_Err
IdentityMatrix4(
A_Matrix4 *matrixP)
{
AEFX_CLR_STRUCT(*matrixP);
matrixP->mat[0][0] = 1.0;
matrixP->mat[1][1] = 1.0;
matrixP->mat[2][2] = 1.0;
matrixP->mat[3][3] = 1.0;
return A_Err_NONE;
}
A_Err
TranslateMatrix4(
A_FpLong x,
A_FpLong y,
A_FpLong z,
A_Matrix4 *resultP)
{
IdentityMatrix4(resultP);
resultP->mat[3][0] = x;
resultP->mat[3][1] = y;
resultP->mat[3][2] = z;
resultP->mat[3][3] = 1.0;
return A_Err_NONE;
}
A_Err
ScaleMatrix4(
A_FpLong x,
A_FpLong y,
A_FpLong z,
A_Matrix4 *resultP)
{
IdentityMatrix4(resultP);
resultP->mat[0][0] = x;
resultP->mat[1][1] = y;
resultP->mat[2][2] = z;
resultP->mat[3][3] = 1.0;
return A_Err_NONE;
}
A_Err
TransposeMatrix4(
const A_Matrix4 *matrix1,
A_Matrix4 *resultP)
{
register A_u_long iLu, jLu;
A_Matrix4 tmp;
for (iLu = 0 ; iLu < 4 ; iLu++){
for (jLu = 0 ; jLu < 4 ; jLu++) {
tmp.mat[iLu][jLu] = matrix1->mat[jLu][iLu];
}
}
AEFX_COPY_STRUCT(tmp, *resultP);
return A_Err_NONE;
}
/* compute inverse, if no inverse, return adjoint */
A_Err
InverseMatrix4(
const A_Matrix4 *m,
A_Matrix4 *resultP)
{
A_Err err = A_Err_NONE;
A_FpLong d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33,
m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33,
D;
m00 = m->mat[0][0]; m01 = m->mat[0][1]; m02 = m->mat[0][2]; m03 = m->mat[0][3];
m10 = m->mat[1][0]; m11 = m->mat[1][1]; m12 = m->mat[1][2]; m13 = m->mat[1][3];
m20 = m->mat[2][0]; m21 = m->mat[2][1]; m22 = m->mat[2][2]; m23 = m->mat[2][3];
m30 = m->mat[3][0]; m31 = m->mat[3][1]; m32 = m->mat[3][2]; m33 = m->mat[3][3];
d00 = m11*m22*m33 + m12*m23*m31 + m13*m21*m32 - m31*m22*m13 - m32*m23*m11 - m33*m21*m12;
d01 = m10*m22*m33 + m12*m23*m30 + m13*m20*m32 - m30*m22*m13 - m32*m23*m10 - m33*m20*m12;
d02 = m10*m21*m33 + m11*m23*m30 + m13*m20*m31 - m30*m21*m13 - m31*m23*m10 - m33*m20*m11;
d03 = m10*m21*m32 + m11*m22*m30 + m12*m20*m31 - m30*m21*m12 - m31*m22*m10 - m32*m20*m11;
d10 = m01*m22*m33 + m02*m23*m31 + m03*m21*m32 - m31*m22*m03 - m32*m23*m01 - m33*m21*m02;
d11 = m00*m22*m33 + m02*m23*m30 + m03*m20*m32 - m30*m22*m03 - m32*m23*m00 - m33*m20*m02;
d12 = m00*m21*m33 + m01*m23*m30 + m03*m20*m31 - m30*m21*m03 - m31*m23*m00 - m33*m20*m01;
d13 = m00*m21*m32 + m01*m22*m30 + m02*m20*m31 - m30*m21*m02 - m31*m22*m00 - m32*m20*m01;
d20 = m01*m12*m33 + m02*m13*m31 + m03*m11*m32 - m31*m12*m03 - m32*m13*m01 - m33*m11*m02;
d21 = m00*m12*m33 + m02*m13*m30 + m03*m10*m32 - m30*m12*m03 - m32*m13*m00 - m33*m10*m02;
d22 = m00*m11*m33 + m01*m13*m30 + m03*m10*m31 - m30*m11*m03 - m31*m13*m00 - m33*m10*m01;
d23 = m00*m11*m32 + m01*m12*m30 + m02*m10*m31 - m30*m11*m02 - m31*m12*m00 - m32*m10*m01;
d30 = m01*m12*m23 + m02*m13*m21 + m03*m11*m22 - m21*m12*m03 - m22*m13*m01 - m23*m11*m02;
d31 = m00*m12*m23 + m02*m13*m20 + m03*m10*m22 - m20*m12*m03 - m22*m13*m00 - m23*m10*m02;
d32 = m00*m11*m23 + m01*m13*m20 + m03*m10*m21 - m20*m11*m03 - m21*m13*m00 - m23*m10*m01;
d33 = m00*m11*m22 + m01*m12*m20 + m02*m10*m21 - m20*m11*m02 - m21*m12*m00 - m22*m10*m01;
D = m00*d00 - m01*d01 + m02*d02 - m03*d03;
if (D) {
resultP->mat[0][0] = d00/D; resultP->mat[0][1] = -d10/D; resultP->mat[0][2] = d20/D; resultP->mat[0][3] = -d30/D;
resultP->mat[1][0] = -d01/D; resultP->mat[1][1] = d11/D; resultP->mat[1][2] = -d21/D; resultP->mat[1][3] = d31/D;
resultP->mat[2][0] = d02/D; resultP->mat[2][1] = -d12/D; resultP->mat[2][2] = d22/D; resultP->mat[2][3] = -d32/D;
resultP->mat[3][0] = -d03/D; resultP->mat[3][1] = d13/D; resultP->mat[3][2] = -d23/D; resultP->mat[3][3] = d33/D;
} else {
resultP->mat[0][0] = d00; resultP->mat[0][1] = -d10; resultP->mat[0][2] = d20; resultP->mat[0][3] = -d30;
resultP->mat[1][0] = -d01; resultP->mat[1][1] = d11; resultP->mat[1][2] = -d21; resultP->mat[1][3] = d31;
resultP->mat[2][0] = d02; resultP->mat[2][1] = -d12; resultP->mat[2][2] = d22; resultP->mat[2][3] = -d32;
resultP->mat[3][0] = -d03; resultP->mat[3][1] = d13; resultP->mat[3][2] = -d23; resultP->mat[3][3] = d33;
}
return err;
}
A_Err
MultiplyMatrix4(
const A_Matrix4 *A,
const A_Matrix4 *B,
A_Matrix4 *resultP)
{
A_Err err = A_Err_NONE;
A_Matrix4 tmp;
for (register A_u_long iLu = 0; iLu < 4; iLu++){
for (register int jLu = 0; jLu < 4; jLu++) {
tmp.mat[iLu][jLu] = A->mat[iLu][0] * B->mat[0][jLu] +
A->mat[iLu][1] * B->mat[1][jLu] +
A->mat[iLu][2] * B->mat[2][jLu] +
A->mat[iLu][3] * B->mat[3][jLu];
}
}
AEFX_COPY_STRUCT(tmp, *resultP);
return err;
}
A_Err
TransformPoint4(
const PointType4D *pointP,
const A_Matrix4 *transformP,
PointType4D *resultP)
{
A_Err err = A_Err_NONE;
PointType4D tmp;
Artie_TRANSFORM_POINT4(*pointP, *transformP, tmp);
*resultP = tmp;
return err;
}
A_Err
TransformVector4(
const VectorType4D *vectorP,
const A_Matrix4 *matrixP,
VectorType4D *resultP)
{
A_Err err = A_Err_NONE;
VectorType4D tmp;
Artie_TRANSFORM_VECTOR4(*vectorP, *matrixP, tmp);
*resultP = tmp;
return err;
}
Ray CreateRay(PointType4D P0, PointType4D P1)
{
Ray R;
R.P0 = P0;
R.P1 = P1;
return R;
}
Ray
TransformRay(
const Ray *rayP,
const A_Matrix4 *xformP)
{
Ray R;
TransformPoint4(&rayP->P0, xformP, &R.P0);
TransformPoint4(&rayP->P1, xformP, &R.P1);
return R;
}
| 27.072421
| 128
| 0.635971
|
richardlalancette
|
8dcdc5b342e6868a2206b99876e2e6270592aeba
| 6,799
|
cpp
|
C++
|
Code/Framework/AzCore/Tests/Math/IntersectPointTest.cpp
|
BreakerOfThings/o3de
|
f4c59f868c726470ec910623facd836047d059c3
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
Code/Framework/AzCore/Tests/Math/IntersectPointTest.cpp
|
BreakerOfThings/o3de
|
f4c59f868c726470ec910623facd836047d059c3
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
Code/Framework/AzCore/Tests/Math/IntersectPointTest.cpp
|
BreakerOfThings/o3de
|
f4c59f868c726470ec910623facd836047d059c3
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Math/IntersectPoint.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AZTestShared/Math/MathTestHelpers.h>
using namespace AZ;
namespace UnitTest::IntersectTest
{
// Tests a point inside sphere
TEST(MATH_IntersectPointSphere, TestPointInside)
{
Vector3 sphereCenter(1.f, 2.f, 3.f);
float sphereRadius = 5.f;
Vector3 testPoint(2.f, 3.f, 4.f);
EXPECT_TRUE(Intersect::PointSphere(sphereCenter, sphereRadius * sphereRadius, testPoint));
}
// Tests a point outside sphere
TEST(MATH_IntersectPointSphere, TestPointOutside)
{
Vector3 sphereCenter(1.f, 2.f, 3.f);
float sphereRadius = 5.f;
Vector3 testPoint(10.f, 10.f, 10.f);
EXPECT_FALSE(Intersect::PointSphere(sphereCenter, sphereRadius * sphereRadius, testPoint));
}
// Tests a point just inside the border of the sphere
TEST(MATH_IntersectPointSphere, TestPointInsideBorder)
{
Vector3 sphereCenter(1.f, 2.f, 3.f);
float sphereRadius = 5.f;
Vector3 testPoint(5.99f, 2.f, 3.f);
EXPECT_TRUE(Intersect::PointSphere(sphereCenter, sphereRadius * sphereRadius, testPoint));
}
// Tests a point just outside the border of the sphere
TEST(MATH_IntersectPointSphere, TestPointOutsideBorder)
{
Vector3 sphereCenter(1.f, 2.f, 3.f);
float sphereRadius = 5.f;
Vector3 testPoint(6.01f, 2.f, 3.f);
EXPECT_FALSE(Intersect::PointSphere(sphereCenter, sphereRadius * sphereRadius, testPoint));
}
// Tests a point inside cylinder
TEST(MATH_IntersectPointCylinder, TestPointInside)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(1.f, 5.f, 3.f);
EXPECT_TRUE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point outside cylinder
TEST(MATH_IntersectPointCylinder, TestPointOutside)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 1.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = 2.f;
Vector3 testPoint(9.f, 9.f, 9.f);
EXPECT_FALSE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point just inside border at the top of the cylinder
TEST(MATH_IntersectPointCylinder, TestPointInsideBorderTop)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(1.f, 6.99f, 3.f);
EXPECT_TRUE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point just outside border at the top of the cylinder
TEST(MATH_IntersectPointCylinder, TestPointOutsideBorderTop)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(1.f, 7.01f, 3.f);
EXPECT_FALSE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point just inside border at the bottom of the cylinder
TEST(MATH_IntersectPointCylinder, TestPointInsideBorderBottom)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(1.f, 2.01f, 3.f);
EXPECT_TRUE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point just outside border at the bottom of the cylinder
TEST(MATH_IntersectPointCylinder, TestPointOutsideBorderBottom)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(1.f, 1.99f, 3.f);
EXPECT_FALSE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point just inside border at the side of the cylinder
TEST(MATH_IntersectPointCylinder, TestPointInsideBorderSide)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(1.99f, 2.f, 3.f);
EXPECT_TRUE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
// Tests a point just outside border at the side of the cylinder
TEST(MATH_IntersectPointCylinder, TestPointOutsideBorderSide)
{
Vector3 cylinderBase(1.f, 2.f, 3.f);
Vector3 cylinderAxis(0.f, 5.f, 0.f);
float cylinderRadius = 1.f;
float cylinderLength = cylinderAxis.GetLength();
Vector3 testPoint(2.01f, 2.f, 3.f);
EXPECT_FALSE(Intersect::PointCylinder(cylinderBase, cylinderAxis, cylinderLength * cylinderLength, cylinderRadius * cylinderRadius, testPoint));
}
TEST(MATH_IntersectBarycentric, TestBarycentric)
{
EXPECT_THAT(AZ::Intersect::Barycentric(AZ::Vector3(1.0f,0.0f,0.0f), AZ::Vector3(0.0f,1,0.0f), AZ::Vector3(0.0f,0.0f,1), AZ::Vector3(1,0.0f,0.0f)),
IsClose(AZ::Vector3(1.0f,0.0f,0.0f)));
EXPECT_THAT(AZ::Intersect::Barycentric(AZ::Vector3(1.0f,0.0f,0.0f), AZ::Vector3(0.0f,1.0f,0.0f), AZ::Vector3(0.0f,0.0f,1.0f), AZ::Vector3(0.0f,1.0f,0.0f)),
IsClose(AZ::Vector3(0,1,0)));
EXPECT_THAT(AZ::Intersect::Barycentric(AZ::Vector3(1.0f,0.0f,0.0f), AZ::Vector3(0.0f,1.0f,0.0f), AZ::Vector3(0.0f,0.0f,1.0f), AZ::Vector3(0.0f,0.0f,1.0f)),
IsClose(AZ::Vector3(0,0,1)));
EXPECT_THAT(AZ::Intersect::Barycentric(AZ::Vector3(1.0f,0.0f,0.0f), AZ::Vector3(0.0f,1.0f,0.0f), AZ::Vector3(0.0f,0.0f,1.0f), AZ::Vector3(0.3f,0.3f,0.3f)),
IsClose(AZ::Vector3(0.333333f,0.333333f,0.333333f)));
}
}
| 40.712575
| 163
| 0.674805
|
BreakerOfThings
|
8dcdceb83fc9d8ea0df3482ac0a2b963dda53557
| 6,152
|
hpp
|
C++
|
src/field/fieldI.hpp
|
NSCCWX-AMD/HSF
|
dbf5987e364ce0ca3e92e72540a66a62353f4b3a
|
[
"Apache-2.0"
] | null | null | null |
src/field/fieldI.hpp
|
NSCCWX-AMD/HSF
|
dbf5987e364ce0ca3e92e72540a66a62353f4b3a
|
[
"Apache-2.0"
] | 1
|
2020-09-10T01:17:13.000Z
|
2020-09-10T01:17:13.000Z
|
src/field/fieldI.hpp
|
NSCCWX-AMD/HSF
|
dbf5987e364ce0ca3e92e72540a66a62353f4b3a
|
[
"Apache-2.0"
] | 2
|
2019-11-29T08:00:29.000Z
|
2019-11-29T08:26:13.000Z
|
/*
The MIT License
Copyright (c) 2019 Hanfeng GU <hanfenggu@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
* @File: fieldI.hpp
* @Author: Hanfeng GU
* @Email: hanfenggu@gmail.com
* @Date: 2019-09-18 16:04:01
* @Last Modified by: Hanfeng
* @Last Modified time: 2019-11-28 14:11:47
*/
/*
* @brief: Implementation of template functions in Field class
*/
template <typename T>
Field<T>::Field()
: setType_(NULL),
ndim_(0),
locSize_(0),
nbrSize_(0),
data_(NULL),
sendBufferPtr_(NULL),
sendRecvRequests_(NULL),
patchTabPtr_(NULL)
{
}
template <typename T>
Field<T>::Field(Word setType, label ndim, label n, T *dataPtr)
: setType_(setType),
ndim_(ndim),
locSize_(n),
nbrSize_(0),
data_(NULL),
sendBufferPtr_(NULL),
sendRecvRequests_(NULL),
patchTabPtr_(NULL)
{
data_ = new T[n * ndim];
memcpy(data_, dataPtr, n * ndim * sizeof(T));
}
template <typename T>
Field<T>::Field(Word setType,
label ndim,
label n,
T *dataPtr,
Table<Word, Table<Word, Patch *> *> &patchTab)
: setType_(setType),
ndim_(ndim),
locSize_(n),
nbrSize_(0),
data_(NULL),
sendBufferPtr_(NULL),
sendRecvRequests_(NULL),
patchTabPtr_(NULL)
{
label sizeAll = 0;
Table<Word, Table<Word, Patch *> *>::iterator it = patchTab.find(setType);
if (it != patchTab.end())
{
patchTabPtr_ = patchTab[setType];
Table<Word, Patch *> &patches = *patchTabPtr_;
Table<Word, Patch *>::iterator it2;
for (it2 = patches.begin(); it2 != patches.end(); ++it2)
{
Patch &patchI = *(it2->second);
sizeAll += patchI.getRecvSize();
}
nbrSize_ = sizeAll;
}
else
{
par_std_out_("No such type patch in region patchTab%s\n", setType.c_str());
}
sizeAll += locSize_;
data_ = new T[sizeAll * ndim_];
memcpy(data_, dataPtr, n * ndim * sizeof(T));
forAll(i, nbrSize_)
{
forAll(j, ndim)
{
data_[(n + i) * ndim + j] = 0;
}
}
}
template <typename T>
void Field<T>::initSend()
{
//- create
if (patchTabPtr_)
{
//- create
if (!sendBufferPtr_)
{
sendBufferPtr_ = new Table<Word, T *>;
}
Table<Word, Patch *> &patches = *patchTabPtr_;
Table<Word, T *> &sendBuffer = *sendBufferPtr_;
label nPatches = patches.size();
//- create memory for MPI_Request
if (!sendRecvRequests_)
{
sendRecvRequests_ = new MPI_Request[2 * nPatches];
}
Table<Word, Patch *>::iterator it = patches.begin();
//- if nbrdata not created
if (nbrSize_ <= 0)
{
nbrSize_ = 0;
for (it = patches.begin(); it != patches.end(); ++it)
{
Patch &patchI = *(it->second);
nbrSize_ += patchI.getRecvSize();
}
T *dataOld = data_;
data_ = new T[(locSize_ + nbrSize_) * ndim_];
memcpy(data_, dataOld, locSize_ * ndim_ * sizeof(T));
DELETE_POINTER(dataOld);
}
T *recvArrayPtr = &(data_[locSize_ * ndim_]);
it = patches.begin();
for (label i = 0; i < nPatches, it != patches.end(); ++i, ++it)
{
Patch &patchI = *(it->second);
label sendSize = patchI.getSendSize();
label recvSize = patchI.getRecvSize();
Word patchName = it->first;
//- here memory created
if (!sendBuffer[patchName])
{
sendBuffer[patchName] = new T[sendSize * ndim_];
}
T *patchI_sendBuffer = sendBuffer[patchName];
T *patchI_recvBuffer = recvArrayPtr;
label *patchI_addressing = patchI.getAddressing();
for (label j = 0; j < sendSize; ++j)
{
for (label k = 0; k < ndim_; ++k)
{
patchI_sendBuffer[j * ndim_ + k] =
data_[patchI_addressing[j] * ndim_ + k];
}
}
MPI_Isend(patchI_sendBuffer,
sendSize * ndim_ * sizeof(T),
MPI_BYTE,
patchI.getNbrProcID(),
1,
MPI_COMM_WORLD,
&sendRecvRequests_[i]);
MPI_Irecv(patchI_recvBuffer,
recvSize * ndim_ * sizeof(T),
MPI_BYTE,
patchI.getNbrProcID(),
1,
MPI_COMM_WORLD,
&sendRecvRequests_[i + nPatches]);
recvArrayPtr += recvSize * ndim_;
}
}
}
template <typename T>
label Field<T>::checkSendStatus()
{
if (sendRecvRequests_)
{
Table<Word, Patch *> &patches = *patchTabPtr_;
label nPatches = patches.size();
MPI_Waitall(2 * nPatches, &sendRecvRequests_[0], MPI_STATUSES_IGNORE);
DELETE_POINTER(sendRecvRequests_);
}
return 1;
}
template <typename T>
void Field<T>::freeSendRecvBuffer()
{
//- free sendBufferPtr_
if (sendBufferPtr_)
{
Table<Word, T *> &sendBuffer = *sendBufferPtr_;
typename Table<Word, T *>::iterator it = sendBuffer.begin();
for (it = sendBuffer.begin(); it != sendBuffer.end(); ++it)
{
DELETE_POINTER(it->second);
}
DELETE_OBJECT_POINTER(sendBufferPtr_);
}
}
template <typename T>
Field<T>::~Field()
{
DELETE_POINTER(data_);
freeSendRecvBuffer();
}
| 25.957806
| 79
| 0.611996
|
NSCCWX-AMD
|
8dd2f535b0f0b2fa61ec96dbe8390931fb18ac3d
| 6,827
|
hpp
|
C++
|
eagleeye/framework/pipeline/SignalFactory.hpp
|
MirrorYu/eagleeye
|
c251e7b3bc919673b41360212c38d5fda85bbe2f
|
[
"Apache-2.0"
] | 12
|
2020-09-21T02:24:11.000Z
|
2022-03-10T03:02:03.000Z
|
eagleeye/framework/pipeline/SignalFactory.hpp
|
MirrorYu/eagleeye
|
c251e7b3bc919673b41360212c38d5fda85bbe2f
|
[
"Apache-2.0"
] | 1
|
2020-11-30T08:22:50.000Z
|
2020-11-30T08:22:50.000Z
|
eagleeye/framework/pipeline/SignalFactory.hpp
|
MirrorYu/eagleeye
|
c251e7b3bc919673b41360212c38d5fda85bbe2f
|
[
"Apache-2.0"
] | 3
|
2020-03-16T12:10:55.000Z
|
2021-07-20T09:58:15.000Z
|
namespace eagleeye
{
/* Image Signal */
template<class T>
ImageSignal<T>::ImageSignal(Matrix<T> data,char* name,char* info)
:BaseImageSignal(TypeTrait<T>::type,TypeTrait<T>::size,info),
img(data)
{
this->m_meta.name = name;
this->m_meta.info = info;
this->m_meta.fps = 0.0;
this->m_meta.nb_frames = 0;
this->m_meta.frame = 0;
this->m_meta.is_end_frame = false;
this->m_meta.is_start_frame = false;
this->m_meta.rotation = 0;
this->m_meta.rows = 0;
this->m_meta.cols = 0;
this->m_meta.needed_rows = 0;
this->m_meta.needed_cols = 0;
this->m_meta.allocate_mode = 0;
this->m_meta.timestamp = 0;
this->m_sig_category = SIGNAL_CATEGORY_IMAGE;
}
template<class T>
void ImageSignal<T>::copyInfo(AnySignal* sig){
if(sig == NULL){
return;
}
//call the base class
BaseImageSignal::copyInfo(sig);
if(SIGNAL_CATEGORY_IMAGE == (sig->getSignalCategory() & SIGNAL_CATEGORY_IMAGE)){
this->m_meta = sig->meta();
}
}
template<class T>
void ImageSignal<T>::copy(AnySignal* sig){
if((SIGNAL_CATEGORY_IMAGE != (sig->getSignalCategory() & SIGNAL_CATEGORY_IMAGE)) ||
(this->getValueType() != sig->getValueType())){
return;
}
ImageSignal<T>* from_sig = (ImageSignal<T>*)(sig);
MetaData from_data_meta;
Matrix<T> from_data = from_sig->getData(from_data_meta);
this->setData(from_data, from_data_meta);
}
template<class T>
void ImageSignal<T>::printUnit()
{
Superclass::printUnit();
EAGLEEYE_LOGD("image name %s \n",this->m_meta.name.c_str());
EAGLEEYE_LOGD("image type %d channels %d rows %d cols %d \n",pixel_type,channels,img.rows(),img.cols());
}
template<class T>
void ImageSignal<T>::makeempty(bool auto_empty)
{
if(auto_empty){
if(this->m_release_count % this->getOutDegree() != 0){
this->m_release_count += 1;
return;
}
}
img = Matrix<T>();
this->m_meta.name = "";
this->m_meta.info = "";
this->m_meta.fps = 0.0;
this->m_meta.nb_frames = 0;
this->m_meta.frame = 0;
this->m_meta.is_end_frame = false;
this->m_meta.is_start_frame = false;
this->m_meta.rotation = 0;
this->m_meta.rows = 0;
this->m_meta.cols = 0;
this->m_meta.timestamp = 0;
if(auto_empty){
// reset count
this->m_release_count = 1;
}
//force time update
modified();
}
template<class T>
bool ImageSignal<T>::isempty(){
if(this->getSignalCategory() == SIGNAL_CATEGORY_IMAGE){
if(img.rows() == 0 || img.cols() == 0){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
template<class T>
typename ImageSignal<T>::DataType ImageSignal<T>::getData(){
// refresh data
if(this->m_link_node != NULL){
this->m_link_node->refresh();
}
if(this->getSignalCategory() == SIGNAL_CATEGORY_IMAGE){
// SIGNAL_CATEGORY_IMAGE
return img;
}
else{
// SIGNAL_CATEGORY_IMAGE_QUEUE
std::unique_lock<std::mutex> locker(this->m_mu);
while(this->m_queue.size() == 0){
this->m_cond.wait(locker);
if(this->m_queue.size() > 0 || this->m_signal_exit){
break;
}
}
if(this->m_signal_exit){
return Matrix<T>();
}
Matrix<T> data = this->m_queue.front();
this->m_queue.pop();
this->m_meta_queue.pop();
locker.unlock();
return data;
}
}
template<class T>
void ImageSignal<T>::setData(ImageSignal<T>::DataType data){
if(this->getSignalCategory() == SIGNAL_CATEGORY_IMAGE){
// SIGNAL_CATEGORY_IMAGE
this->img = data;
this->m_meta.rows = this->img.rows();
this->m_meta.cols = this->img.cols();
}
else{
// SIGNAL_CATEGORY_IMAGE_QUEUE
std::unique_lock<std::mutex> locker(this->m_mu);
this->m_queue.push(data);
MetaData mm;
mm.rows = data.rows();
mm.cols = data.cols();
this->m_meta_queue.push(mm);
locker.unlock();
// notify
this->m_cond.notify_all();
}
modified();
}
template<class T>
typename ImageSignal<T>::DataType ImageSignal<T>::getData(MetaData& mm){
// refresh data
if(this->m_link_node != NULL){
this->m_link_node->refresh();
}
if(this->getSignalCategory() == SIGNAL_CATEGORY_IMAGE){
// SIGNAL_CATEGORY_IMAGE
mm = this->m_meta;
return img;
}
else{
// SIGNAL_CATEGORY_IMAGE_QUEUE
std::unique_lock<std::mutex> locker(this->m_mu);
while(this->m_queue.size() == 0){
this->m_cond.wait(locker);
if(this->m_queue.size() > 0 || this->m_signal_exit){
break;
}
}
if(this->m_signal_exit){
return Matrix<T>();
}
Matrix<T> data = this->m_queue.front();
mm = this->m_meta_queue.front();
this->m_queue.pop();
this->m_meta_queue.pop();
locker.unlock();
return data;
}
}
template<class T>
void ImageSignal<T>::setData(ImageSignal<T>::DataType data, MetaData mm){
if(this->getSignalCategory() == SIGNAL_CATEGORY_IMAGE){
// SIGNAL_CATEGORY_IMAGE
this->img = data;
// ignore needed_rows, needed_cols and allocate_mode
int needed_rows = this->m_meta.needed_rows;
int needed_cols = this->m_meta.needed_cols;
int allocate_mode = this->m_meta.allocate_mode;
this->m_meta = mm;
this->m_meta.needed_rows = needed_rows;
this->m_meta.needed_cols = needed_cols;
this->m_meta.allocate_mode = allocate_mode;
}
else{
// SIGNAL_CATEGORY_IMAGE_QUEUE
std::unique_lock<std::mutex> locker(this->m_mu);
this->m_queue.push(data);
this->m_meta_queue.push(mm);
locker.unlock();
// notify
// this->m_cond.notify_one();
this->m_cond.notify_all();
}
modified();
}
template<class T>
void ImageSignal<T>::setData(void* data, MetaData meta){
// const int* data_size, const int data_dims, int rotation
if(this->getSignalType() == EAGLEEYE_SIGNAL_TEXTURE){
unsigned int texture_id = *((unsigned int*)(data));
EAGLEEYE_LOGD("TEXTURE ID %d", texture_id);
this->img = Matrix<T>(texture_id);
this->m_meta = meta;
return;
}
// MetaData meta_data = this->meta();
Matrix<T> signal_content;
if(meta.allocate_mode == 1){
// InPlace Mode
signal_content = Matrix<T>(meta.rows, meta.cols, data, false);
}
else if(meta.allocate_mode == 2){
// Largest Mode
signal_content = Matrix<T>(meta.rows, meta.cols, this->getNeededMem(), false);
memcpy(signal_content.dataptr(), data, sizeof(T)*meta.rows*meta.cols);
}
else{
// Copy Mode
signal_content = Matrix<T>(meta.rows, meta.cols, data, true);
}
this->setData(signal_content, meta);
}
template<class T>
void ImageSignal<T>::getSignalContent(void*& data, int* data_size, int& data_dims, int& data_type){
this->m_tmp = this->getData();
data = (void*)this->m_tmp.dataptr();
data_dims = 3;
data_size[0] = this->m_tmp.rows();
data_size[1] = this->m_tmp.cols();
data_size[2] = TypeTrait<T>::size;
data_type = TypeTrait<T>::type;
}
template<class T>
void ImageSignal<T>::setMeta(MetaData meta){
if(meta.allocate_mode == 3 && meta.needed_rows > 0 && meta.needed_cols > 0){
// allocate allowed largest space
this->setNeededMem(sizeof(T)*meta.needed_rows*meta.needed_cols);
}
this->m_meta = meta;
}
}
| 24.038732
| 105
| 0.676139
|
MirrorYu
|
8dd36af4771b112910bf0b04fadce500a90ac765
| 1,519
|
cpp
|
C++
|
plugins/eclblas/daxpy.cpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 286
|
2015-01-03T12:45:17.000Z
|
2022-03-25T18:12:57.000Z
|
plugins/eclblas/daxpy.cpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 9,034
|
2015-01-02T08:49:19.000Z
|
2022-03-31T20:34:44.000Z
|
plugins/eclblas/daxpy.cpp
|
cloLN/HPCC-Platform
|
42ffb763a1cdcf611d3900831973d0a68e722bbe
|
[
"Apache-2.0"
] | 208
|
2015-01-02T03:27:28.000Z
|
2022-02-11T05:54:52.000Z
|
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2016 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
// Vector add, alpha X + Y
#include "eclblas.hpp"
namespace eclblas {
ECLBLAS_CALL void daxpy(bool & __isAllResult, size32_t & __lenResult,
void * & __result, uint32_t n, double alpha,
bool isAllX, size32_t lenX, const void * x, uint32_t incx,
bool isAllY, size32_t lenY, const void* y, uint32_t incy,
uint32_t x_skipped, uint32_t y_skipped) {
__isAllResult = false;
__lenResult = lenY;
const double* X = ((const double*)x) + x_skipped;
double *result = (double*) rtlMalloc(__lenResult);
memcpy(result, y,lenY);
double* Y = result + y_skipped;
cblas_daxpy(n, alpha, X, incx, Y, incy);
__result = (void*) result;
}
}
| 38.948718
| 82
| 0.597762
|
miguelvazq
|
8dd4dcd5ef4d83bb13c99645e91b6891f9c1b949
| 5,854
|
hh
|
C++
|
data.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | 1
|
2021-05-06T04:41:37.000Z
|
2021-05-06T04:41:37.000Z
|
data.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | null | null | null |
data.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | 1
|
2021-05-06T04:41:39.000Z
|
2021-05-06T04:41:39.000Z
|
/* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#ifndef DATA_HH
#define DATA_HH
#include <vector>
#include <unordered_map>
#include <QTimer>
#include <chrono>
#include <QMutex>
#include <iostream>
#include <string>
#include <memory>
#include <QDebug>
#include <cstdint>
#include <cassert>
#include "nogood_representation.hh"
#include "cpprofiler/universal.hh"
class NameMap;
namespace cpprofiler {
class Message;
}
class DbEntry {
public:
DbEntry(NodeUID uid, NodeUID parent_uid, int _alt, int _kids,
std::string _label, int tid, int _status, int64_t _time_stamp,
int64_t _node_time) :
nodeUID(uid), parentUID(parent_uid), alt(_alt), numberOfKids(_kids), label(_label), thread_id(tid), time_stamp(_time_stamp), node_time(_node_time), status(_status)
{
/// Map message status to profiler status;
/// alternatively could make treebuilder use message status
// switch (_status) {
// case 0:
// break;
// }
// status
}
DbEntry(NodeUID uid, NodeUID parent_uid, int alt, int kids, int status)
: nodeUID(uid),
parentUID(parent_uid),
alt(alt),
numberOfKids(kids),
status(status) {}
DbEntry() = default;
friend std::ostream& operator<<(std::ostream& s, const DbEntry& e);
NodeUID nodeUID;
NodeUID parentUID;
int32_t gid {-1}; // gist id, set to -1 so we don't forget to assign the real value
int32_t alt; // which child by order
int32_t numberOfKids;
std::string label;
int32_t thread_id{-1};
int32_t depth {-1};
uint64_t time_stamp{0};
uint64_t node_time{0};
char status;
};
class NodeTimer;
class Data : public QObject {
Q_OBJECT
std::unique_ptr<NodeTimer> search_timer;
std::vector<DbEntry*> nodes_arr;
// Whether received DONE_SENDING message
bool _isDone{false};
/// How many nodes received within each NODE_RATE_STEP interval
std::vector<float> node_rate;
int last_interval_nc;
/// Map solver Id to no-good string (rid = 0 always for chuffed)
Uid2Nogood uid2nogood;
NameMap* nameMap;
/// node rate intervals
std::vector<int> nr_intervals;
std::unordered_map<NodeUID, int> uid2obj;
public:
/// Mapping from solver Id to array Id (nodes_arr)
/// can't use vector because sid is too big with threads
std::unordered_map<NodeUID, int> uid2aid;
/// Maps gist Id to dbEntry (possibly in the other Data instance);
/// i.e. needed for a merged tree to show labels etc.
/// TODO(maixm): this should probably be a vector?
std::unordered_map<int, DbEntry*> gid2entry;
std::unordered_map<NodeUID, std::shared_ptr<std::string>> uid2info;
/// synchronise access to data entries
mutable QMutex dataMutex {QMutex::Recursive};
private:
/// Populate nodes_arr with the data coming from
void pushInstance(DbEntry* entry);
public:
Data();
~Data();
void handleNodeCallback(const cpprofiler::Message& node);
/// TODO(maxim): Do I want a reference here?
/// return label by gid (Gist ID)
std::string getLabel(int gid);
/// return solver id by gid (Gist ID)
NodeUID gid2uid(int gid) const;
void connectNodeToEntry(int gid, DbEntry* const entry);
/// return total number of nodes
int size() const { return nodes_arr.size(); }
/// ********* GETTERS **********
bool isDone(void) const { return _isDone; }
const std::vector<DbEntry*>& getEntries() const { return nodes_arr; }
inline const Uid2Nogood& getNogoods(void) { return uid2nogood; }
uint64_t getTotalTime();
int32_t getGidByUID(NodeUID uid) {
return nodes_arr[uid2aid[uid]]->gid;
}
const int* getObjective(NodeUID uid) const {
auto it = uid2obj.find(uid);
if (it != uid2obj.end()) {
return &it->second;
} else {
return nullptr;
}
}
/// NOTE(maxim): this only works for a merged tree now?
DbEntry* getEntry(int gid) const;
const NameMap* getNameMap() const { return nameMap; }
void setNameMap(NameMap* names);
const std::vector<int>& node_rate_intervals() const { return nr_intervals; }
/// ****************************
/// Starts node timer
void initReceiving();
public Q_SLOTS:
void setDoneReceiving();
#ifdef MAXIM_DEBUG
void setLabel(int gid, const std::string& str);
const std::string getDebugInfo() const;
#endif
};
inline
void Data::connectNodeToEntry(int gid, DbEntry* const entry) {
gid2entry[gid] = entry;
}
inline
DbEntry* Data::getEntry(int gid) const {
auto it = gid2entry.find(gid);
if (it != gid2entry.end()) {
return it->second;
} else {
return nullptr;
}
}
#endif // DATA_HH
| 26.609091
| 171
| 0.66399
|
cp-profiler
|
8dd93358887ec518a9ba3cf295d91528162fcbea
| 7,217
|
cpp
|
C++
|
base/source/ESBReadWriteLock.cpp
|
duderino/everscale
|
38388289dcce869852680a167f3dcb7e090d851c
|
[
"Apache-2.0"
] | null | null | null |
base/source/ESBReadWriteLock.cpp
|
duderino/everscale
|
38388289dcce869852680a167f3dcb7e090d851c
|
[
"Apache-2.0"
] | null | null | null |
base/source/ESBReadWriteLock.cpp
|
duderino/everscale
|
38388289dcce869852680a167f3dcb7e090d851c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ESB_READ_WRITE_LOCK_H
#include <ESBReadWriteLock.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
namespace ESB {
ReadWriteLock::ReadWriteLock() : _magic(0) {
#ifdef HAVE_PTHREAD_RWLOCK_INIT
if (0 == pthread_rwlock_init(&_lock, 0)) {
_magic = ESB_MAGIC;
}
#elif defined HAVE_PTHREAD_MUTEX_INIT && defined HAVE_PTHREAD_COND_INIT && defined HAVE_PTHREAD_MUTEX_DESTROY && \
defined HAVE_PTHREAD_COND_DESTROY
if (0 != pthread_mutex_init(&_lock._mutex, 0)) {
return;
}
if (0 != pthread_cond_init(&_lock._readSignal, 0)) {
pthread_mutex_destroy(&_lock._mutex);
return;
}
if (0 != pthread_cond_init(&_lock._writeSignal, 0)) {
pthread_mutex_destroy(&_lock._mutex);
pthread_cond_destroy(&_lock._readSignal);
return;
}
_lock._readersActive = 0;
_lock._readersWaiting = 0;
_lock._writersActive = 0;
_lock._writersWaiting = 0;
_magic = ESB_MAGIC;
#else
#error "Platform has no rw lock initializer"
#endif
}
ReadWriteLock::~ReadWriteLock() {
if (ESB_MAGIC != _magic) {
return;
}
#ifdef HAVE_PTHREAD_RWLOCK_DESTROY
pthread_rwlock_destroy(&_lock);
#elif defined HAVE_PTHREAD_MUTEX_DESTROY && defined HAVE_PTHREAD_COND_DESTROY
pthread_mutex_destroy(&_lock._mutex);
pthread_cond_destroy(&_lock._readSignal);
pthread_cond_destroy(&_lock._writeSignal);
#else
#error "Platform has no rw lock destructor."
#endif
}
Error ReadWriteLock::writeAcquire() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_WRLOCK
return ConvertError(pthread_rwlock_wrlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_COND_WAIT && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
while (0 < _lock._writersActive || 0 < _lock._readersActive) {
++_lock._writersWaiting;
error = ConvertError(pthread_cond_wait(&_lock._writeSignal, &_lock._mutex));
--_lock._writersWaiting;
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
}
assert(0 == _lock._writersActive && 0 == _lock._readersActive);
_lock._writersActive = 1;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock write lock function."
#endif
}
Error ReadWriteLock::readAcquire() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_RDLOCK
return ConvertError(pthread_rwlock_rdlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_COND_WAIT && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
while (0 < _lock._writersActive || 0 < _lock._writersWaiting) {
++_lock._readersWaiting;
error = ConvertError(pthread_cond_wait(&_lock._readSignal, &_lock._mutex));
--_lock._readersWaiting;
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
}
++_lock._readersActive;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock read lock function."
#endif
}
Error ReadWriteLock::writeAttempt() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_TRYWRLOCK
int error = pthread_rwlock_trywrlock(&_lock);
switch (error) {
case 0:
return ESB_SUCCESS;
case EBUSY:
return ESB_AGAIN;
default:
return ConvertError(error);
}
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
if (0 < _lock._writersActive || 0 < _lock._readersActive) {
error = ConvertError(pthread_mutex_unlock(&_lock._mutex));
return ESB_SUCCESS == error ? ESB_AGAIN : error;
}
_lock._writersActive = 1;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock try write lock function."
#endif
}
Error ReadWriteLock::readAttempt() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_TRYRDLOCK
int error = pthread_rwlock_tryrdlock(&_lock);
switch (error) {
case 0:
return ESB_SUCCESS;
case EBUSY:
return ESB_AGAIN;
default:
return ConvertError(error);
}
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
if (0 < _lock._writersActive) {
error = ConvertError(pthread_mutex_unlock(&_lock._mutex));
return ESB_SUCCESS == error ? ESB_AGAIN : error;
}
++_lock._readersActive;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock try read lock function."
#endif
}
Error ReadWriteLock::writeRelease() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_UNLOCK
return ConvertError(pthread_rwlock_unlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK && defined HAVE_PTHREAD_COND_SIGNAL && \
defined HAVE_PTHREAD_COND_BROADCAST
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
assert(1 == _lock._writersActive);
if (1 != _lock._writersActive) {
pthread_mutex_unlock(&_lock._mutex);
return ESB_INVALID_STATE;
}
_lock._writersActive = 0;
error = ESB_SUCCESS;
if (0 < _lock._writersWaiting) {
error = ConvertError(pthread_cond_signal(&_lock._writeSignal));
} else if (0 < _lock._readersWaiting) {
error = ConvertError(pthread_cond_broadcast(&_lock._readSignal));
}
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock write unlock function."
#endif
}
Error ReadWriteLock::readRelease() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_UNLOCK
return ConvertError(pthread_rwlock_unlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK && defined HAVE_PTHREAD_COND_SIGNAL && \
defined HAVE_PTHREAD_COND_BROADCAST
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
assert(0 == _lock._writersActive);
assert(0 < _lock._readersActive);
if (0 < _lock._writersActive || 1 > _lock._readersActive) {
pthread_mutex_unlock(&_lock._mutex);
return ESB_INVALID_STATE;
}
--_lock._readersActive;
if (0 == _lock._readersActive && 0 < _lock._writersWaiting) {
error = ConvertError(pthread_cond_signal(&_lock._writeSignal));
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
}
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock read unlock function."
#endif
}
} // namespace ESB
| 21.803625
| 115
| 0.720382
|
duderino
|
8dd9ee89d9d3745ee949f9b6ad9642311151a589
| 1,295
|
hpp
|
C++
|
src/servercommon/struct/global/autoparam.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 3
|
2021-12-16T13:57:28.000Z
|
2022-03-26T07:50:08.000Z
|
src/servercommon/struct/global/autoparam.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | null | null | null |
src/servercommon/struct/global/autoparam.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 1
|
2022-03-26T07:50:11.000Z
|
2022-03-26T07:50:11.000Z
|
#pragma once
#include "common/tlvprotocol.h"
class AutoParamBase
{
public:
virtual ~AutoParamBase() = default;
virtual int Size() const = 0;
virtual void Reset() = 0;
virtual bool Serialize(TLVSerializer &serializer) = 0;
virtual bool Unserialize(TLVUnserializer &unserializer) = 0;
};
template<typename StructParam>
class AutoParamTemplate : public AutoParamBase
{
public:
int Size() const override { return sizeof(m_data); }
void Reset() override { m_data.Reset(); }
bool Serialize(TLVSerializer &serializer) override
{
TLVSerializer data;
data.Reset(static_cast<void*>(&m_data), sizeof(m_data));
data.MoveCurPos(sizeof(m_data));
return serializer.Push(data);
}
bool Unserialize(TLVUnserializer &unserializer) override
{
m_data.Reset();
if (unserializer.IsAllPoped()) return true;
TLVUnserializer data;
if (!unserializer.Pop(&data))
{
printf("UNSERIALIZE_USER_DATA %s Pop fail!\n", __FUNCTION__); return false;
}
if (sizeof(m_data) >= data.Size())
{
memcpy(&m_data, data.Ptr(), data.Size());
}
else
{
printf("UNSERIALIZE_USER_DATA %s size check fail!\n", __FUNCTION__); return false;
}
return true;
}
StructParam & Param() { return m_data; }
const StructParam & Param() const { return m_data; }
private:
StructParam m_data;
};
| 23.125
| 85
| 0.711969
|
mage-game
|
8ddc6940da14f4a282e8905395a41cad2c65b69a
| 7,484
|
cpp
|
C++
|
CPP_Files/Collider.cpp
|
Yaters/Knightmare
|
4440fafb910054cc70bc2d01994435011226061f
|
[
"MIT"
] | null | null | null |
CPP_Files/Collider.cpp
|
Yaters/Knightmare
|
4440fafb910054cc70bc2d01994435011226061f
|
[
"MIT"
] | null | null | null |
CPP_Files/Collider.cpp
|
Yaters/Knightmare
|
4440fafb910054cc70bc2d01994435011226061f
|
[
"MIT"
] | null | null | null |
#include "Collider.h"
/*Well Fudge. I've learned my lesson. Don't trust online 'optimizations' without checking.
* Square Root apparently isn't as 'costly' as some articles made it out to be. I'm not going back to change
* all my work using LSquare and radSquare instead of gl::length, but that's annoying. Real annoying
*/
//These were made for cursor cols (though PointCircle will probably never be used
GLboolean Collider::checkPointRecCol(glm::vec2 point, GameObject rect) {
GLboolean colx = (point.x >= rect.pos.x && point.x <= rect.pos.x + rect.size.x); //Check that x is between x values
GLboolean coly = (point.y >= rect.pos.y && point.y <= rect.pos.y + rect.size.y);
return colx && coly;
}
GLboolean Collider::checkPointCircleCol(glm::vec2 point, GameObject circle) {
glm::vec2 Diff = (circle.pos + 0.5f * circle.size) - point;
return glm::length(Diff) <= circle.size.y * 0.5f; //Basically is point within rad of center
}
//This isn't adjusted to factor in dir. THIS IS BROKEN DON'T USE IT UNLESS YOU'RE WILLING TO FIX IT
GLboolean Collider::checkRectRectCol(GameObject rect1, GameObject rect2) {
GLboolean colx = (rect1.pos.x + rect1.size.x >= rect2.pos.x && rect2.pos.x + rect2.size.x >= rect1.pos.x);
GLboolean coly = (rect1.pos.y + rect1.size.y >= rect2.pos.y && rect2.pos.y + rect2.size.y >= rect1.pos.y);
return colx && coly;
}
GLboolean Collider::checkCircleRectCol(GameObject circle, GameObject rect) {
//Basically ctrlc ctrlv from SpriteRender.cpp
glm::mat2 rotate = glm::mat2(rect.dir.y, rect.dir.x,
-rect.dir.x, rect.dir.y);
glm::vec2 circleCenter = circle.pos + 0.5f * circle.size;
glm::vec2 diff = circleCenter - (rect.pos + 0.5f * rect.size); //Vec2 going from rect center to circle center
diff = rotate * diff; //rotate it to follow rectangle?
circleCenter = diff; //Set circleCenter to rotate later
glm::vec2 closest = glm::clamp(diff, -0.5f * rect.size, 0.5f * rect.size); //Clamps Diff to be within rectangle- closest = closest point to circle
diff = closest - circleCenter;
return (LSquare(diff)) <= (float)(0.25 * circle.size.y * circle.size.y); //If point->circle center > r, it's colliding
}
//Ok we're assuming triangle texture on quad, with center and top corners as the points.
GLboolean Collider::checkCircleTriangleCol(GameObject circle, GameObject tri) {
//This is the inverse of normal rotation matrix, rotates clockwise instead of counterclockwise (reason is because the dir.y is now opposite dir.y wanted
glm::mat2 rotate = glm::mat2(tri.dir.y, -tri.dir.x,
tri.dir.x, tri.dir.y);
//LSquare returns length squared: -radSquare means instead of checking for <radSquare, we can check <0
//List of stuff we'll need
//I tried -y on CircCenter to adjust to normal graph, but it broke it. This works
glm::vec2 CircCenter = circle.pos + 0.5f * circle.size - (tri.pos + 0.5f * tri.size);
GLfloat radSquare = circle.size.y * circle.size.y * 0.25f;
//Points (P0 is 0,0)
glm::vec2 P1 = rotate * glm::vec2(tri.size.x / 2, tri.size.y / 2);
glm::vec2 P2 = rotate * glm::vec2(-tri.size.x / 2, tri.size.y / 2);
// Points to circle Center from vertices (C0 was replaced by CircCenter)
glm::vec2 C1 = CircCenter - P1;
glm::vec2 C2 = CircCenter - P2;
//length of previous vector squared
GLfloat C0Squared = LSquare(CircCenter) - radSquare;
GLfloat C1Squared = LSquare(C1) - radSquare;
GLfloat C2Squared = LSquare(C2) - radSquare;
//Edge vectors (e0 was = P1 and e2 was = -P2, both were replaced)
glm::vec2 e1 = P2 - P1;
/* Ok here's the deal. Right now I'm using a quad with a triangle texture to draw Triangles.
"wtf man? Opengl is like made for triangles!" i know, i know. But making a triangle draw
means making a new Draw in SpriteRender, two new shaders, and a much more annoying system for
finding vertices in here. Then I need that TWICE to get textured triangles. So sorry */
//CASE #1: CORNERS IN CIRCLE
if (C0Squared <= 0 || C1Squared <= 0 || C2Squared <= 0) return GL_TRUE;
//CASE #2: CIRCLE INSIDE TRIANGLE
//I might be able to optimize this more, but I won't for readability. Normal = (y2-y1, x1-x2)
glm::vec2 Norm0(P1.y, -P1.x);
glm::vec2 Norm1(P2.y - P1.y, P1.x - P2.x);
glm::vec2 Norm2(-P2.y, P2.x);
//If in triangle side of edge, dot is negative(I did counterclock order for norms)
if (glm::dot(Norm0, CircCenter) < 0 && glm::dot(Norm1, C1) < 0 && glm::dot(Norm2, C2) < 0) return GL_TRUE;
// CASE #3: EDGE IN CIRCLE
//k is just a temp value to store dot product. technically the length along triangle to where circle is nearest to edge
GLfloat k = glm::dot(CircCenter, P1);
//If dot product is positive(not past p1)
if (k > 0) {
GLfloat sideLenSquare = LSquare(P1);
k *= k / sideLenSquare;
//Checks if it's past P0 (bigger than edge length)
if (k < sideLenSquare) {
if (C0Squared <= k) return GL_TRUE;
}
}
k = glm::dot(C1, e1);
if (k > 0) {
GLfloat sideLenSquare = LSquare(e1);
k *= k / sideLenSquare;
if (k < sideLenSquare) {
if (C1Squared <= k) return GL_TRUE;
}
}
k = glm::dot(C2, -P2);
if (k > 0) {
GLfloat sideLenSquare = LSquare(-P2);
k *= k / sideLenSquare;
if (k < sideLenSquare) {
if (C2Squared <= k) return GL_TRUE;
}
}
return GL_FALSE;
}
//For Circles I default to using y size as radius for things like background
GLboolean Collider::checkCircleCircleCol(GameObject circle1, GameObject circle2) {
//Find vector w/ difference between centers
glm::vec2 temp = (circle1.pos + circle1.size * 0.5f) - (circle2.pos + circle2.size * 0.5f);
//If length of distance <= length of radii combined, it's a collision
return glm::length(temp) <= (circle1.size.y * 0.5f + circle2.size.y * 0.5f);
}
//Contains a given circle within the circular GameObject
void Collider::CircleContainCircle(GameObject outsideCircle, GameObject& insideCircle) {
//Vector between centers
glm::vec2 diff = (insideCircle.pos + insideCircle.size * 0.5f) - (outsideCircle.pos + outsideCircle.size * 0.5f);
GLfloat len = glm::length(diff);
//If(centers are closer than difference in radii) <- difference because one is inside
if (len > (0.5f * (outsideCircle.size.y - insideCircle.size.y))) {
//insideCircle.pos = diff * (0.5f * (outsideCircle.size.y - insideCircle.size.y)) / len; //LOL this is fun but not what I'm going for: Try it out
insideCircle.pos = diff * 0.5f * (outsideCircle.size.y - insideCircle.size.y) / len; // First move circle center to inside
insideCircle.pos -= 0.5f * insideCircle.size; // then move pos to top left of circle sprite
insideCircle.pos += outsideCircle.size * 0.5f; //then move pos to be relative to screen/big circle
}
}
//Exclued a given circle from the circular GameObject
void Collider::CircleExcludeCircle(GameObject circleStay, GameObject& circleKeepOut) {
//Vector between centers
glm::vec2 diff = (circleKeepOut.pos + circleKeepOut.size * 0.5f) - (circleStay.pos + circleStay.size * 0.5f);
GLfloat len = glm::length(diff);
if (len < (0.5f * (circleStay.size.y + circleKeepOut.size.y))) { //If distance < combined radii
diff /= len; //Normalize diff
len = 0.5f * (circleStay.size.y + circleKeepOut.size.y); //Set the distance between equal to what we want
diff *= len; //Multiply diff(gives direction) by desired length
circleKeepOut.pos = diff + (circleStay.pos + circleStay.size * 0.5f); // Set outside circle to be Circle Stay center + new diff vector
circleKeepOut.pos -= circleKeepOut.size * 0.5f; // Then adjust so pos = top left of circle
}
}
| 44.284024
| 153
| 0.700828
|
Yaters
|
8ddccfeff11d9917a006a18ae1a98158dd46e11d
| 2,336
|
inl
|
C++
|
Kalydo/KRFReadLib/Include/kifstream.inl
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | 1
|
2022-02-14T15:46:44.000Z
|
2022-02-14T15:46:44.000Z
|
Kalydo/KRFReadLib/Include/kifstream.inl
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | null | null | null |
Kalydo/KRFReadLib/Include/kifstream.inl
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | 2
|
2022-01-10T22:17:06.000Z
|
2022-01-17T09:34:08.000Z
|
#include "KRFReadLib.h"
#include "kseek.h"
inline kifstream::kifstream()
: m_File(NULL)
, m_State(std::ios_base::goodbit)
{
}
inline kifstream::kifstream(const char* filename, std::ios_base::openmode mode)
: m_File(kopen(filename, NULL))
, m_State(std::ios_base::goodbit)
{
}
inline kifstream::~kifstream()
{
close();
}
inline kifstream& kifstream::read(char* s, long long n)
{
if (!m_File)
return *this;
// n is always small enough to cast
m_Count = kread(s, 1, (size_t)n, m_File);
setState(m_Count == n);
return *this;
}
inline long long kifstream::gcount() const
{
return m_Count;
}
inline bool kifstream::is_open() const
{
return m_File != NULL;
}
inline bool kifstream::open(const char* filename, std::ios_base::openmode mode)
{
m_File = kopen(filename, NULL);
m_State = std::ios_base::goodbit;
}
inline void kifstream::close()
{
if (m_File != NULL)
{
kclose(m_File);
m_File = NULL;
}
}
inline void kifstream::seekg(long pos)
{
int res = kseek(m_File, pos, SEEK_SET);
setState(res == 0);
}
inline void kifstream::seekg(long off, std::ios_base::seekdir dir)
{
int origin;
switch(dir)
{
case std::ios_base::beg: origin = SEEK_SET; break;
case std::ios_base::cur: origin = SEEK_CUR; break;
case std::ios_base::end: origin = SEEK_END; break;
default: setState(false); return;
}
int res = kseek(m_File, off, origin);
setState(res == 0);
}
inline long long kifstream::tellg() const
{
return ktell(m_File);
}
inline void kifstream::setState(bool error)
{
if (!error)
{
m_State = std::ios_base::goodbit;
return;
}
m_State = std::ios_base::failbit;
if (keof(m_File))
m_State |= std::ios_base::eofbit;
else
m_State |= std::ios_base::badbit;
}
inline bool kifstream::good() const
{
return m_State == std::ios_base::goodbit;
}
inline bool kifstream::fail() const
{
return (m_State & (std::ios_base::failbit | std::ios_base::badbit)) != 0;
}
inline bool kifstream::bad() const
{
return (m_State & std::ios_base::badbit) != 0;
}
inline bool kifstream::eof() const
{
return (m_State & std::ios_base::eofbit) != 0;
}
inline std::ios_base::iostate kifstream::rdstate() const
{
return m_State;
}
inline void kifstream::clear(std::ios_base::iostate state)
{
m_State = state;
}
inline void kifstream::setstate(std::ios_base::iostate state)
{
clear(rdstate() | state);
}
| 17.432836
| 79
| 0.684075
|
openlastchaos
|
8ddded375da17fec488d16b92232e2c1a2498443
| 5,902
|
cc
|
C++
|
Dragon/src/operators/norm/group_norm.cc
|
awesome-archive/Dragon
|
b35f9320909d07d138c2f6b345a4c24911f7c521
|
[
"BSD-2-Clause"
] | null | null | null |
Dragon/src/operators/norm/group_norm.cc
|
awesome-archive/Dragon
|
b35f9320909d07d138c2f6b345a4c24911f7c521
|
[
"BSD-2-Clause"
] | null | null | null |
Dragon/src/operators/norm/group_norm.cc
|
awesome-archive/Dragon
|
b35f9320909d07d138c2f6b345a4c24911f7c521
|
[
"BSD-2-Clause"
] | null | null | null |
#include "core/workspace.h"
#include "utils/filler.h"
#include "utils/op_kernel.h"
#include "utils/math_functions.h"
#include "operators/norm/group_norm_op.h"
namespace dragon {
template <class Context> template <typename Tx, typename Tp>
void GroupNormOp<Context>::RunWithType() {
TENSOR_FILL_WITH_TYPE(Input(1), vector<int64_t>({ C }), Tp);
TENSOR_FILL_WITH_TYPE(Input(2), vector<int64_t>({ C }), Tp);
auto* x = Input(0).template data<Tx, Context>();
auto* gamma = Input(1).template data<Tp, Context>();
auto* beta = Input(2).template data<Tp, Context>();
auto* mu = mean->template mutable_data<Tp, Context>();
auto* rsig = var->template mutable_data<Tp, Context>();
auto* s = scale.template mutable_data<Tp, Context>();
auto* b = bias.template mutable_data<Tp, Context>();
auto* y = Output(0)->template mutable_data<Tx, Context>();
// Compute the moments
if (data_format == "NCHW") {
vector<int> dims = { (int)(N * G), (int)(D * S) };
vector<int> axes = { 1 };
kernel::Moments(
2, dims.data(), 1, axes.data(),
x, mu, rsig, ctx());
} else if (data_format == "NHWC") {
vector<int> dims = { (int)N, (int)S, (int)G, (int)D };
vector<int> axes = { 1, 3 };
kernel::Moments(
4, dims.data(), 2, axes.data(),
x, mu, rsig, ctx());
}
math::InvStd(N * G, eps, rsig, rsig, ctx());
kernel::GroupNormForward(N, G, D, S, data_format,
x, mu, rsig, gamma, beta, s, b, y, ctx());
}
template <class Context>
void GroupNormOp<Context>::Reshape() {
// Determine the data format
int64_t channel_axis = axis;
data_format = "NCHW";
if (channel_axis == -1) channel_axis += Input(0).ndim();
if (channel_axis + 1 == Input(0).ndim()) data_format = "NHWC";
if (Input(0).ndim() == 2) data_format = "NCHW";
N = Input(0).dim(0); C = Input(0).dim(channel_axis);
S = Input(0).count() / N / C;
// InstanceNorm, LayerNorm or GroupNorm ?
G = group > 0 ? group : C; D = C / G;
// Check the channels and groups
CHECK_EQ(C % G, 0) << "\nThe " << C << " channels "
<< "can not be split into " << G << " groups.";
if (G == C && Input(0).ndim() == 2)
LOG(WARNING) << "The 2d input will output all zeros.";
// Create the shared resources
mean = ws()->CreateTensor(mount_name(
"gn/mu"))->Reshape({ N * G });
var = ws()->CreateTensor(mount_name(
"gn/rsig"))->Reshape({ N * G });
// Reshape
scale.Reshape({ N * C }); bias.Reshape({ N * C });
Output(0)->ReshapeLike(Input(0));
}
template <class Context>
void GroupNormOp<Context>::RunOnDevice() {
Reshape();
if (XIsType(Input(0), float)) RunWithType<float, float>();
else if (XIsType(Input(0), float16)) RunWithType<float16, float>();
else LOG(FATAL) << DTypeHelper(Input(0), { "float32", "float16" });
}
DEPLOY_CPU(GroupNorm);
#ifdef WITH_CUDA
DEPLOY_CUDA(GroupNorm);
#endif
OPERATOR_SCHEMA(GroupNorm)
.NumInputs(3).NumOutputs(1);
template <class Context> template <typename Tx, typename Tp>
void GroupNormGradientOp<Context>::RunWithType() {
auto* x = Input(0).template data<Tx, Context>();
auto* mu = mean->template data<Tp, Context>();
auto* rsig = var->template data<Tp, Context>();
auto* gamma = Input(1).template data<Tp, Context>();
auto* dy = Input(-1).template data<Tx, Context>();
auto* ds = dscale.template mutable_data<Tp, Context>();
auto* db = dbias.template mutable_data<Tp, Context>();
auto* dx = Output(0)->template mutable_data<Tx, Context>();
auto* dgamma = Output(1)->template mutable_data<Tp, Context>();
auto* dbeta = Output(2)->template mutable_data<Tp, Context>();
kernel::GroupNormBackward(
N, G, D, S, data_format,
x, mu, rsig, gamma, dy,
ds, db, dx, dgamma, dbeta, ctx());
}
template <class Context>
void GroupNormGradientOp<Context>::Reshape() {
// Determine the data format
int64_t channel_axis = axis;
data_format = "NCHW";
if (channel_axis == -1) channel_axis += Input(0).ndim();
if (channel_axis + 1 == Input(0).ndim()) data_format = "NHWC";
if (Input(0).ndim() == 2) data_format = "NCHW";
N = Input(0).dim(0); C = Input(0).dim(channel_axis);
S = Input(0).count() / N / C;
// InstanceNorm, LayerNorm or GroupNorm ?
G = group > 0 ? group : C; D = C / G;
// Check the channels and groups
CHECK_EQ(C % G, 0) << "\nThe " << C << " channels "
<< "can not be split into " << G << " groups.";
if (G == C && Input(0).ndim() == 2)
LOG(WARNING) << "The 2d input will output all zeros.";
// Get the shared resources
mean = ws()->GetTensor(mount_name("gn/mu"));
var = ws()->GetTensor(mount_name("gn/rsig"));
// Reshape
dscale.Reshape({ N * G }); dbias.Reshape({ N * G });
Output(0)->ReshapeLike(Input(0)); // dx
Output(1)->Reshape({ C }); // dgamma
Output(2)->Reshape({ C }); // dbeta
}
template <class Context>
void GroupNormGradientOp<Context>::RunOnDevice() {
Reshape();
if (XIsType(Input(0), float)) RunWithType<float, float>();
else if (XIsType(Input(0), float16)) RunWithType<float16, float>();
else LOG(FATAL) << DTypeHelper(Input(0), { "float32", "float16" });
}
DEPLOY_CPU(GroupNormGradient);
#ifdef WITH_CUDA
DEPLOY_CUDA(GroupNormGradient);
#endif
OPERATOR_SCHEMA(GroupNormGradient)
.NumInputs(3).NumOutputs(3);
class GetGroupNormGradient final : public GradientMakerBase {
public:
GRADIENT_MAKER_CTOR(GetGroupNormGradient);
vector<OperatorDef> MakeDefs() override {
return SingleDef(def.type() + "Gradient", "",
vector<string>({ I(0), I(1), GO(0) }),
vector<string>({ GI(0), GI(1), GI(2) }));
}
};
REGISTER_GRADIENT(GroupNorm, GetGroupNormGradient);
} // namespace dragon
| 34.717647
| 71
| 0.603016
|
awesome-archive
|
8de04c3d945f848d21b8c823ef034a7f5f912d49
| 919
|
cpp
|
C++
|
src/json/ConfigManager.cpp
|
firmware-loader/cpp-firmware-loader
|
895159a50b92526cee59f48d8f42131f5a043879
|
[
"MIT"
] | null | null | null |
src/json/ConfigManager.cpp
|
firmware-loader/cpp-firmware-loader
|
895159a50b92526cee59f48d8f42131f5a043879
|
[
"MIT"
] | 2
|
2019-06-13T18:53:01.000Z
|
2019-06-14T20:13:38.000Z
|
src/json/ConfigManager.cpp
|
firmware-loader/cpp-firmware-loader
|
895159a50b92526cee59f48d8f42131f5a043879
|
[
"MIT"
] | null | null | null |
//
// Created by sebastian on 03.06.19.
//
#include "ConfigManager.h"
namespace firmware::json::config {
ConfigManager::ConfigManager(const std::string &deviceName) {
ConfigFinder config{deviceName};
if (auto &content = config.getFileContents()) {
if(!content->empty()) {
mParser.emplace(*content);
} else {
mError = "config should not be empty!";
}
} else {
mError = content.error();
}
}
ConfigManager::ConfigManager(const std::filesystem::path& filePath) {
auto fileContent = utils::readFile(filePath);
if (fileContent) {
if(!fileContent->empty()) {
mParser.emplace(*fileContent);
} else {
mError = "config should not be empty!";
}
} else {
mError = fileContent.error();
}
}
}
| 29.645161
| 73
| 0.523395
|
firmware-loader
|
8de1fa2a9fe015e112ef79c5d18aeb21b2db14f9
| 3,598
|
cpp
|
C++
|
generated-sources/cpp-restsdk/mojang-api/model/ChangeSkinRequest.cpp
|
AsyncMC/Mojang-API-Libs
|
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
|
[
"Apache-2.0"
] | null | null | null |
generated-sources/cpp-restsdk/mojang-api/model/ChangeSkinRequest.cpp
|
AsyncMC/Mojang-API-Libs
|
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
|
[
"Apache-2.0"
] | null | null | null |
generated-sources/cpp-restsdk/mojang-api/model/ChangeSkinRequest.cpp
|
AsyncMC/Mojang-API-Libs
|
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
|
[
"Apache-2.0"
] | null | null | null |
/**
* Mojang API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 2020-06-05
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.3.4.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "ChangeSkinRequest.h"
namespace com {
namespace github {
namespace asyncmc {
namespace mojang {
namespace api {
namespace cpp {
namespace restsdk {
namespace model {
ChangeSkinRequest::ChangeSkinRequest()
{
m_ModelIsSet = false;
m_Url = utility::conversions::to_string_t("");
}
ChangeSkinRequest::~ChangeSkinRequest()
{
}
void ChangeSkinRequest::validate()
{
// TODO: implement validation
}
web::json::value ChangeSkinRequest::toJson() const
{
web::json::value val = web::json::value::object();
if(m_ModelIsSet)
{
val[utility::conversions::to_string_t("model")] = ModelBase::toJson(m_Model);
}
val[utility::conversions::to_string_t("url")] = ModelBase::toJson(m_Url);
return val;
}
void ChangeSkinRequest::fromJson(const web::json::value& val)
{
if(val.has_field(utility::conversions::to_string_t("model")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("model"));
if(!fieldValue.is_null())
{
std::shared_ptr<SkinModel> newItem(new SkinModel());
newItem->fromJson(fieldValue);
setModel( newItem );
}
}
setUrl(ModelBase::stringFromJson(val.at(utility::conversions::to_string_t("url"))));
}
void ChangeSkinRequest::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m_ModelIsSet)
{
if (m_Model.get())
{
m_Model->toMultipart(multipart, utility::conversions::to_string_t("model."));
}
}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("url"), m_Url));
}
void ChangeSkinRequest::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("model")))
{
if(multipart->hasContent(utility::conversions::to_string_t("model")))
{
std::shared_ptr<SkinModel> newItem(new SkinModel());
newItem->fromMultiPart(multipart, utility::conversions::to_string_t("model."));
setModel( newItem );
}
}
setUrl(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("url"))));
}
std::shared_ptr<SkinModel> ChangeSkinRequest::getModel() const
{
return m_Model;
}
void ChangeSkinRequest::setModel(const std::shared_ptr<SkinModel>& value)
{
m_Model = value;
m_ModelIsSet = true;
}
bool ChangeSkinRequest::modelIsSet() const
{
return m_ModelIsSet;
}
void ChangeSkinRequest::unsetModel()
{
m_ModelIsSet = false;
}
utility::string_t ChangeSkinRequest::getUrl() const
{
return m_Url;
}
void ChangeSkinRequest::setUrl(const utility::string_t& value)
{
m_Url = value;
}
}
}
}
}
}
}
}
}
| 24.47619
| 120
| 0.673152
|
AsyncMC
|
8de2427540199994d234727c62d0615f40bbe0fa
| 113
|
cpp
|
C++
|
SAI/behaviors/VDSAIDefaultBehaviors.cpp
|
VoiDjinn/vdautomata
|
2cfa263d366ec31e298a7743f63a3787f5b6ff0d
|
[
"MIT"
] | null | null | null |
SAI/behaviors/VDSAIDefaultBehaviors.cpp
|
VoiDjinn/vdautomata
|
2cfa263d366ec31e298a7743f63a3787f5b6ff0d
|
[
"MIT"
] | 1
|
2021-07-22T15:18:47.000Z
|
2021-07-26T11:12:32.000Z
|
SAI/behaviors/VDSAIDefaultBehaviors.cpp
|
VoiDjinn/vdautomata
|
2cfa263d366ec31e298a7743f63a3787f5b6ff0d
|
[
"MIT"
] | null | null | null |
#include "VDSAIDefaultBehaviors.h"
VDAsaiDBArrive::VDAsaiDBArrive() {}
void VDAsaiDBArrive::_bind_methods() {}
| 18.833333
| 39
| 0.778761
|
VoiDjinn
|
8de2890abc8b5226dbcbd94a329d87e1159e5e53
| 8,470
|
cpp
|
C++
|
Libs/Idx/src/IdxMosaicAccess.cpp
|
n8vm/OpenVisus
|
dab633f6ecf13ffcf9ac2ad47d51e48902d4aaef
|
[
"Unlicense"
] | 1
|
2019-04-30T12:11:24.000Z
|
2019-04-30T12:11:24.000Z
|
Libs/Idx/src/IdxMosaicAccess.cpp
|
tjhei/OpenVisus
|
f0c3bf21cb0c02f303025a8efb68b8c36701a9fd
|
[
"Unlicense"
] | null | null | null |
Libs/Idx/src/IdxMosaicAccess.cpp
|
tjhei/OpenVisus
|
f0c3bf21cb0c02f303025a8efb68b8c36701a9fd
|
[
"Unlicense"
] | null | null | null |
/*-----------------------------------------------------------------------------
Copyright(c) 2010 - 2018 ViSUS L.L.C.,
Scientific Computing and Imaging Institute of the University of Utah
ViSUS L.L.C., 50 W.Broadway, Ste. 300, 84101 - 2044 Salt Lake City, UT
University of Utah, 72 S Central Campus Dr, Room 3750, 84112 Salt Lake City, UT
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
For additional information about this project contact : pascucci@acm.org
For support : support@visus.net
-----------------------------------------------------------------------------*/
#include <Visus/IdxMosaicAccess.h>
#include <Visus/IdxMultipleDataset.h>
#include <Visus/VisusConfig.h>
#include <Visus/ApplicationStats.h>
namespace Visus {
///////////////////////////////////////////////////////////////////////////////////////
IdxMosaicAccess::IdxMosaicAccess(IdxMultipleDataset* VF_, StringTree CONFIG)
: VF(VF_)
{
VisusReleaseAssert(VF->bMosaic);
if (!VF->valid())
ThrowException("IdxDataset not valid");
this->name = CONFIG.readString("name", "IdxMosaicAccess");
this->CONFIG = CONFIG;
this->can_read = StringUtils::find(CONFIG.readString("chmod", "rw"), "r") >= 0;
this->can_write = StringUtils::find(CONFIG.readString("chmod", "rw"), "w") >= 0;
this->bitsperblock = VF->getDefaultBitsPerBlock();
auto first = VF->childs.begin()->second.dataset;
auto dims = first->getBox().p2;
int pdim = first->getPointDim();
for (auto it : VF->childs)
{
auto vf = std::dynamic_pointer_cast<IdxDataset>(it.second.dataset); VisusAssert(vf);
auto offset = it.second.M.getColumn(3).dropW();
auto index = NdPoint(pdim);
for (int D = 0; D < pdim; D++)
index[D] = ((NdPoint::coord_t)offset[D]) / dims[D];
VisusAssert(!this->childs.count(index));
this->childs[index].dataset=vf;
}
}
///////////////////////////////////////////////////////////////////////////////////////
IdxMosaicAccess::~IdxMosaicAccess()
{
}
///////////////////////////////////////////////////////////////////////////////////////
SharedPtr<Access> IdxMosaicAccess::getChildAccess(const Child& child) const
{
if (child.access)
return child.access;
//with thousansands of childs I don't want to create ThreadPool or NetService
auto config = StringTree();
config.writeBool("disable_async",true);
auto ret = child.dataset->createAccess(config,/*bForBlockQuery*/true);
const_cast<Child&>(child).access = ret;
return ret;
}
///////////////////////////////////////////////////////////////////////////////////////
void IdxMosaicAccess::beginIO(String mode) {
Access::beginIO(mode);
}
///////////////////////////////////////////////////////////////////////////////////////
void IdxMosaicAccess::endIO()
{
for (const auto& it : childs)
{
auto access = it.second.access;
if (access && (access->isReading() || access->isWriting()))
access->endIO();
}
Access::endIO();
}
///////////////////////////////////////////////////////////////////////////////////////
void IdxMosaicAccess::readBlock(SharedPtr<BlockQuery> QUERY)
{
VisusAssert(isReading());
auto pdim = VF->getPointDim();
auto BLOCK = QUERY->start_address >> bitsperblock;
auto first = childs.begin()->second.dataset;
auto NBITS = VF->getMaxResolution() - first->getMaxResolution();
NdPoint dims = first->getBox().p2;
bool bBlockTotallyInsideSingle = (BLOCK >= ((BigInt)1 << NBITS));
if (bBlockTotallyInsideSingle)
{
//forward the block read to a single child
NdPoint p1, index = NdPoint::one(pdim);
for (int D = 0; D < VISUS_NDPOINT_DIM; D++) {
index[D] = QUERY->logic_box.p1[D] / dims[D];
p1[D] = QUERY->logic_box.p1[D] % dims[D];
}
auto it = childs.find(index);
if (it == childs.end())
return readFailed(QUERY);
auto vf = it->second.dataset;
VisusAssert(vf);
auto hzfrom = HzOrder(vf->idxfile.bitmask, vf->getMaxResolution()).getAddress(p1);
auto block_query = std::make_shared<BlockQuery>(QUERY->field, QUERY->time, hzfrom, hzfrom + ((BigInt)1 << bitsperblock), QUERY->aborted);
auto access = getChildAccess(it->second);
if (!access->isReading())
access->beginIO(this->getMode());
//TODO: should I keep track of running queries in order to wait for them in the destructor?
vf->readBlock(access, block_query).when_ready([this, QUERY, block_query](Void) {
if (block_query->failed())
return readFailed(QUERY); //failed
QUERY->buffer = block_query->buffer;
return readOk(QUERY);
});
}
else
{
//THIS IS GOING TO BE SLOW: i need to compose coarse blocks by executing "normal" query and merging them
auto t1 = Time::now();
VisusInfo()<<"IdxMosaicAccess is composing block "<<BLOCK<<" (slow)";
//row major
QUERY->buffer.layout = "";
DatasetBitmask BITMASK = VF->idxfile.bitmask;
HzOrder HZORDER(BITMASK, VF->getMaxResolution());
for (const auto& it : childs)
{
auto vf = it.second.dataset;
auto offset = it.first.innerMultiply(dims);
auto access = getChildAccess(it.second);
auto query = std::make_shared<Query>(vf.get(), 'r');
query->time = QUERY->time;
query->field = QUERY->field;
query->position = QUERY->logic_box.translate(-offset);
query->end_resolutions = { HZORDER.getAddressResolution(BITMASK, QUERY->end_address - 1) - NBITS };
query->start_resolution = BLOCK ? query->end_resolutions[0] : 0;
if (access->isReading() || access->isWriting())
access->endIO();
if (!vf->beginQuery(query))
continue;
if (!query->allocateBufferIfNeeded())
continue;
if (!vf->executeQuery(access, query))
continue;
auto pixel_p1 = NdPoint(pdim); auto logic_p1 = query->logic_box.pixelToLogic(pixel_p1); auto LOGIC_P1 = logic_p1 + offset; auto PIXEL_P1 = QUERY->logic_box.logicToPixel(LOGIC_P1);
auto pixel_p2 = query->buffer.dims; auto logic_p2 = query->logic_box.pixelToLogic(pixel_p2); auto LOGIC_P2 = logic_p2 + offset; auto PIXEL_p2 = QUERY->logic_box.logicToPixel(LOGIC_P2);
ArrayUtils::insert(
QUERY->buffer, PIXEL_P1, PIXEL_p2, NdPoint::one(pdim),
query->buffer, pixel_p1, pixel_p2, NdPoint::one(pdim),
QUERY->aborted);
}
if (bool bPrintStats = false)
{
auto stats = ApplicationStats::io.readValues(true);
VisusInfo() << "!!! BLOCK " << BLOCK << " inside " << (bBlockTotallyInsideSingle ? "yes" : "no")
<< " nopen(" << stats.nopen << ") rbytes(" << StringUtils::getStringFromByteSize(stats.rbytes) << ") wbytes(" << StringUtils::getStringFromByteSize(stats.wbytes) << ")"
<< " msec(" << t1.elapsedMsec() << ")";
}
return QUERY->aborted() ? readFailed(QUERY) : readOk(QUERY);
}
}
///////////////////////////////////////////////////////////////////////////////////////
void IdxMosaicAccess::writeBlock(SharedPtr<BlockQuery> QUERY)
{
//not supported!
VisusAssert(isWriting());
VisusAssert(false);
return writeFailed(QUERY);
}
} //namespace Visus
| 35
| 190
| 0.628808
|
n8vm
|
8de2c262a9224ed23cc47ebc66021bb2ef374350
| 2,947
|
hpp
|
C++
|
src/sdl/surface.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/sdl/surface.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/sdl/surface.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "handle/sdl.hpp"
#include "mutex.hpp"
#include "abstbuffer.hpp"
#include "lubee/src/rect.hpp"
#include "handle/sdl.hpp"
#include <SDL_surface.h>
#include <memory>
namespace rev {
struct RGB;
struct RGBA;
class Surface {
private:
SDL_Surface* _sfc;
mutable Mutex _mutex;
AB_Byte _buff;
class LockObj {
const Surface& _sfc;
void* _bits;
int _pitch;
public:
LockObj(LockObj&& lk) noexcept;
LockObj(const Surface& sfc, void* bits, int pitch) noexcept;
~LockObj();
void* getBits() noexcept;
int getPitch() const noexcept;
operator bool () const noexcept;
};
void _unlock() const noexcept;
Surface(SDL_Surface* sfc) noexcept;
Surface(SDL_Surface* sfc, ByteBuff&& buff) noexcept;
ByteBuff _extractAsContinuous(uint32_t dstFmt=0) const;
public:
struct LoadFailed : std::runtime_error {
using std::runtime_error::runtime_error;
};
static uint32_t Map(uint32_t format, RGB rgb) noexcept;
//! RGBA値をSDLのピクセルフォーマット形式にパックする
static uint32_t Map(uint32_t format, RGBA rgba);
//! SDLのピクセルフォーマットからRGB値を取り出す
static RGBA Get(uint32_t format, uint32_t pixel);
//! SDLのピクセルフォーマット名を表す文字列を取得
static const std::string& GetFormatString(uint32_t format);
//! 任意のフォーマットの画像を読み込む
static HSfc Load(HRW hRW);
//! 空のサーフェス作成
static HSfc Create(int w, int h, uint32_t format);
//! ピクセルデータを元にサーフェス作成
static HSfc Create(const ByteBuff& src, int pitch, int w, int h, uint32_t format);
static HSfc Create(ByteBuff&& src, int pitch, int w, int h, uint32_t format);
~Surface();
void saveAsBMP(HRW hDst) const;
void saveAsPNG(HRW hDst) const;
LockObj lock() const;
LockObj try_lock() const;
const SDL_PixelFormat& getFormat() const noexcept;
uint32_t getFormatEnum() const noexcept;
lubee::SizeI getSize() const noexcept;
int width() const noexcept;
int height() const noexcept;
//! 同サイズのサーフェスを作成
HSfc makeBlank() const;
HSfc duplicate() const;
HSfc flipHorizontal() const;
HSfc flipVertical() const;
//! ピクセルフォーマット変換
HSfc convert(uint32_t fmt) const;
HSfc convert(const SDL_PixelFormat& fmt) const;
//! ピクセルデータがデータ配列先頭から隙間なく詰められているか
bool isContinuous() const noexcept;
//! Continuousな状態でピクセルデータを抽出
ByteBuff extractAsContinuous(uint32_t dstFmt=0) const;
//! ビットブロック転送
void blit(const HSfc& sfc, const lubee::RectI& srcRect, int dstX, int dstY) const;
//! スケーリング有りのビットブロック転送
void blitScaled(const HSfc& sfc, const lubee::RectI& srcRect, const lubee::RectI& dstRect) const;
//! 単色での矩形塗りつぶし
void fillRect(const lubee::RectI& rect, uint32_t color);
SDL_Surface* getSurface() const noexcept;
HSfc resize(const lubee::SizeI& s) const;
void setEnableColorKey(uint32_t key);
void setDisableColorKey();
spi::Optional<uint32_t> getColorKey() const;
void setBlendMode(SDL_BlendMode mode);
SDL_BlendMode getBlendMode() const;
};
}
| 31.688172
| 100
| 0.709196
|
degarashi
|
8de6bdbe7832f99cc8adfa472432fdd5782c2df6
| 10,224
|
cc
|
C++
|
arcane/samples_build/samples/honeycomb_heat/HoneyCombHeatModule.cc
|
grospelliergilles/framework
|
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
|
[
"Apache-2.0"
] | 16
|
2021-09-20T12:37:01.000Z
|
2022-03-18T09:19:14.000Z
|
arcane/samples_build/samples/honeycomb_heat/HoneyCombHeatModule.cc
|
grospelliergilles/framework
|
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
|
[
"Apache-2.0"
] | 66
|
2021-09-17T13:49:39.000Z
|
2022-03-30T16:24:07.000Z
|
arcane/samples_build/samples/honeycomb_heat/HoneyCombHeatModule.cc
|
grospelliergilles/framework
|
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
|
[
"Apache-2.0"
] | 11
|
2021-09-27T16:48:55.000Z
|
2022-03-23T19:06:56.000Z
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* HoneycombHeatModule.cc (C) 2000-2022 */
/* */
/* Module HoneycombHeatModule of honeycomb_heat sample. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "HoneyCombHeat_axl.h"
#include <arcane/ITimeLoopMng.h>
#include <arcane/IItemFamily.h>
#include <arcane/IndexedItemConnectivityView.h>
#include <arcane/IMesh.h>
#include <arcane/UnstructuredMeshConnectivity.h>
#include <arcane/ItemPrinter.h>
#include <arcane/mesh/IncrementalItemConnectivity.h>
using namespace Arcane;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Module HoneyCombHeatModule.
*/
class HoneyCombHeatModule
: public ArcaneHoneyCombHeatObject
{
public:
explicit HoneyCombHeatModule(const ModuleBuildInfo& mbi);
public:
/*!
* \brief Méthode appelée à chaque itération.
*/
void compute() override;
/*!
* \brief Méthode appelée lors de l'initialisation.
*/
void startInit() override;
/** Retourne le numéro de version du module */
VersionInfo versionInfo() const override { return VersionInfo(1, 0, 0); }
private:
//! Connectivités standards du maillage
UnstructuredMeshConnectivityView m_mesh_connectivity_view;
//! Vue sur la connectivité Maille<->Maille par les faces
IndexedCellCellConnectivityView m_cell_cell_connectivity_view;
/*!
* \brief Index de la face (donc entre 0 et 5 (2D) ou 7 (3D)) dans la maille
* voisine pour la i-ème maille connectée.
*
* La valeur de \a i correspond au parcours via m_cell_cell_connectivity_view.
* Pour une maille interne, \a i est aussi l'index de la face dans cette propre maille
* mais ce n'est pas le cas pour une maille externe (c'est à dire une maille qui a
* au moins une face non connectée à une autre maille).
*/
VariableCellArrayInt32 m_cell_neighbour_face_index;
/*!
* \brief Index de la face (donc entre 0 et 5 (2D) ou 7 (3D)) dans notre maille
* pour la i-ème maille connectée.
*
* La valeur de \a i correspond au parcours via m_cell_cell_connectivity_view.
* Pour une maille interne, \a i est aussi l'index de la face dans cette propre maille
* mais ce n'est pas le cas pour une maille externe (c'est à dire une maille qui a
* au moins une face non connectée à une autre maille).
*/
VariableCellArrayInt32 m_cell_current_face_index;
private:
void _applyBoundaryCondition();
Int32 _getNeighbourFaceIndex(CellLocalId cell, CellLocalId neighbour_cell);
Int32 _getCurrentFaceIndex(CellLocalId cell, FaceLocalId face);
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
HoneyCombHeatModule::
HoneyCombHeatModule(const ModuleBuildInfo& mbi)
: ArcaneHoneyCombHeatObject(mbi)
, m_cell_neighbour_face_index(VariableBuildInfo(mbi.meshHandle(), "CellNeighbourFaceIndex"))
, m_cell_current_face_index(VariableBuildInfo(mbi.meshHandle(), "CellCurrentFaceIndex"))
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void HoneyCombHeatModule::
compute()
{
info() << "Module HoneyCombHeatModule COMPUTE";
// Stop code after 10 iterations
if (m_global_iteration() > 500) {
subDomain()->timeLoopMng()->stopComputeLoop(true);
return;
}
// Mise a jour de la temperature aux noeuds en prenant la moyenne
// valeurs aux mailles voisines
ENUMERATE_NODE (inode, allNodes()) {
Node node = *inode;
Real sumt = 0;
for (Cell cell : node.cells())
sumt += m_cell_temperature[cell];
m_node_temperature[inode] = sumt / node.nbCell();
}
m_node_temperature.synchronize();
// Mise a jour de la temperature aux mailles en prenant la moyenne
// des valeurs aux noeuds voisins
ENUMERATE_CELL (icell, allCells()) {
Cell cell = *icell;
Real sumt = 0;
for (Node node : cell.nodes())
sumt += m_node_temperature[node];
m_cell_temperature[icell] = sumt / cell.nbNode();
}
_applyBoundaryCondition();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Retourne l'index dans la liste des faces de 'neighbour_cell' de
* la face commune entre 'cell' et 'neighbour_cell'.
*/
Int32 HoneyCombHeatModule::
_getNeighbourFaceIndex(CellLocalId cell, CellLocalId neighbour_cell)
{
auto cell_face_cv = m_mesh_connectivity_view.cellFace();
Int32 face_neighbour_index = 0;
// Recherche la face commune entre 'neighbour_cell' et 'cell'.
for (FaceLocalId neighbour_face : cell_face_cv.faces(neighbour_cell)) {
for (FaceLocalId current_face : cell_face_cv.faces(cell)) {
if (current_face == neighbour_face)
return face_neighbour_index;
}
++face_neighbour_index;
}
ARCANE_FATAL("No common face between the two cells '{0}' and '{1}'", cell, neighbour_cell);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void HoneyCombHeatModule::
startInit()
{
info() << "Module HoneyCombHeatModule INIT";
m_cell_temperature.fill(0.0);
m_node_temperature.fill(0.0);
// Initialise le pas de temps à une valeur fixe
m_global_deltat = 1.0;
const bool is_verbose = false;
m_mesh_connectivity_view.setMesh(mesh());
// Créé une connectivité Maille/Maille sur les mailles voisines
IItemFamily* cell_family = mesh()->cellFamily();
CellGroup cells = cell_family->allItems();
// NOTE: l'objet est automatiquement détruit par le maillage
auto* cn = new mesh::IncrementalItemConnectivity(cell_family, cell_family, "NeighbourCellCell");
ENUMERATE_CELL (icell, cells) {
Cell cell = *icell;
Integer nb_face = cell.nbFace();
cn->notifySourceItemAdded(cell);
for (Integer i = 0; i < nb_face; ++i) {
Face face = cell.face(i);
if (face.nbCell() == 2) {
Cell opposite_cell = (face.backCell() == cell) ? face.frontCell() : face.backCell();
cn->addConnectedItem(cell, opposite_cell);
}
}
}
m_cell_cell_connectivity_view = cn->connectivityView();
const Int32 max_neighbour = (mesh()->dimension() == 3) ? 8 : 6;
m_cell_neighbour_face_index.resize(max_neighbour);
m_cell_neighbour_face_index.fill(NULL_ITEM_LOCAL_ID);
m_cell_current_face_index.resize(max_neighbour);
m_cell_current_face_index.fill(NULL_ITEM_LOCAL_ID);
// Calcul l'index de la face voisine pour chaque maille connectée
ENUMERATE_ (Cell, icell, cells) {
Cell cell = *icell;
Int32 local_cell_index = 0;
for (CellLocalId neighbour_cell : m_cell_cell_connectivity_view.cells(icell)) {
Int32 neighbour_face_index = _getNeighbourFaceIndex(cell, neighbour_cell);
Int32 current_face_index = _getNeighbourFaceIndex(neighbour_cell, cell);
if (is_verbose)
info() << "Cell=" << cell.uniqueId() << " I=" << local_cell_index
<< " neighbour_cell_local_id=" << neighbour_cell
<< " face_index_in_neighbour_cell=" << neighbour_face_index
<< " face_index_in_current_cell=" << current_face_index;
m_cell_neighbour_face_index[icell][local_cell_index] = neighbour_face_index;
m_cell_current_face_index[icell][local_cell_index] = current_face_index;
++local_cell_index;
}
}
// Vérifie que tout est OK
{
auto cell_face_cv = m_mesh_connectivity_view.cellFace();
ENUMERATE_ (Cell, icell, cells) {
Cell cell = *icell;
auto neighbour_cells_id = m_cell_cell_connectivity_view.cells(icell);
for (Int32 i = 0; i < neighbour_cells_id.size(); ++i) {
CellLocalId neighbour_cell_id = neighbour_cells_id[i];
Int32 neighbour_face_index = m_cell_neighbour_face_index[icell][i];
Int32 current_face_index = m_cell_current_face_index[icell][i];
if (is_verbose)
info() << "Check: Cell=" << cell.uniqueId() << " I=" << i
<< " neighbour_cell_local_id=" << neighbour_cell_id
<< " face_index_in_neighbour_cell=" << neighbour_face_index
<< " face_index_in_current_cell=" << current_face_index;
FaceLocalId neighbour_face_id = cell_face_cv.faces(neighbour_cell_id)[neighbour_face_index];
FaceLocalId current_face_id = cell_face_cv.faces(cell)[current_face_index];
if (neighbour_face_id != current_face_id)
ARCANE_FATAL("Bad face neighbour={0} current={1} cell={2}", neighbour_face_id, current_face_id, ItemPrinter(cell));
}
}
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void HoneyCombHeatModule::
_applyBoundaryCondition()
{
// Les 10 premières mailles ont une température fixe.
ENUMERATE_CELL (icell, allCells()) {
Cell cell = *icell;
if (cell.uniqueId() < 10)
m_cell_temperature[cell] = 10000.0;
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_REGISTER_MODULE_HONEYCOMBHEAT(HoneyCombHeatModule);
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 37.450549
| 125
| 0.586072
|
grospelliergilles
|
8de9dc71831e53c481a3b0fca8d5a92cf9f2941a
| 2,209
|
cpp
|
C++
|
HyoDioForm.cpp
|
hyo0913/DurgaTestSlave
|
913084be0a9ec8ffe5d2fc3f23f7fcb670007f0f
|
[
"MIT"
] | null | null | null |
HyoDioForm.cpp
|
hyo0913/DurgaTestSlave
|
913084be0a9ec8ffe5d2fc3f23f7fcb670007f0f
|
[
"MIT"
] | null | null | null |
HyoDioForm.cpp
|
hyo0913/DurgaTestSlave
|
913084be0a9ec8ffe5d2fc3f23f7fcb670007f0f
|
[
"MIT"
] | null | null | null |
#include "HyoDioForm.h"
#include "ui_HyoDioForm.h"
#include <QHBoxLayout>
#include <QPushButton>
HyoDioForm::HyoDioForm(int points, QWidget *parent) :
QWidget(parent),
ui(new Ui::HyoDioForm)
{
ui->setupUi(this);
this->setObjectName("Digital I/O");
makePoints(points);
this->adjustSize();
}
HyoDioForm::~HyoDioForm()
{
delete ui;
}
void HyoDioForm::makePoints(int points)
{
QHBoxLayout* layout = NULL;
for( int i = 0; i < points; i++ )
{
if( i% 8 == 0 ) {
layout = new QHBoxLayout();
ui->verticalLayout->addLayout(layout);
}
QPushButton* pushButton = new QPushButton();
layout->addWidget(pushButton);
m_points.append(pushButton);
pushButton->setText(QString(""));
QSize size(21, 21);
pushButton->setMaximumSize(size);
pushButton->setMinimumSize(size);
pushButton->setCheckable(true);
QIcon icon;
icon.addFile(":/Icon/IconLampOff", size, QIcon::Normal, QIcon::Off);
icon.addFile(":/Icon/IconLampOn", size, QIcon::Normal, QIcon::On);
pushButton->setIcon(icon);
if( i > 0 && i % 8 == 0 ) {
QSpacerItem* spacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed);
layout->addSpacerItem(spacer);
}
}
}
quint64 HyoDioForm::getValue() const
{
quint64 val = 0;
for( int i = m_points.count()-1; i >= 0; i-- )
{
val <<= 1;
if( this->getValue(i) ) {
val |= 1;
}
}
return val;
}
bool HyoDioForm::getValue(int idx) const
{
if( idx >= m_points.count() ) { return false; }
QPushButton* pushButton = m_points.at(idx);
if( pushButton == NULL ) { return false; }
return pushButton->isChecked();
}
void HyoDioForm::setValue(int idx, bool val)
{
if( idx >= m_points.count() ) { return; }
QPushButton* pushButton = m_points.at(idx);
if( pushButton == NULL ) { return; }
pushButton->setChecked(val);
}
void HyoDioForm::setValue(quint64 val)
{
quint64 bitVal = 1;
for( int i = 0; i < m_points.count(); i++ )
{
setValue(i, (val&bitVal));
bitVal <<= 1;
}
}
| 21.656863
| 100
| 0.57809
|
hyo0913
|
8dea7d0d3b5a4ae3dc71f7840e7fc01a831ada28
| 19,953
|
cpp
|
C++
|
NEST-14.0-FPGA/models/iaf_cond_alpha_mc.cpp
|
OpenHEC/SNN-simulator-on-PYNQcluster
|
14f86a76edf4e8763b58f84960876e95d4efc43a
|
[
"MIT"
] | 45
|
2019-12-09T06:45:53.000Z
|
2022-01-29T12:16:41.000Z
|
NEST-14.0-FPGA/models/iaf_cond_alpha_mc.cpp
|
zlchai/SNN-simulator-on-PYNQcluster
|
14f86a76edf4e8763b58f84960876e95d4efc43a
|
[
"MIT"
] | 2
|
2020-05-23T05:34:21.000Z
|
2021-09-08T02:33:46.000Z
|
NEST-14.0-FPGA/models/iaf_cond_alpha_mc.cpp
|
OpenHEC/SNN-simulator-on-PYNQcluster
|
14f86a76edf4e8763b58f84960876e95d4efc43a
|
[
"MIT"
] | 10
|
2019-12-09T06:45:59.000Z
|
2021-03-25T09:32:56.000Z
|
/*
* iaf_cond_alpha_mc.cpp
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST 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.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "iaf_cond_alpha_mc.h"
#ifdef HAVE_GSL
// C++ includes:
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <limits>
// Includes from libnestutil:
#include "numerics.h"
// Includes from nestkernel:
#include "exceptions.h"
#include "kernel_manager.h"
#include "universal_data_logger_impl.h"
// Includes from sli:
#include "dict.h"
#include "dictutils.h"
#include "doubledatum.h"
#include "integerdatum.h"
/* ----------------------------------------------------------------
* Compartment name list
* ---------------------------------------------------------------- */
/* Harold Gutch reported some static destruction problems on OSX 10.4.
He pointed out that the problem is avoided by defining the comp_names_
vector with its final size. See also #348.
*/
std::vector< Name > nest::iaf_cond_alpha_mc::comp_names_( NCOMP );
/* ----------------------------------------------------------------
* Receptor dictionary
* ---------------------------------------------------------------- */
// leads to seg fault on exit, see #328
// DictionaryDatum nest::iaf_cond_alpha_mc::receptor_dict_ = new Dictionary();
/* ----------------------------------------------------------------
* Recordables map
* ---------------------------------------------------------------- */
nest::RecordablesMap< nest::iaf_cond_alpha_mc >
nest::iaf_cond_alpha_mc::recordablesMap_;
namespace nest
{
// specialization must be place in namespace
template <>
void
RecordablesMap< iaf_cond_alpha_mc >::create()
{
insert_( Name( "V_m.s" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::V_M,
iaf_cond_alpha_mc::SOMA > );
insert_( Name( "g_ex.s" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::G_EXC,
iaf_cond_alpha_mc::SOMA > );
insert_( Name( "g_in.s" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::G_INH,
iaf_cond_alpha_mc::SOMA > );
insert_( Name( "V_m.p" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::V_M,
iaf_cond_alpha_mc::PROX > );
insert_( Name( "g_ex.p" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::G_EXC,
iaf_cond_alpha_mc::PROX > );
insert_( Name( "g_in.p" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::G_INH,
iaf_cond_alpha_mc::PROX > );
insert_( Name( "V_m.d" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::V_M,
iaf_cond_alpha_mc::DIST > );
insert_( Name( "g_ex.d" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::G_EXC,
iaf_cond_alpha_mc::DIST > );
insert_( Name( "g_in.d" ),
&iaf_cond_alpha_mc::get_y_elem_< iaf_cond_alpha_mc::State_::G_INH,
iaf_cond_alpha_mc::DIST > );
insert_( names::t_ref_remaining, &iaf_cond_alpha_mc::get_r_ );
}
}
/* ----------------------------------------------------------------
* Iteration function
* ---------------------------------------------------------------- */
extern "C" int
nest::iaf_cond_alpha_mc_dynamics( double,
const double y[],
double f[],
void* pnode )
{
// some shorthands
typedef nest::iaf_cond_alpha_mc N;
typedef nest::iaf_cond_alpha_mc::State_ S;
// get access to node so we can work almost as in a member function
assert( pnode );
const nest::iaf_cond_alpha_mc& node =
*( reinterpret_cast< nest::iaf_cond_alpha_mc* >( pnode ) );
// compute dynamics for each compartment
// computations written quite explicitly for clarity, assume compile
// will optimized most stuff away ...
for ( size_t n = 0; n < N::NCOMP; ++n )
{
// membrane potential for current compartment
const double V = y[ S::idx( n, S::V_M ) ];
// excitatory synaptic current
const double I_syn_exc =
y[ S::idx( n, S::G_EXC ) ] * ( V - node.P_.E_ex[ n ] );
// inhibitory synaptic current
const double I_syn_inh =
y[ S::idx( n, S::G_INH ) ] * ( V - node.P_.E_in[ n ] );
// leak current
const double I_L = node.P_.g_L[ n ] * ( V - node.P_.E_L[ n ] );
// coupling currents
const double I_conn =
( n > N::SOMA
? node.P_.g_conn[ n - 1 ] * ( V - y[ S::idx( n - 1, S::V_M ) ] )
: 0 )
+ ( n < N::NCOMP - 1
? node.P_.g_conn[ n ] * ( V - y[ S::idx( n + 1, S::V_M ) ] )
: 0 );
// derivatives
// membrane potential
f[ S::idx( n, S::V_M ) ] =
( -I_L - I_syn_exc - I_syn_inh - I_conn + node.B_.I_stim_[ n ]
+ node.P_.I_e[ n ] ) / node.P_.C_m[ n ];
// excitatory conductance
f[ S::idx( n, S::DG_EXC ) ] =
-y[ S::idx( n, S::DG_EXC ) ] / node.P_.tau_synE[ n ];
f[ S::idx( n, S::G_EXC ) ] = y[ S::idx( n, S::DG_EXC ) ]
- y[ S::idx( n, S::G_EXC ) ] / node.P_.tau_synE[ n ];
// inhibitory conductance
f[ S::idx( n, S::DG_INH ) ] =
-y[ S::idx( n, S::DG_INH ) ] / node.P_.tau_synI[ n ];
f[ S::idx( n, S::G_INH ) ] = y[ S::idx( n, S::DG_INH ) ]
- y[ S::idx( n, S::G_INH ) ] / node.P_.tau_synI[ n ];
}
return GSL_SUCCESS;
}
/* ----------------------------------------------------------------
* Default constructors defining default parameters and state
* ---------------------------------------------------------------- */
nest::iaf_cond_alpha_mc::Parameters_::Parameters_()
: V_th( -55.0 ) // mV
, V_reset( -60.0 ) // mV
, t_ref( 2.0 ) // ms
{
// conductances between compartments
g_conn[ SOMA ] = 2.5; // nS, soma-proximal
g_conn[ PROX ] = 1.0; // nS, proximal-distal
// soma parameters
g_L[ SOMA ] = 10.0; // nS
C_m[ SOMA ] = 150.0; // pF
E_ex[ SOMA ] = 0.0; // mV
E_in[ SOMA ] = -85.0; // mV
E_L[ SOMA ] = -70.0; // mV
tau_synE[ SOMA ] = 0.5; // ms
tau_synI[ SOMA ] = 2.0; // ms
I_e[ SOMA ] = 0.0; // pA
// proximal parameters
g_L[ PROX ] = 5.0; // nS
C_m[ PROX ] = 75.0; // pF
E_ex[ PROX ] = 0.0; // mV
E_in[ PROX ] = -85.0; // mV
E_L[ PROX ] = -70.0; // mV
tau_synE[ PROX ] = 0.5; // ms
tau_synI[ PROX ] = 2.0; // ms
I_e[ PROX ] = 0.0; // pA
// distal parameters
g_L[ DIST ] = 10.0; // nS
C_m[ DIST ] = 150.0; // pF
E_ex[ DIST ] = 0.0; // mV
E_in[ DIST ] = -85.0; // mV
E_L[ DIST ] = -70.0; // mV
tau_synE[ DIST ] = 0.5; // ms
tau_synI[ DIST ] = 2.0; // ms
I_e[ DIST ] = 0.0; // pA
}
nest::iaf_cond_alpha_mc::Parameters_::Parameters_( const Parameters_& p )
: V_th( p.V_th )
, V_reset( p.V_reset )
, t_ref( p.t_ref )
{
// copy C-arrays
for ( size_t n = 0; n < NCOMP - 1; ++n )
{
g_conn[ n ] = p.g_conn[ n ];
}
for ( size_t n = 0; n < NCOMP; ++n )
{
g_L[ n ] = p.g_L[ n ];
C_m[ n ] = p.C_m[ n ];
E_ex[ n ] = p.E_ex[ n ];
E_in[ n ] = p.E_in[ n ];
E_L[ n ] = p.E_L[ n ];
tau_synE[ n ] = p.tau_synE[ n ];
tau_synI[ n ] = p.tau_synI[ n ];
I_e[ n ] = p.I_e[ n ];
}
}
nest::iaf_cond_alpha_mc::Parameters_& nest::iaf_cond_alpha_mc::Parameters_::
operator=( const Parameters_& p )
{
assert( this != &p ); // would be bad logical error in program
V_th = p.V_th;
V_reset = p.V_reset;
t_ref = p.t_ref;
// copy C-arrays
for ( size_t n = 0; n < NCOMP - 1; ++n )
{
g_conn[ n ] = p.g_conn[ n ];
}
for ( size_t n = 0; n < NCOMP; ++n )
{
g_L[ n ] = p.g_L[ n ];
C_m[ n ] = p.C_m[ n ];
E_ex[ n ] = p.E_ex[ n ];
E_in[ n ] = p.E_in[ n ];
E_L[ n ] = p.E_L[ n ];
tau_synE[ n ] = p.tau_synE[ n ];
tau_synI[ n ] = p.tau_synI[ n ];
I_e[ n ] = p.I_e[ n ];
}
return *this;
}
nest::iaf_cond_alpha_mc::State_::State_( const Parameters_& p )
: r_( 0 )
{
// for simplicity, we first initialize all values to 0,
// then set the membrane potentials for each compartment
for ( size_t i = 0; i < STATE_VEC_SIZE; ++i )
{
y_[ i ] = 0;
}
for ( size_t n = 0; n < NCOMP; ++n )
{
y_[ idx( n, V_M ) ] = p.E_L[ n ];
}
}
nest::iaf_cond_alpha_mc::State_::State_( const State_& s )
: r_( s.r_ )
{
for ( size_t i = 0; i < STATE_VEC_SIZE; ++i )
{
y_[ i ] = s.y_[ i ];
}
}
nest::iaf_cond_alpha_mc::State_& nest::iaf_cond_alpha_mc::State_::operator=(
const State_& s )
{
assert( this != &s ); // would be bad logical error in program
for ( size_t i = 0; i < STATE_VEC_SIZE; ++i )
{
y_[ i ] = s.y_[ i ];
}
r_ = s.r_;
return *this;
}
nest::iaf_cond_alpha_mc::Buffers_::Buffers_( iaf_cond_alpha_mc& n )
: logger_( n )
, s_( 0 )
, c_( 0 )
, e_( 0 )
{
// Initialization of the remaining members is deferred to
// init_buffers_().
}
nest::iaf_cond_alpha_mc::Buffers_::Buffers_( const Buffers_&,
iaf_cond_alpha_mc& n )
: logger_( n )
, s_( 0 )
, c_( 0 )
, e_( 0 )
{
// Initialization of the remaining members is deferred to
// init_buffers_().
}
/* ----------------------------------------------------------------
* Parameter and state extractions and manipulation functions
* ---------------------------------------------------------------- */
void
nest::iaf_cond_alpha_mc::Parameters_::get( DictionaryDatum& d ) const
{
def< double >( d, names::V_th, V_th );
def< double >( d, names::V_reset, V_reset );
def< double >( d, names::t_ref, t_ref );
def< double >( d, names::g_sp, g_conn[ SOMA ] );
def< double >( d, names::g_pd, g_conn[ PROX ] );
// create subdictionaries for per-compartment parameters
for ( size_t n = 0; n < NCOMP; ++n )
{
DictionaryDatum dd = new Dictionary();
def< double >( dd, names::g_L, g_L[ n ] );
def< double >( dd, names::E_L, E_L[ n ] );
def< double >( dd, names::E_ex, E_ex[ n ] );
def< double >( dd, names::E_in, E_in[ n ] );
def< double >( dd, names::C_m, C_m[ n ] );
def< double >( dd, names::tau_syn_ex, tau_synE[ n ] );
def< double >( dd, names::tau_syn_in, tau_synI[ n ] );
def< double >( dd, names::I_e, I_e[ n ] );
( *d )[ comp_names_[ n ] ] = dd;
}
}
void
nest::iaf_cond_alpha_mc::Parameters_::set( const DictionaryDatum& d )
{
// allow setting the membrane potential
updateValue< double >( d, names::V_th, V_th );
updateValue< double >( d, names::V_reset, V_reset );
updateValue< double >( d, names::t_ref, t_ref );
updateValue< double >( d, Name( names::g_sp ), g_conn[ SOMA ] );
updateValue< double >( d, Name( names::g_pd ), g_conn[ PROX ] );
// extract from sub-dictionaries
for ( size_t n = 0; n < NCOMP; ++n )
{
if ( d->known( comp_names_[ n ] ) )
{
DictionaryDatum dd = getValue< DictionaryDatum >( d, comp_names_[ n ] );
updateValue< double >( dd, names::E_L, E_L[ n ] );
updateValue< double >( dd, names::E_ex, E_ex[ n ] );
updateValue< double >( dd, names::E_in, E_in[ n ] );
updateValue< double >( dd, names::C_m, C_m[ n ] );
updateValue< double >( dd, names::g_L, g_L[ n ] );
updateValue< double >( dd, names::tau_syn_ex, tau_synE[ n ] );
updateValue< double >( dd, names::tau_syn_in, tau_synI[ n ] );
updateValue< double >( dd, names::I_e, I_e[ n ] );
}
}
if ( V_reset >= V_th )
{
throw BadProperty( "Reset potential must be smaller than threshold." );
}
if ( t_ref < 0 )
{
throw BadProperty( "Refractory time cannot be negative." );
}
// apply checks compartment-wise
for ( size_t n = 0; n < NCOMP; ++n )
{
if ( C_m[ n ] <= 0 )
{
throw BadProperty( "Capacitance (" + comp_names_[ n ].toString()
+ ") must be strictly positive." );
}
if ( tau_synE[ n ] <= 0 || tau_synI[ n ] <= 0 )
{
throw BadProperty( "All time constants (" + comp_names_[ n ].toString()
+ ") must be strictly positive." );
}
}
}
void
nest::iaf_cond_alpha_mc::State_::get( DictionaryDatum& d ) const
{
// we assume here that State_::get() always is called after
// Parameters_::get(), so that the per-compartment dictionaries exist
for ( size_t n = 0; n < NCOMP; ++n )
{
assert( d->known( comp_names_[ n ] ) );
DictionaryDatum dd = getValue< DictionaryDatum >( d, comp_names_[ n ] );
def< double >( dd, names::V_m, y_[ idx( n, V_M ) ] ); // Membrane potential
}
}
void
nest::iaf_cond_alpha_mc::State_::set( const DictionaryDatum& d,
const Parameters_& )
{
// extract from sub-dictionaries
for ( size_t n = 0; n < NCOMP; ++n )
{
if ( d->known( comp_names_[ n ] ) )
{
DictionaryDatum dd = getValue< DictionaryDatum >( d, comp_names_[ n ] );
updateValue< double >( dd, names::V_m, y_[ idx( n, V_M ) ] );
}
}
}
/* ----------------------------------------------------------------
* Default and copy constructor for node, and destructor
* ---------------------------------------------------------------- */
nest::iaf_cond_alpha_mc::iaf_cond_alpha_mc()
: Archiving_Node()
, P_()
, S_( P_ )
, B_( *this )
{
recordablesMap_.create();
// set up table of compartment names
// comp_names_.resize(NCOMP); --- Fixed size, see comment on definition
comp_names_[ SOMA ] = Name( "soma" );
comp_names_[ PROX ] = Name( "proximal" );
comp_names_[ DIST ] = Name( "distal" );
}
nest::iaf_cond_alpha_mc::iaf_cond_alpha_mc( const iaf_cond_alpha_mc& n )
: Archiving_Node( n )
, P_( n.P_ )
, S_( n.S_ )
, B_( n.B_, *this )
{
}
nest::iaf_cond_alpha_mc::~iaf_cond_alpha_mc()
{
// GSL structs may not have been allocated, so we need to protect destruction
if ( B_.s_ )
{
gsl_odeiv_step_free( B_.s_ );
}
if ( B_.c_ )
{
gsl_odeiv_control_free( B_.c_ );
}
if ( B_.e_ )
{
gsl_odeiv_evolve_free( B_.e_ );
}
}
/* ----------------------------------------------------------------
* Node initialization functions
* ---------------------------------------------------------------- */
void
nest::iaf_cond_alpha_mc::init_state_( const Node& proto )
{
const iaf_cond_alpha_mc& pr = downcast< iaf_cond_alpha_mc >( proto );
S_ = pr.S_;
}
void
nest::iaf_cond_alpha_mc::init_buffers_()
{
B_.spikes_.resize( NUM_SPIKE_RECEPTORS );
for ( size_t n = 0; n < NUM_SPIKE_RECEPTORS; ++n )
{
B_.spikes_[ n ].clear();
} // includes resize
B_.currents_.resize( NUM_CURR_RECEPTORS );
for ( size_t n = 0; n < NUM_CURR_RECEPTORS; ++n )
{
B_.currents_[ n ].clear();
} // includes resize
B_.logger_.reset();
Archiving_Node::clear_history();
B_.step_ = Time::get_resolution().get_ms();
B_.IntegrationStep_ = B_.step_;
if ( B_.s_ == 0 )
{
B_.s_ =
gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
}
else
{
gsl_odeiv_step_reset( B_.s_ );
}
if ( B_.c_ == 0 )
{
B_.c_ = gsl_odeiv_control_y_new( 1e-3, 0.0 );
}
else
{
gsl_odeiv_control_init( B_.c_, 1e-3, 0.0, 1.0, 0.0 );
}
if ( B_.e_ == 0 )
{
B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
}
else
{
gsl_odeiv_evolve_reset( B_.e_ );
}
B_.sys_.function = iaf_cond_alpha_mc_dynamics;
B_.sys_.jacobian = NULL;
B_.sys_.dimension = State_::STATE_VEC_SIZE;
B_.sys_.params = reinterpret_cast< void* >( this );
for ( size_t n = 0; n < NCOMP; ++n )
{
B_.I_stim_[ n ] = 0.0;
}
}
void
nest::iaf_cond_alpha_mc::calibrate()
{
// ensures initialization in case mm connected after Simulate
B_.logger_.init();
for ( size_t n = 0; n < NCOMP; ++n )
{
V_.PSConInit_E_[ n ] = 1.0 * numerics::e / P_.tau_synE[ n ];
V_.PSConInit_I_[ n ] = 1.0 * numerics::e / P_.tau_synI[ n ];
}
V_.RefractoryCounts_ = Time( Time::ms( P_.t_ref ) ).get_steps();
// since t_ref >= 0, this can only fail in error
assert( V_.RefractoryCounts_ >= 0 );
}
/* ----------------------------------------------------------------
* Update and spike handling functions
* ---------------------------------------------------------------- */
void
nest::iaf_cond_alpha_mc::update( Time const& origin,
const long from,
const long to )
{
assert(
to >= 0 && ( delay ) from < kernel().connection_manager.get_min_delay() );
assert( from < to );
for ( long lag = from; lag < to; ++lag )
{
double t = 0.0;
// numerical integration with adaptive step size control:
// ------------------------------------------------------
// gsl_odeiv_evolve_apply performs only a single numerical
// integration step, starting from t and bounded by step;
// the while-loop ensures integration over the whole simulation
// step (0, step] if more than one integration step is needed due
// to a small integration step size;
// note that (t+IntegrationStep > step) leads to integration over
// (t, step] and afterwards setting t to step, but it does not
// enforce setting IntegrationStep to step-t; this is of advantage
// for a consistent and efficient integration across subsequent
// simulation intervals
while ( t < B_.step_ )
{
const int status = gsl_odeiv_evolve_apply( B_.e_,
B_.c_,
B_.s_,
&B_.sys_, // system of ODE
&t, // from t
B_.step_, // to t <= step
&B_.IntegrationStep_, // integration step size
S_.y_ ); // neuronal state
if ( status != GSL_SUCCESS )
{
throw GSLSolverFailure( get_name(), status );
}
}
// add incoming spikes at end of interval
// exploit here that spike buffers are compartment for compartment,
// alternating between excitatory and inhibitory
for ( size_t n = 0; n < NCOMP; ++n )
{
S_.y_[ n * State_::STATE_VEC_COMPS + State_::DG_EXC ] +=
B_.spikes_[ 2 * n ].get_value( lag ) * V_.PSConInit_E_[ n ];
S_.y_[ n * State_::STATE_VEC_COMPS + State_::DG_INH ] +=
B_.spikes_[ 2 * n + 1 ].get_value( lag ) * V_.PSConInit_I_[ n ];
}
// refractoriness and spiking
// exploit here that plain offset enum value V_M indexes soma V_M
if ( S_.r_ )
{ // neuron is absolute refractory
--S_.r_;
S_.y_[ State_::V_M ] = P_.V_reset;
}
else if ( S_.y_[ State_::V_M ] >= P_.V_th )
{ // neuron fires spike
S_.r_ = V_.RefractoryCounts_;
S_.y_[ State_::V_M ] = P_.V_reset;
set_spiketime( Time::step( origin.get_steps() + lag + 1 ) );
SpikeEvent se;
kernel().event_delivery_manager.send( *this, se, lag );
}
// set new input currents
for ( size_t n = 0; n < NCOMP; ++n )
{
B_.I_stim_[ n ] = B_.currents_[ n ].get_value( lag );
}
// log state data
B_.logger_.record_data( origin.get_steps() + lag );
}
}
void
nest::iaf_cond_alpha_mc::handle( SpikeEvent& e )
{
assert( e.get_delay() > 0 );
assert( 0 <= e.get_rport() && e.get_rport() < 2 * NCOMP );
B_.spikes_[ e.get_rport() ].add_value(
e.get_rel_delivery_steps( kernel().simulation_manager.get_slice_origin() ),
e.get_weight() * e.get_multiplicity() );
}
void
nest::iaf_cond_alpha_mc::handle( CurrentEvent& e )
{
assert( e.get_delay() > 0 );
// not 100% clean, should look at MIN, SUP
assert( 0 <= e.get_rport() && e.get_rport() < NCOMP );
// add weighted current; HEP 2002-10-04
B_.currents_[ e.get_rport() ].add_value(
e.get_rel_delivery_steps( kernel().simulation_manager.get_slice_origin() ),
e.get_weight() * e.get_current() );
}
void
nest::iaf_cond_alpha_mc::handle( DataLoggingRequest& e )
{
B_.logger_.handle( e );
}
#endif // HAVE_GSL
| 28.302128
| 79
| 0.565629
|
OpenHEC
|
8deca7c3cc465cea32e06b3586fa6f8c0766b8ef
| 2,154
|
hh
|
C++
|
runtime/windows/include/log4tango/threading/DummyThreads.hh
|
t-b/igorpro-binding
|
9b9d3568d37bc0db5a107d019854e529e19008df
|
[
"BSD-3-Clause"
] | null | null | null |
runtime/windows/include/log4tango/threading/DummyThreads.hh
|
t-b/igorpro-binding
|
9b9d3568d37bc0db5a107d019854e529e19008df
|
[
"BSD-3-Clause"
] | null | null | null |
runtime/windows/include/log4tango/threading/DummyThreads.hh
|
t-b/igorpro-binding
|
9b9d3568d37bc0db5a107d019854e529e19008df
|
[
"BSD-3-Clause"
] | null | null | null |
//
// DummyThreads.hh
//
// Copyright (C) : 2000 - 2002
// LifeLine Networks BV (www.lifeline.nl). All rights reserved.
// Bastiaan Bakker. All rights reserved.
//
// 2004,2005,2006,2007,2008,2009,2010,2011,2012
// Synchrotron SOLEIL
// L'Orme des Merisiers
// Saint-Aubin - BP 48 - France
//
// This file is part of log4tango.
//
// Log4ango is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Log4tango 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 Log4Tango. If not, see <http://www.gnu.org/licenses/>.
#ifndef _LOG4TANGO_THREADING_DUMMY_THREADS_H
#define _LOG4TANGO_THREADING_DUMMY_THREADS_H
#include <log4tango/Portability.hh>
#include <stdio.h>
#include <string>
namespace log4tango {
namespace threading {
std::string get_thread_id (void);
typedef int Mutex;
typedef int ScopedLock;
#ifdef LOG4TANGO_HAS_NDC
template<typename T> class ThreadLocalDataHolder
{
public:
typedef T data_type;
inline ThreadLocalDataHolder ()
: _data(0)
{
//no-op
};
inline ~ThreadLocalDataHolder () {
if (_data) {
delete _data;
}
};
inline T* get (void) const {
return _data;
};
inline T* operator->() const {
return get();
};
inline T& operator*() const {
return *get();
};
inline T* release() {
T* result = _data;
_data = 0;
return result;
};
inline void reset (T* p = 0) {
if (_data) {
delete _data;
}
_data = p;
};
private:
T* _data;
};
#endif // #ifdef LOG4TANGO_HAS_NDC
} // namespace threading
} // namespace log4tango
#endif // _LOG4TANGO_THREADING_DUMMY_THREADS_H
| 21.979592
| 78
| 0.659239
|
t-b
|
8dee852bf0b19030413966eb84a31b0f739c6149
| 693
|
cpp
|
C++
|
src/Hazel/Audio/AudioManager.cpp
|
TroyNeubauer/hazel
|
f2c1993048e6e12ab0a44a533343c9da54004233
|
[
"Apache-2.0"
] | 1
|
2019-10-21T20:50:07.000Z
|
2019-10-21T20:50:07.000Z
|
src/Hazel/Audio/AudioManager.cpp
|
TroyNeubauer/hazel
|
f2c1993048e6e12ab0a44a533343c9da54004233
|
[
"Apache-2.0"
] | null | null | null |
src/Hazel/Audio/AudioManager.cpp
|
TroyNeubauer/hazel
|
f2c1993048e6e12ab0a44a533343c9da54004233
|
[
"Apache-2.0"
] | null | null | null |
#include "hzpch.h"
#include "AudioManager.h"
#include "Platform/LabSound/LabSoundAudioManager.h"
#include "Platform/NoAPI/NoAPIAudio.h"
namespace Hazel {
Scope<AudioManagerImpl> AudioManager::s_Instance;
void Hazel::AudioManager::Init()
{
HZ_CORE_ASSERT(!s_Instance, "Audio Manager already exists!");
#if defined(HZ_USE_AUDIO_NONE)
s_Instance.reset(new NoAPIAudioManager());
#elif defined(HZ_USE_LABSOUND_AUDIO)
s_Instance.reset(new LabSoundAudioManager());
#elif defined(HZ_USE_JS_AUDIO)
#error JS not supported yet
s_Instance.reset(...);
#else
#error No audio API selected
#endif
}
void Hazel::AudioManager::Shutdown()
{
s_Instance.reset(nullptr);//Free impl
}
}
| 21
| 63
| 0.756133
|
TroyNeubauer
|
8df257d3deff0e3d644a3a50d4208e0c9af07099
| 5,698
|
hpp
|
C++
|
include/Core/Castor3D/Shader/Program.hpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 245
|
2015-10-29T14:31:45.000Z
|
2022-03-31T13:04:45.000Z
|
include/Core/Castor3D/Shader/Program.hpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 64
|
2016-03-11T19:45:05.000Z
|
2022-03-31T23:58:33.000Z
|
include/Core/Castor3D/Shader/Program.hpp
|
Mu-L/Castor3D
|
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
|
[
"MIT"
] | 11
|
2018-05-24T09:07:43.000Z
|
2022-03-21T21:05:20.000Z
|
/*
See LICENSE file in root folder
*/
#ifndef ___C3D_ShaderProgram_H___
#define ___C3D_ShaderProgram_H___
#include "ShaderModule.hpp"
#include "Castor3D/Cache/CacheModule.hpp"
#include "Castor3D/Miscellaneous/DebugName.hpp"
#include "Castor3D/Render/RenderDevice.hpp"
#include <CastorUtils/Data/TextWriter.hpp>
#include <CastorUtils/Design/Named.hpp>
#include <ShaderAST/Shader.hpp>
#include <ashespp/Core/Device.hpp>
#include <ashespp/Pipeline/PipelineShaderStageCreateInfo.hpp>
namespace castor3d
{
class ShaderProgram
: public castor::Named
, public castor::OwnedBy< RenderSystem >
, public std::enable_shared_from_this< ShaderProgram >
{
friend class castor::TextWriter< castor3d::ShaderProgram >;
public:
struct CompiledShader
{
castor::String name;
SpirVShader shader;
};
public:
/**
*\~english
*\brief Constructor
*\param[in] name The program name.
*\param[in] renderSystem The RenderSystem.
*\~french
*\brief Constructeur
*\param[in] name Le nom du programme.
*\param[in] renderSystem Le RenderSystem.
*/
C3D_API explicit ShaderProgram( castor::String const & name
, RenderSystem & renderSystem );
/**
*\~english
*\brief Destructor.
*\~french
*\brief Destructeur.
*/
C3D_API ~ShaderProgram();
/**
*\~english
*\brief Sets the shader file.
*\param[in] target The shader module concerned.
*\param[in] pathFile The file name.
*\~french
*\brief Définit le fichier du shader.
*\param[in] target Le module shader concerné.
*\param[in] pathFile Le nom du fichier.
*/
C3D_API void setFile( VkShaderStageFlagBits target, castor::Path const & pathFile );
/**
*\~english
*\brief Retrieves the shader file.
*\param[in] target The shader object concerned.
*\return The file name.
*\~french
*\brief Récupère le fichier du shader.
*\param[in] target Le shader object concerné.
*\return Le nom du fichier.
*/
C3D_API castor::Path getFile( VkShaderStageFlagBits target )const;
/**
*\~english
*\brief Tells if the shader object has a source file.
*\param[in] target The shader object concerned.
*\return \p true if the shader object has a source file.
*\~french
*\brief Dit si le shader a un fichier source.
*\param[in] target Le shader object concerné.
*\return \p true si le shader a un fichier source.
*/
C3D_API bool hasFile( VkShaderStageFlagBits target )const;
/**
*\~english
*\brief Sets the shader source.
*\param[in] target The shader object concerned.
*\param[in] source The source code.
*\~french
*\brief Définit la source du shader.
*\param[in] target Le shader object concerné.
*\param[in] source Le code de la source.
*/
C3D_API void setSource( VkShaderStageFlagBits target, castor::String const & source );
/**
*\~english
*\brief Sets the shader source.
*\param[in] target The shader object concerned.
*\param[in] shader The source shader.
*\~french
*\brief Définit la source du shader.
*\param[in] target Le shader object concerné.
*\param[in] shader Le shader de la source.
*/
C3D_API void setSource( VkShaderStageFlagBits target, ShaderPtr shader );
/**
*\~english
*\brief Retrieves the shader source.
*\param[in] target The shader object concerned.
*\return The source code.
*\~french
*\brief Récupère la source du shader.
*\param[in] target Le shader object concerné.
*\return Le code de la source.
*/
C3D_API ShaderModule const & getSource( VkShaderStageFlagBits target )const;
/**
*\~english
*\brief Tells if the shader object has a source code.
*\param[in] target The shader object concerned.
*\return \p true if the shader object has a source code.
*\~french
*\brief Dit si le shader a un code source.
*\param[in] target Le shader object concerné.
*\return \p true si le shader a un code source.
*/
C3D_API bool hasSource( VkShaderStageFlagBits target )const;
/**
*\~english
*name
* Getters.
*\~french
*name
* Accesseurs.
*/
/**@{*/
inline ashes::PipelineShaderStageCreateInfoArray const & getStates()const
{
return m_states;
}
/**@}*/
protected:
std::map< VkShaderStageFlagBits, castor::Path > m_files;
std::map< VkShaderStageFlagBits, ShaderModule > m_modules;
std::map< VkShaderStageFlagBits, CompiledShader > m_compiled;
ashes::PipelineShaderStageCreateInfoArray m_states;
};
C3D_API SpirVShader compileShader( RenderDevice const & device
, ShaderModule const & module );
C3D_API SpirVShader compileShader( RenderSystem const & renderSystem
, ShaderModule const & module );
inline ashes::PipelineShaderStageCreateInfo makeShaderState( ashes::Device const & device
, VkShaderStageFlagBits stage
, SpirVShader code
, std::string const & name
, std::string mainFuncName = "main"
, ashes::Optional< ashes::SpecializationInfo > specialization = ashes::nullopt )
{
auto module = device.createShaderModule( name + "ShdMod" + "_" + ashes::getName( stage )
, code.spirv );
return ashes::PipelineShaderStageCreateInfo
{
0u,
stage,
std::move( module ),
std::move( mainFuncName ),
std::move( specialization ),
};
}
inline ashes::PipelineShaderStageCreateInfo makeShaderState( RenderDevice const & device
, ShaderModule const & shaderModule
, std::string mainFuncName = "main"
, ashes::Optional< ashes::SpecializationInfo > specialization = ashes::nullopt )
{
return makeShaderState( *device
, shaderModule.stage
, compileShader( device, shaderModule )
, shaderModule.name
, std::move( mainFuncName )
, std::move( specialization ) );
}
}
#endif
| 29.220513
| 90
| 0.697087
|
Mu-L
|
8df47a1349ede49810cac1e0af817265deb200f5
| 2,140
|
cpp
|
C++
|
tests/fuzz/fuzzScale.cpp
|
Lederstrumpf/substrate-c-tool
|
999bc55ffa2f354b96c347ebb122c79baad812cc
|
[
"MIT"
] | 2
|
2020-05-27T17:45:37.000Z
|
2022-03-05T01:31:29.000Z
|
tests/fuzz/fuzzScale.cpp
|
Lederstrumpf/substrate-c-tool
|
999bc55ffa2f354b96c347ebb122c79baad812cc
|
[
"MIT"
] | null | null | null |
tests/fuzz/fuzzScale.cpp
|
Lederstrumpf/substrate-c-tool
|
999bc55ffa2f354b96c347ebb122c79baad812cc
|
[
"MIT"
] | 3
|
2020-05-10T23:01:22.000Z
|
2020-07-12T07:07:53.000Z
|
#include <string>
#include <iostream>
#include <exception>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstring>
extern "C" {
#include "../../src/scale.h"
}
int print_input(uint8_t *value, size_t value_len) {
std::stringstream s;
for (unsigned int i=0; i<value_len; i++) {
s << std::setfill('0') << std::setw(2) << std::right << std::hex << +value[i];
}
std::cerr << s.str() << std::endl;
std::cerr << "Length: " << value_len << std::endl;
return 0;
}
int main(int argc, char **argv){
std::string input;
ScaleElem encoded_value;
uint8_t decoded_value[SCALE_COMPACT_MAX] = {0};
size_t decoded_value_len, consumed, encoded_value_len;
std::ifstream f;
if (argc >= 2) {
f.open(argv[1]);
}
std::istream &in = (argc >= 2) ? f : std::cin;
std::getline(in, input);
// vector to char array
size_t value_len = input.size();
uint8_t value[value_len];
copy(input.begin(), input.end(), value);
std::cerr << "Input" << std::endl;
print_input(value, value_len);
// let's start the testing
if (value_len >= SCALE_COMPACT_MAX) // this case is not interesting
return 0;
if (value_len == 0) // also not interesting
return 0;
// 1) can encode
if ( encode_scale(&encoded_value, value, value_len, type_compact) > 0)
throw std::runtime_error(std::string("Failed SCALE encoding\n"));
// 2) decodes expected value
if ( decode_scale(&encoded_value, decoded_value, &decoded_value_len) > 0)
throw std::runtime_error(std::string("Failed SCALE decoding\n"));
// 3) encoded == decoded ?
print_scale(&encoded_value);
std::cerr << "Decoded" << std::endl;
print_input(decoded_value, decoded_value_len);
if (value_len >= decoded_value_len) {
if ( std::memcmp(value, decoded_value, value_len) != 0 )
throw std::runtime_error(std::string("Failed SCALE encoded != decoded (value_len >= decoded_value_len)\n"));
} else {
if ( std::memcmp(value, decoded_value, value_len) != 0 )
throw std::runtime_error(std::string("Failed SCALE encoded != decoded (value_len < decoded_value_len)\n"));
}
return 0;
}
| 27.435897
| 114
| 0.65514
|
Lederstrumpf
|
8df64280462de89c2f71cc33cd41d98d3de72d44
| 5,613
|
cpp
|
C++
|
camera_models/extrinsics.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 14
|
2018-03-26T13:43:58.000Z
|
2022-03-03T13:04:36.000Z
|
camera_models/extrinsics.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | null | null | null |
camera_models/extrinsics.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 1
|
2019-08-03T23:12:08.000Z
|
2019-08-03T23:12:08.000Z
|
//Illustration of extrinsic camera parameters
// Andreas Unterweger, 2017-2022
//This code is licensed under the 3-Clause BSD License. See LICENSE file for details.
#include <iostream>
#include <opencv2/viz.hpp>
#include "common.hpp"
#include "math.hpp"
#include "conf_viz.hpp"
static constexpr auto parameter_accuracy = 0.01;
static constexpr auto cone_length = 1.0;
static constexpr char axes[] = {'x', 'y', 'z'};
static auto initializing = true; //Prevents updating incomplete values during initialization
static void AddObjects(vizutils::ConfigurableVisualization &visualization, const char * const model_filename)
{
if (model_filename)
{
const auto mesh = cv::viz::Mesh::load(model_filename);
cv::viz::WMesh original_mesh(mesh);
visualization.objects.insert(std::make_pair("Original object", original_mesh));
}
else
{
constexpr auto cone_radius = 0.5;
constexpr auto cone_resolution = 100;
cv::viz::WCone original_cone(cone_length, cone_radius, cone_resolution);
visualization.objects.insert(std::make_pair("Original object", original_cone));
}
}
static cv::Affine3d RoundCameraPose(const cv::Affine3d &old_pose)
{
cv::Vec3d rotation(old_pose.rvec());
for (size_t i = 0; i < 3; i++)
rotation[i] = floor(rotation[i] / parameter_accuracy) * parameter_accuracy;
cv::Vec3d translation(old_pose.translation());
for (size_t i = 0; i < 3; i++)
translation[i] = floor(translation[i] / parameter_accuracy) * parameter_accuracy;
const cv::Affine3d pose(rotation, translation);
return pose;
}
static std::string GetRotationTrackbarName(const char axis)
{
using namespace std::string_literals;
const auto trackbar_name = "Rotation ("s + axis + ") [°]";
return trackbar_name;
}
static std::string GetTranslationTrackbarName(const char axis)
{
using namespace std::string_literals;
const auto trackbar_name = "Translation ("s + axis + ") [px]";
return trackbar_name;
}
static void UpdateCameraPose(vizutils::ConfigurableVisualization &visualization)
{
if (initializing) //Don't update during initialization
return;
double rotation_angles[comutils::arraysize(axes)], translation_offsets[comutils::arraysize(axes)];
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetRotationTrackbarName(axis);
const auto rotation_degrees = visualization.GetTrackbarValue(trackbar_name);
rotation_angles[i] = comutils::DegreesToRadians(rotation_degrees);
}
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetTranslationTrackbarName(axis);
const auto translation_unscaled = visualization.GetTrackbarValue(trackbar_name);
translation_offsets[i] = translation_unscaled * parameter_accuracy;
}
const cv::Vec3d rotation(rotation_angles);
const cv::Vec3d translation(translation_offsets);
const cv::Affine3d pose(rotation, translation);
const cv::Affine3d rounded_pose = RoundCameraPose(pose);
visualization.SetViewerPose(rounded_pose);
}
static void AddControls(vizutils::ConfigurableVisualization &visualization)
{
for (const auto &axis : axes)
{
const auto trackbar_name = GetRotationTrackbarName(axis);
visualization.AddTrackbar(trackbar_name, UpdateCameraPose, 360);
}
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetTranslationTrackbarName(axis);
const auto limit = i == comutils::arraysize(axes) - 1 ? 500: 50;
visualization.AddTrackbar(trackbar_name, UpdateCameraPose, limit, -limit);
}
}
static void InitializeControlValues(vizutils::ConfigurableVisualization &visualization, const cv::Affine3d &pose)
{
const auto rotation = pose.rvec();
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetRotationTrackbarName(axis);
const auto rotation_radians = comutils::RadiansToDegrees(rotation[i]);
visualization.UpdateTrackbarValue(trackbar_name, rotation_radians);
}
const auto translation = pose.translation();
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetTranslationTrackbarName(axis);
const auto translation_scaled = translation[i] / parameter_accuracy;
visualization.UpdateTrackbarValue(trackbar_name, translation_scaled);
}
initializing = false; //Done initializing
}
int main(const int argc, const char * const argv[])
{
if (argc > 2)
{
std::cout << "Illustrates the effect of the extrinsic parameters of a pinhole camera." << std::endl;
std::cout << "Usage: " << argv[0] << " [3-D model (PLY) file name]" << std::endl;
return 1;
}
const auto model_filename = (argc == 2) ? argv[1] : nullptr;
constexpr auto visualization_window_name = "Camera view";
constexpr auto control_window_name = "Extrinsic camera parameters";
vizutils::ConfigurableVisualization visualization(visualization_window_name, control_window_name);
AddObjects(visualization, model_filename);
AddControls(visualization);
visualization.ShowWindows([&visualization](const cv::Affine3d &pose)
{
const cv::Affine3d rounded_pose = RoundCameraPose(pose);
InitializeControlValues(visualization, rounded_pose);
return rounded_pose;
});
return 0;
}
| 37.42
| 113
| 0.70408
|
dustsigns
|
8df78a649fb600c58e0c2f641bc01ae01cd342e9
| 2,910
|
cpp
|
C++
|
src/System/Clock/PIT/PIT.cpp
|
corigan01/FluxedOS
|
7f854a4636b1a37004e6b3e616b5409c34653ad9
|
[
"MIT"
] | 20
|
2021-01-05T20:49:08.000Z
|
2022-03-31T08:20:16.000Z
|
src/System/Clock/PIT/PIT.cpp
|
corigan01/FluxedOS
|
7f854a4636b1a37004e6b3e616b5409c34653ad9
|
[
"MIT"
] | 4
|
2021-01-05T20:26:29.000Z
|
2022-01-29T07:10:37.000Z
|
src/System/Clock/PIT/PIT.cpp
|
corigan01/FluxedOS
|
7f854a4636b1a37004e6b3e616b5409c34653ad9
|
[
"MIT"
] | 4
|
2021-03-03T23:08:18.000Z
|
2021-12-31T18:07:05.000Z
|
/*
* ______ __ __ __
* / __/ /_ ____ __ / //_/__ _______ ___ / /
* / _// / // /\ \ / / ,< / -_) __/ _ \/ -_) /
* /_/ /_/\_,_//_\_\ /_/|_|\__/_/ /_//_/\__/_/
*
* copyright (c) 2021 Gavin Kellam (aka corigan01)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
#include "PIT.hpp"
#include "../../cpu/cpu.hpp"
#include "../../Port/port.hpp"
using namespace System;
using namespace System::IO;
using namespace System::CPU;
using namespace System::Clock;
i32 timer_ticks = 0;
i16 timer_phase = 18;
i32 timer_seconds = 0;
void PIT::init() {
IRQ::installIRQ(0, System::Clock::PIT::TimerHandler);
kout << "PIT INIT OK" << endl;
}
void PIT::TimerPhase(i16 hz) {
kout << "TimerPhase Reset to " << hz << " hz" << endl;
timer_phase = hz;
int divisor = 1193180 / hz; /* Calculate our divisor */
Port::byte_out(0x43, 0x36); /* Set our command byte 0x36 */
Port::byte_out(0x40, divisor & 0xFF); /* Set low byte of divisor */
Port::byte_out(0x40, divisor >> 8); /* Set high byte of divisor */
}
void PIT::TimerHandler(register_t *r) {
timer_ticks++;
if (timer_ticks % timer_phase == 0) {
NO_INSTRUCTION;
timer_seconds++;
}
PIC::SendEOI(0);
}
void PIT::Sleep(i16 ms) {
i16 timerTicksNeeded = timer_ticks + (timer_phase * (ms / 1000));
i32 timerold = timer_ticks;
int i = 0;
while (i < 600) {
NO_INSTRUCTION;
if (timer_ticks == timerTicksNeeded) {
return;
}
else {
if (timer_ticks % timer_phase == 0 && timerold != timer_ticks) {
NO_INSTRUCTION;
i++;
timerold = timer_ticks;
}
}
}
kout << "Sleep Timed out!" << endl;
}
| 33.068182
| 205
| 0.605155
|
corigan01
|
8dfb81bb9778d34a666d306f1b59daf6d0d56b42
| 1,091
|
cpp
|
C++
|
http/tests/HttpServer-Test.cpp
|
Sun-CX/reactor
|
88d90a96ae8c018c902846437ef6068da2715aa2
|
[
"Apache-2.0"
] | 3
|
2020-08-11T06:47:16.000Z
|
2021-07-16T09:51:28.000Z
|
http/tests/HttpServer-Test.cpp
|
Sun-CX/reactor
|
88d90a96ae8c018c902846437ef6068da2715aa2
|
[
"Apache-2.0"
] | null | null | null |
http/tests/HttpServer-Test.cpp
|
Sun-CX/reactor
|
88d90a96ae8c018c902846437ef6068da2715aa2
|
[
"Apache-2.0"
] | 2
|
2020-08-10T07:38:29.000Z
|
2021-07-16T09:48:09.000Z
|
//
// Created by suncx on 2020/9/23.
//
#include "HttpServer.h"
#include "EventLoop.h"
#include "InetAddress.h"
#include "ConsoleStream.h"
using std::string;
using std::to_string;
using reactor::net::HttpRequest;
using reactor::net::HttpResponse;
using reactor::net::http::Headers;
using reactor::net::EventLoop;
using reactor::net::InetAddress;
using reactor::net::HttpServer;
void service(const HttpRequest &request, HttpResponse &response) {
const Headers &headers = request.get_headers();
for (const auto &e: headers) {
RC_DEBUG << e.first << ':' << e.second;
}
response.set_response_status(200, "OK");
response.set_header("Content-Type", "text/plain");
string body("hello reactor!");
response.set_body(body);
response.set_header("Content-Length", to_string(body.size()));
}
int main(int argc, const char *argv[]) {
EventLoop loop;
InetAddress addr("192.168.2.2", 8080);
HttpServer httpServer(&loop, addr, "http-svr", 3, true);
httpServer.set_http_callback(service);
httpServer.start();
loop.loop();
return 0;
}
| 25.372093
| 66
| 0.683776
|
Sun-CX
|
8dfe5e6135d1354defc4941c715298dddff7d00c
| 6,771
|
hpp
|
C++
|
core/src/impl/Morpheus_DynamicMatrix_Impl.hpp
|
morpheus-org/morpheus
|
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
|
[
"Apache-2.0"
] | 1
|
2021-12-18T01:18:49.000Z
|
2021-12-18T01:18:49.000Z
|
core/src/impl/Morpheus_DynamicMatrix_Impl.hpp
|
morpheus-org/morpheus
|
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
|
[
"Apache-2.0"
] | 5
|
2021-10-05T15:12:02.000Z
|
2022-01-21T23:26:41.000Z
|
core/src/impl/Morpheus_DynamicMatrix_Impl.hpp
|
morpheus-org/morpheus
|
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
|
[
"Apache-2.0"
] | null | null | null |
/**
* Morpheus_DynamicMatrix_Impl.hpp
*
* EPCC, The University of Edinburgh
*
* (c) 2021 - 2022 The University of Edinburgh
*
* Contributing Authors:
* Christodoulos Stylianou (c.stylianou@ed.ac.uk)
*
* 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 MORPHEUS_DYNAMICMATRIX_IMPL_HPP
#define MORPHEUS_DYNAMICMATRIX_IMPL_HPP
#include <string>
#include <Morpheus_Exceptions.hpp>
#include <Morpheus_FormatsRegistry.hpp>
#include <impl/Morpheus_ContainerTraits.hpp>
namespace Morpheus {
namespace Impl {
template <class ValueType, class... Properties>
struct any_type_resize
: public Impl::ContainerTraits<any_type_resize, ValueType, Properties...> {
using traits =
Impl::ContainerTraits<any_type_resize, ValueType, Properties...>;
using index_type = typename traits::index_type;
using value_type = typename traits::value_type;
using result_type = void;
// Specialization for Coo resize with three arguments
template <typename... Args>
result_type operator()(
typename CooMatrix<ValueType, Properties...>::type &mat,
const index_type nrows, const index_type ncols, const index_type nnnz) {
mat.resize(nrows, ncols, nnnz);
}
// Specialization for Csr resize with three arguments
template <typename... Args>
result_type operator()(
typename CsrMatrix<ValueType, Properties...>::type &mat,
const index_type nrows, const index_type ncols, const index_type nnnz) {
mat.resize(nrows, ncols, nnnz);
}
// Specialization for Dia resize with five arguments
template <typename... Args>
result_type operator()(
typename DiaMatrix<ValueType, Properties...>::type &mat,
const index_type nrows, const index_type ncols, const index_type nnnz,
const index_type ndiag, const index_type alignment = 32) {
mat.resize(nrows, ncols, nnnz, ndiag, alignment);
}
// Constrains any other overloads for supporting formats
// Unsupported formats won't compile
template <typename... Args>
result_type operator()(
typename CooMatrix<ValueType, Properties...>::type &mat, Args &&...args) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface for current format (" +
std::to_string(mat.format_index()) + ").");
}
template <typename... Args>
result_type operator()(
typename CsrMatrix<ValueType, Properties...>::type &mat, Args &&...args) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface for current format (" +
std::to_string(mat.format_index()) + ").");
}
template <typename... Args>
result_type operator()(
typename DiaMatrix<ValueType, Properties...>::type &mat, Args &&...args) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface for current format (" +
std::to_string(mat.format_index()) + ").");
}
};
struct any_type_resize_from_mat {
using result_type = void;
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
dst.resize(src);
}
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
!std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface. Src and dst tags must be "
"the same (" +
std::to_string(src.format_index()) +
" != " + std::to_string(dst.format_index()) + ")");
}
};
struct any_type_allocate {
using result_type = void;
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
dst = T2().allocate(src);
}
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
!std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic allocate interface. Src and std tags must "
"be the same (" +
std::to_string(src.format_index()) +
" != " + std::to_string(dst.format_index()) + ")");
}
};
struct any_type_assign {
using result_type = void;
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
dst = src;
}
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
!std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic assign interface. Src and dst tags must be "
"the same (" +
std::to_string(src.format_index()) +
" != " + std::to_string(dst.format_index()) + ")");
}
};
template <size_t I, class ValueType, typename... Properties>
struct activate_impl {
using variant = typename MatrixFormats<ValueType, Properties...>::variant;
using type_list = typename MatrixFormats<ValueType, Properties...>::type_list;
static void activate(variant &A, size_t idx) {
if (idx == I - 1) {
A = typename type_list::template type<I - 1>{};
} else {
activate_impl<I - 1, ValueType, Properties...>::activate(A, idx);
}
}
};
// Base case, activate to the first type in the variant
template <class ValueType, typename... Properties>
struct activate_impl<0, ValueType, Properties...> {
using variant = typename MatrixFormats<ValueType, Properties...>::variant;
using type_list = typename MatrixFormats<ValueType, Properties...>::type_list;
static void activate(variant &A, size_t idx) {
idx = 0;
activate_impl<1, ValueType, Properties...>::activate(A, idx);
}
};
} // namespace Impl
} // namespace Morpheus
#endif // MORPHEUS_DYNAMICMATRIX_IMPL_HPP
| 32.868932
| 80
| 0.66962
|
morpheus-org
|
5c03373b7984c0652faf5b7d28e4efd9d412a798
| 6,137
|
cpp
|
C++
|
GameClient/GameStateCommunicating.cpp
|
SamirAroudj/BaseProject
|
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
|
[
"BSD-3-Clause"
] | null | null | null |
GameClient/GameStateCommunicating.cpp
|
SamirAroudj/BaseProject
|
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
|
[
"BSD-3-Clause"
] | 1
|
2019-06-19T15:55:25.000Z
|
2019-06-27T07:47:27.000Z
|
GameClient/GameStateCommunicating.cpp
|
SamirAroudj/BaseProject
|
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
|
[
"BSD-3-Clause"
] | 1
|
2019-07-07T04:37:56.000Z
|
2019-07-07T04:37:56.000Z
|
/*
* Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#include <cstdio>
#include "Platform/ApplicationTimer.h"
#include "Client.h"
#include "ClientTimeManager.h"
#include "FontManager.h"
#include "GameStateCommunicating.h"
#include "GameStateConnecting.h"
#include "Platform/Input/InputManager.h"
#include "MagicGameConstants.h"
#include "MagicGraphicsConstants.h"
#include "Platform/ExceptionHandling/NetworkExceptionFactory.h"
#include "Session.h"
#include "Graphics/Texture.h"
using namespace ExceptionHandling;
using namespace GamePlay;
using namespace Graphics;
using namespace GUI;
using namespace Input;
using namespace Math;
using namespace ResourceManagement;
using namespace Network;
using namespace std;
GameStateCommunicating::GameStateCommunicating(GameState *&mPreviousState) :
mCamera(FOVY, Z_NEAR, Z_FAR), mDisconnectReason(L""),
mDirectionalLight(Color(0.8f, 0.8f, 0.8f, 1.0f), Color(0.8f, 0.8f, 0.8f, 1.0f), Color(0.3f, 0.3f, 0.8f, 1.0f), Vector3(0.0f, -1.0f, 0.0f))
{
delete mPreviousState;
mPreviousState = NULL;
mTank = new LocalTank(Session::getSingleton().getOwnIdentifier());
mFloor = new StaticObject("WoodCrate.mat", "Crate");
mBlock = new StaticObject("Color.mat", "Floor");
Session::getSingleton().addListener(this);
mCamera.setAsActiveCamera();
}
GameStateCommunicating::~GameStateCommunicating()
{
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
delete mRemoteTanks[i];
delete mBlock;
delete mFloor;
delete mTank;
assert(UserResource<StaticMesh>::getNumOfResources() == 0); // test whether everything was freed
assert(UserResource<VertexLayout>::getNumOfResources() == 0);
assert(UserResource<Shader>::getNumOfResources() == 0);
assert(UserResource<Texture>::getNumOfResources() == 0);
assert(UserResource<Material>::getNumOfResources() == 0);
}
void GameStateCommunicating::notifyNewMember(const SessionMember &newMember)
{
if (newMember.getIdentifier() == Session::getSingleton().getOwnIdentifier() || newMember.getIdentifier() == 0)
return;
RemoteTank *remoteTank = new RemoteTank(newMember.getIdentifier(), Vector2(0.0f, 0.0f));
mRemoteTanks.push_back(remoteTank);
mTank->requestUpdate();
}
void GameStateCommunicating::notifyRemovedMember(uint16 identifier)
{
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
{
if (identifier == mRemoteTanks[i]->getIdentifier())
{
delete mRemoteTanks[i];
mRemoteTanks[i] = mRemoteTanks.back();
mRemoteTanks.pop_back();
return;
}
}
}
void GameStateCommunicating::postRender()
{
}
void GameStateCommunicating::render()
{
wchar_t buffer[100];
const Matrix4x4 viewProjection(mCamera.getViewMatrix() * mCamera.getProjectionMatrix());
Matrix4x4 translation;
mFloor->render(translation * viewProjection, translation);
translation.addTranslation(2.0f, 0.0f, 2.0f);
mBlock->render(translation * viewProjection, translation);
translation.addTranslation(-3.0f, 0.0f, -3.0f);
mBlock->render(translation * viewProjection, translation);
translation.addTranslation(1.0f, -0.5f, 1.0f);
mTank->render(viewProjection);
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
mRemoteTanks[i]->render(viewProjection);
swprintf(buffer, 100, L"%u", static_cast<uint32>(0.5f + 1000.0f * ClientTimeManager::getSingleton().getNetworkTime()));
FontManager::getSingleton().getFont(0).renderText(L"Connection to the chosen server was established.", 50, 50, TEXT_COLOR);
FontManager::getSingleton().getFont(0).renderText(buffer, 50, 150, TEXT_COLOR);
}
GameState::State GameStateCommunicating::update(Real deltaTime)
{
Vector4 cameraPosition;
Vector4 tankPosition;
try
{
Client::getSingleton().update();
if (ClientState::READY_TO_USE == Client::getSingleton().getState())
{
processReceivedPackets();
mTank->update(deltaTime);
tankPosition.set(mTank->getXCoordinate(), 0.0f, mTank->getZCoordinate(), 1.0f);
cameraPosition.set(tankPosition.x + 2.0f, tankPosition.y + 20.0f, tankPosition.z + 2.0f, 1.0f);
mCamera.lookAtLH(cameraPosition, tankPosition, Vector3(0.0f, 1.0f, 0.0f));
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
mRemoteTanks[i]->update(deltaTime);
if (InputManager::getSingleton().getKeyboard().isKeyPressed(KEY_ESCAPE))
{
mDisconnectReason = L"User requested disconnect.";
Client::getSingleton().disconnect();
}
else
Client::getSingleton().send();
}
}
catch(ExceptionHandling::ClosedConnectionException &exception)
{
mDisconnectReason = L"Server shut down.";
}
switch(Client::getSingleton().getState())
{
case ClientState::DISCONNECTING:
return GameState::DISCONNECTING;
case ClientState::DISCONNECTED:
return GameState::DISCONNECTED;
case ClientState::READY_TO_USE:
break;
default:
assert(false);
}
return GameState::NO_STATE_CHANGE;
}
void GameStateCommunicating::processReceivedPackets()
{
uint16 senderIdentifier = 0;
MessageType message = Client::getSingleton().getCurrentUDPMessageIdentifier(senderIdentifier);
switch(message)
{
case UDPPacket::NO_MESSAGE:
return;
case TANK_UPDATE_MESSAGE:
{
Real latency = ClientTimeManager::getSingleton().getNetworkTime() - Client::getSingleton().getUDPMessageNetworkTime();
updateRemoteTank(latency);
return;
}
default:
assert(false);
}
}
void GameStateCommunicating::updateRemoteTank(Real latency)
{
Tank remoteUpdate(0);
Client::getSingleton().getUDPMessage(&remoteUpdate, 1);
if (remoteUpdate.getIdentifier() == Session::getSingleton().getOwnIdentifier())
return;
remoteUpdate.update(latency);
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
{
if (remoteUpdate.getIdentifier() == mRemoteTanks[i]->getIdentifier())
{
mRemoteTanks[i]->processRemoteUpdate(remoteUpdate);
return;
}
}
assert(false);
}
| 28.812207
| 139
| 0.744338
|
SamirAroudj
|
5c05f054d1f1047c5f44822fc367f254e5b5b3f0
| 2,020
|
cpp
|
C++
|
012. Integer to Roman.cpp
|
rajeev-ranjan-au6/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | 3
|
2020-12-30T00:29:59.000Z
|
2021-01-24T22:43:04.000Z
|
012. Integer to Roman.cpp
|
rajeevranjancom/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | null | null | null |
012. Integer to Roman.cpp
|
rajeevranjancom/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | null | null | null |
// Top-voted solution (https://discuss.leetcode.com/topic/12384/simple-solution).
class Solution {
public:
string intToRoman(int num) {
string M[] = {"", "M", "MM", "MMM"};
string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
};
// While my solution is...
class Solution {
public:
string intToRoman(int num) {
//'I' = 1, 'X' = 10, 'C' = 100, 'M' = 1000, 'V' = 5, 'L' = 50, 'D' = 500;
// Subtractive Notation
// Number 4 9 40 90 400 900
// Notation IV IX XL XC CD CM
string res = "";
while(num >= 1000){
num -= 1000;
res.push_back('M');
}
if(num >= 900){
num -= 900;
res.append("CM");
}
if(num >= 500){
num -= 500;
res.push_back('D');
}
if(num >= 400){
num -= 400;
res.append("CD");
}
while(num >= 100){
num -= 100;
res.push_back('C');
}
if(num >= 90){
num -= 90;
res.append("XC");
}
if(num >= 50){
num -= 50;
res.push_back('L');
}
if(num >= 40){
num -= 40;
res.append("XL");
}
while(num >= 10){
num -= 10;
res.push_back('X');
}
if(num >= 9){
num -= 9;
res.append("IX");
}
if(num >= 5){
num -= 5;
res.push_back('V');
}
if(num >= 4){
num -= 4;
res.append("IV");
}
while(num > 0){
num -= 1;
res.push_back('I');
}
return res;
}
};
| 26.233766
| 82
| 0.357921
|
rajeev-ranjan-au6
|
5c093c8085970f18b15ba463ae86b785f68bb36b
| 12,570
|
cc
|
C++
|
serving/processor/serving/model_config.cc
|
aalbersk/DeepRec
|
f673a950780959b44dcda99398880a1d883ab338
|
[
"Apache-2.0"
] | 292
|
2021-12-24T03:24:33.000Z
|
2022-03-31T15:41:05.000Z
|
serving/processor/serving/model_config.cc
|
aalbersk/DeepRec
|
f673a950780959b44dcda99398880a1d883ab338
|
[
"Apache-2.0"
] | 54
|
2021-12-24T06:40:09.000Z
|
2022-03-30T07:57:24.000Z
|
serving/processor/serving/model_config.cc
|
aalbersk/DeepRec
|
f673a950780959b44dcda99398880a1d883ab338
|
[
"Apache-2.0"
] | 75
|
2021-12-24T04:48:21.000Z
|
2022-03-29T10:13:39.000Z
|
#include <stdlib.h>
#include "serving/processor/serving/model_config.h"
#include "serving/processor/serving/tracer.h"
#include "include/json/json.h"
#include "tensorflow/core/util/env_var.h"
#include "tensorflow/core/lib/core/errors.h"
namespace tensorflow {
namespace processor {
namespace {
constexpr int DEFAULT_CPUS = 8;
Status AddOSSAccessPrefix(std::string& dir,
const ModelConfig* config) {
auto offset = dir.find("oss://");
// error oss format
if (offset == std::string::npos) {
return tensorflow::errors::Internal(
"Invalid user input oss dir, ", dir);
}
std::string tmp(dir.substr(6));
offset = tmp.find("/");
if (offset == std::string::npos) {
return tensorflow::errors::Internal(
"Invalid user input oss dir, ", dir);
}
dir = strings::StrCat(dir.substr(0, offset+6),
"\x01id=", config->oss_access_id,
"\x02key=", config->oss_access_key,
"\x02host=", config->oss_endpoint,
tmp.substr(offset));
return Status::OK();
}
}
Status ModelConfigFactory::Create(const char* model_config, ModelConfig** config) {
if (strlen(model_config) <= 0) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Invalid ModelConfig json.");
}
Json::Reader reader;
Json::Value json_config;
if (!reader.parse(model_config, json_config)) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Parse ModelConfig json failed.");
}
int64 schedule_threads;
ReadInt64FromEnvVar("SCHEDULABLE_CPUS", DEFAULT_CPUS, &schedule_threads);
*config = new ModelConfig;
if (!json_config["session_num"].isNull()) {
(*config)->session_num =
json_config["session_num"].asInt();
} else {
(*config)->session_num = 1;
}
(*config)->select_session_policy = "MOD";
if (!json_config["select_session_policy"].isNull()) {
(*config)->select_session_policy =
json_config["select_session_policy"].asString();
}
if ((*config)->select_session_policy != "MOD" &&
(*config)->select_session_policy != "RR") {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] select_session_policy must be 'RR' or 'MOD'");
}
bool enable_inline_execute = false;
if (!json_config["enable_inline_execute"].isNull()) {
enable_inline_execute = json_config["enable_inline_execute"].asBool();
}
if (enable_inline_execute) {
if (setenv("RUN_ALL_KERNELS_INLINE", "1", 1) != 0) {
LOG(WARNING) << "Set RUN_ALL_KERNELS_INLINE env error: "
<< json_config["enable_inline_execute"].asBool();
}
}
if (!json_config["omp_num_threads"].isNull()) {
if (setenv("OMP_NUM_THREADS",
json_config["omp_num_threads"].asString().c_str(), 1) != 0) {
LOG(WARNING) << "Set OMP_NUM_THREADS env error: "
<< json_config["omp_num_threads"];
}
}
if (!json_config["kmp_blocktime"].isNull()) {
if (setenv("KMP_BLOCKTIME",
json_config["kmp_blocktime"].asString().c_str(), 1) != 0) {
LOG(WARNING) << "Set KMP_BLOCKTIME env error: "
<< json_config["kmp_blocktime"];
}
}
if (!json_config["inter_op_parallelism_threads"].isNull()) {
(*config)->inter_threads =
json_config["inter_op_parallelism_threads"].asInt();
} else {
(*config)->inter_threads = schedule_threads / 2;
}
if (!json_config["intra_op_parallelism_threads"].isNull()) {
(*config)->intra_threads =
json_config["intra_op_parallelism_threads"].asInt();
} else {
(*config)->intra_threads = schedule_threads / 2;
}
if (!json_config["init_timeout_minutes"].isNull()) {
(*config)->init_timeout_minutes =
json_config["init_timeout_minutes"].asInt();
} else {
(*config)->init_timeout_minutes = -1;
}
if (!json_config["signature_name"].isNull()) {
(*config)->signature_name =
json_config["signature_name"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No signature_name in ModelConfig.");
}
if ((*config)->signature_name.empty()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Signature_name shouldn't be empty string.");
}
if (!json_config["warmup_file_name"].isNull()) {
(*config)->warmup_file_name =
json_config["warmup_file_name"].asString();
} else {
(*config)->warmup_file_name = "";
}
if (!json_config["serialize_protocol"].isNull()) {
(*config)->serialize_protocol =
json_config["serialize_protocol"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No serialize_protocol in ModelConfig.");
}
if ((*config)->serialize_protocol.empty()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] serialize_protocol shouldn't be empty string.");
}
if (!json_config["checkpoint_dir"].isNull()) {
(*config)->checkpoint_dir =
json_config["checkpoint_dir"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No checkpoint_dir in ModelConfig.");
}
if (!json_config["savedmodel_dir"].isNull()) {
(*config)->savedmodel_dir =
json_config["savedmodel_dir"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No savedmodel_dir in ModelConfig.");
}
if (!json_config["feature_store_type"].isNull()) {
(*config)->feature_store_type =
json_config["feature_store_type"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No feature_store_type in ModelConfig.");
}
if ((*config)->feature_store_type.empty()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] feature_store_type shouldn't be empty string.");
}
// @feature_store_type:
// 'redis/cluster_redis' or 'local'
if ((*config)->feature_store_type == "cluster_redis" ||
(*config)->feature_store_type == "redis") {
if (!json_config["redis_url"].isNull()) {
(*config)->redis_url =
json_config["redis_url"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] Should set redis_url in ModelConfig \
when feature_store_type=cluster_redis.");
}
if (!json_config["redis_password"].isNull()) {
(*config)->redis_password =
json_config["redis_password"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] Should set redis_password in ModelConfig \
when feature_store_type=cluster_redis.");
}
if (!json_config["read_thread_num"].isNull()) {
(*config)->read_thread_num =
json_config["read_thread_num"].asInt();
} else {
(*config)->read_thread_num = 4;
}
if (!json_config["update_thread_num"].isNull()) {
(*config)->update_thread_num =
json_config["update_thread_num"].asInt();
} else {
(*config)->update_thread_num = 2;
}
}
if (!json_config["model_store_type"].isNull()) {
(*config)->model_store_type =
json_config["model_store_type"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No model_store_type in ModelConfig.");
}
if ((*config)->model_store_type != "local") {
if ((*config)->checkpoint_dir.find((*config)->model_store_type)
== std::string::npos) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Mismatch model_store_type and checkpoint_dir.");
}
if ((*config)->savedmodel_dir.find((*config)->model_store_type)
== std::string::npos) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Mismatch model_store_type and savedmodel_dir.");
}
}
if ((*config)->model_store_type == "oss") {
if (!json_config["oss_endpoint"].isNull()) {
(*config)->oss_endpoint =
json_config["oss_endpoint"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No oss_endpoint in ModelConfig.");
}
if ((*config)->oss_endpoint.empty()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] oss_endpoint shouldn't be empty string.");
}
if (!json_config["oss_access_id"].isNull()) {
(*config)->oss_access_id =
json_config["oss_access_id"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No oss_access_id in ModelConfig.");
}
if ((*config)->oss_access_id.empty()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] oss_access_id shouldn't be empty string.");
}
if (!json_config["oss_access_key"].isNull()) {
(*config)->oss_access_key =
json_config["oss_access_key"].asString();
} else {
return Status(error::Code::NOT_FOUND,
"[TensorFlow] No oss_access_key in ModelConfig.");
}
if ((*config)->oss_access_key.empty()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] oss_access_key shouldn't be empty string.");
}
TF_RETURN_IF_ERROR(AddOSSAccessPrefix(
(*config)->savedmodel_dir, *config));
TF_RETURN_IF_ERROR(AddOSSAccessPrefix(
(*config)->checkpoint_dir, *config));
}
// timeout of distribute lock
if (!json_config["lock_timeout"].isNull()) {
(*config)->lock_timeout =
json_config["lock_timeout"].asInt();
} else {
(*config)->lock_timeout = 15 * 60; // 900 seconds
}
(*config)->use_per_session_threads = false;
if (!json_config["use_per_session_threads"].isNull()) {
(*config)->use_per_session_threads =
json_config["use_per_session_threads"].asBool();
}
(*config)->shard_embedding = false;
bool shard_embedding = false;
if (!json_config["shard_embedding"].isNull()) {
shard_embedding = json_config["shard_embedding"].asBool();
}
if (shard_embedding) {
if ((*config)->feature_store_type != "local") {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Sharded embedding must be load in local,"
"this require feature_store_type must be 'local' mode.");
}
(*config)->shard_embedding = true;
if (json_config["embedding_names"].isNull() ||
json_config["shard_instance_count"].isNull() ||
json_config["id_type"].isNull()) {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Shard embedding require args: embedding_names, "
"shard_instance_count and id_type.");
}
std::string embedding_names = json_config["embedding_names"].asString();
(*config)->shard_instance_count = json_config["shard_instance_count"].asInt();
// "string" or "int64"
(*config)->id_type = json_config["id_type"].asString();
// "name1;name2;name3"
auto idx = embedding_names.find(";");
while (idx != std::string::npos) {
(*config)->shard_embedding_names.push_back(embedding_names.substr(0, idx));
embedding_names = embedding_names.substr(idx+1);
idx = embedding_names.find(";");
}
(*config)->shard_embedding_names.push_back(embedding_names);
}
// enable trace timeline
if (!json_config["timeline_start_step"].isNull() &&
!json_config["timeline_interval_step"].isNull() &&
!json_config["timeline_trace_count"].isNull() &&
!json_config["timeline_path"].isNull()) {
auto path = json_config["timeline_path"].asString();
auto start_step = json_config["timeline_start_step"].asInt();
auto interval_step = json_config["timeline_interval_step"].asInt();
auto trace_count = json_config["timeline_trace_count"].asInt();
// save timeline to local
if (path[0] == '/') {
Tracer::GetTracer()->SetParams(start_step, interval_step, trace_count, path);
} else if (path.find("oss://") != std::string::npos) {
// save timeline to oss
if ((*config)->oss_endpoint == "" ||
(*config)->oss_access_id == "" ||
(*config)->oss_access_key == "") {
return Status(error::Code::INVALID_ARGUMENT,
"Timeline require oss_endpoint, oss_access_id, and oss_access_key.");
}
Tracer::GetTracer()->SetParams(start_step,
interval_step, trace_count, (*config)->oss_endpoint,
(*config)->oss_access_id, (*config)->oss_access_key, path);
} else {
return Status(error::Code::INVALID_ARGUMENT,
"[TensorFlow] Only support save timeline to local or oss now.");
}
}
return Status::OK();
}
} // processor
} // tensorflow
| 33.430851
| 83
| 0.638186
|
aalbersk
|
5c0bcc63b1882c769eadd024b77e906337024e57
| 437
|
hpp
|
C++
|
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
|
crdrisko/nd-grad
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | 1
|
2020-09-26T12:38:55.000Z
|
2020-09-26T12:38:55.000Z
|
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
|
crdrisko/nd-research
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | null | null | null |
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
|
crdrisko/nd-research
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved.
// See the LICENSE file in the project root for more information.
//
// Name: byref.hpp
// Author: crdrisko
// Date: 08/13/2020-12:12:50
// Description: Missing file from book
#ifndef BYREF_HPP
#define BYREF_HPP
template<typename T>
T const& checked(T const& a, T const& b)
{
return test() ? a : b;
}
#endif
| 23
| 121
| 0.709382
|
crdrisko
|
5c0d9b4f004dcd5e404e8024d67e964b9bfb5d83
| 8,061
|
cc
|
C++
|
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
|
billionshang/gem5
|
18cc4294f32315595f865d07d1f33434e92b06b2
|
[
"BSD-3-Clause"
] | null | null | null |
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
|
billionshang/gem5
|
18cc4294f32315595f865d07d1f33434e92b06b2
|
[
"BSD-3-Clause"
] | null | null | null |
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
|
billionshang/gem5
|
18cc4294f32315595f865d07d1f33434e92b06b2
|
[
"BSD-3-Clause"
] | null | null | null |
#include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_enum_TimingExprOp[] = {
120,156,197,88,239,114,211,214,18,223,35,201,78,236,56,196,
36,144,240,39,128,129,2,190,92,18,67,248,219,194,48,165,
109,218,161,211,134,123,37,58,80,181,115,85,199,58,177,21,
108,201,149,142,67,220,73,190,52,157,182,47,208,71,232,135,
62,64,223,227,190,209,237,238,202,114,36,59,164,124,184,19,
50,241,201,209,239,236,217,179,187,231,183,171,117,26,48,248,
201,225,231,195,10,64,244,167,6,224,226,175,128,54,64,71,
128,45,64,72,1,110,25,94,229,32,188,3,110,14,126,2,
176,53,144,26,236,225,68,135,111,52,240,75,188,39,15,109,
157,17,1,253,34,72,3,236,28,188,240,143,131,33,243,240,
170,8,225,119,32,132,240,5,188,116,39,192,157,132,159,80,
59,78,10,172,112,18,8,44,50,88,0,119,138,193,34,184,
37,158,76,65,191,12,178,4,246,52,137,217,199,80,237,117,
84,59,195,106,255,75,106,93,92,57,14,238,49,18,71,187,
190,38,73,131,36,249,188,25,214,130,42,116,216,60,78,227,
30,185,133,15,179,96,207,50,58,151,70,79,128,125,130,209,
147,105,116,30,236,121,70,23,210,232,41,176,79,49,122,58,
141,158,1,251,12,163,103,211,232,34,216,139,140,158,75,163,
231,193,62,207,232,133,52,90,1,187,194,232,197,52,122,9,
236,75,140,94,78,163,239,129,253,30,163,87,210,232,85,176,
175,50,122,45,141,86,193,174,50,250,143,52,122,29,236,235,
140,254,51,141,222,0,251,6,163,75,105,116,25,236,101,70,
107,105,244,38,216,55,25,189,149,70,87,192,94,97,244,118,
26,189,3,246,29,70,239,166,209,123,96,223,99,244,126,26,
125,0,246,3,70,223,79,163,31,128,253,1,163,15,193,126,
72,204,179,170,179,72,97,239,127,248,83,21,56,83,37,28,
182,100,24,121,129,239,120,254,70,224,105,180,158,167,129,8,
223,160,97,98,192,252,143,137,249,127,0,211,222,213,6,204,
223,5,16,244,12,208,214,96,151,39,187,26,244,171,176,35,
96,211,0,87,135,29,60,38,71,38,53,5,236,105,240,173,
78,2,187,56,26,200,207,243,96,168,152,246,155,204,207,88,
211,4,236,230,96,39,7,214,203,29,141,128,87,5,8,127,
135,31,22,89,233,36,43,213,96,7,71,3,246,12,216,205,
195,11,20,66,104,179,64,172,22,47,119,208,83,68,172,170,
129,214,174,165,220,37,87,92,47,244,235,29,169,40,18,142,
244,123,29,231,185,215,241,252,230,234,118,55,124,214,173,22,
19,185,32,90,238,214,85,203,228,141,58,69,164,211,85,172,
48,240,165,154,194,201,134,231,187,78,39,112,123,109,169,38,
73,155,179,225,181,165,227,240,226,211,78,55,8,213,106,24,
6,161,73,65,101,176,29,212,135,59,40,164,141,118,16,201,
42,157,198,199,152,164,94,145,244,70,151,53,146,1,108,44,
109,118,101,212,8,189,174,194,187,138,53,146,52,105,171,210,
45,241,16,213,113,168,117,124,85,107,53,55,162,154,213,170,
135,210,106,73,191,214,148,157,187,75,65,232,53,61,127,41,
82,245,245,182,92,90,185,121,235,238,210,251,75,183,107,235,
61,175,237,214,182,31,220,171,117,251,170,21,248,181,206,221,
154,231,43,137,97,106,215,198,2,180,140,66,20,186,232,181,
215,116,60,118,210,105,201,118,87,134,211,132,158,33,51,68,
89,148,68,94,232,162,42,166,113,150,195,143,46,22,181,41,
177,230,145,155,13,114,157,56,102,164,89,69,87,45,224,149,
6,225,34,113,102,19,127,5,93,50,50,199,162,53,141,215,
254,77,241,137,209,77,157,152,16,131,59,204,51,36,28,74,
62,162,171,247,129,201,146,131,205,60,196,36,66,238,197,172,
10,251,52,162,56,169,209,80,185,1,209,111,128,241,70,250,
236,192,128,90,123,58,8,191,12,170,72,5,18,209,121,60,
240,71,102,167,85,37,243,215,152,35,170,229,69,193,107,159,
111,130,230,156,79,22,70,230,95,253,103,235,155,178,161,162,
11,8,124,29,244,42,141,186,239,7,170,82,119,221,74,93,
169,208,91,239,41,25,85,84,80,185,18,85,233,114,205,227,
9,205,134,250,250,221,132,86,68,1,164,85,252,224,122,13,
133,15,115,252,192,183,16,73,133,20,105,5,110,132,56,169,
104,74,101,146,145,138,130,28,176,33,204,32,135,68,233,120,
148,59,134,207,79,18,75,152,166,213,124,66,170,72,182,55,
84,145,249,89,143,34,135,45,33,156,169,72,138,183,234,237,
158,100,237,72,38,133,6,209,52,182,225,200,201,120,138,28,
75,226,192,206,249,129,239,246,209,86,175,113,141,204,56,197,
148,44,49,41,79,34,33,39,112,204,227,223,188,152,215,26,
198,128,134,249,132,138,243,20,4,96,34,136,1,23,144,150,
123,88,140,170,26,87,19,246,143,179,245,18,205,104,179,185,
72,195,57,26,206,211,112,33,9,193,81,198,97,122,52,14,
247,233,108,141,157,103,55,233,226,244,196,77,55,147,113,167,
247,51,14,11,168,69,153,163,81,126,237,103,142,65,197,54,
124,76,35,138,114,78,234,16,61,167,210,78,25,198,202,40,
153,48,45,104,182,159,44,28,52,179,76,193,152,76,120,110,
18,121,211,12,110,166,24,108,210,125,49,125,205,211,73,221,
116,72,34,38,174,121,150,84,229,14,136,122,133,134,139,239,
34,244,251,20,108,142,81,240,33,153,81,30,80,112,154,169,
87,196,79,89,107,232,131,251,24,190,91,231,70,168,71,188,
51,14,224,221,85,154,233,227,17,120,135,148,27,248,253,105,
138,114,100,170,150,118,111,13,39,253,5,242,42,77,182,5,
108,26,94,248,11,216,7,104,220,7,220,228,62,128,123,9,
110,74,227,194,174,115,109,143,39,57,10,207,134,14,243,131,
247,123,84,192,177,27,6,219,253,74,176,81,81,236,63,213,
225,71,87,162,229,43,209,67,172,176,149,199,92,219,226,26,
27,87,209,80,118,169,10,210,214,213,237,134,228,183,42,63,
57,78,92,244,28,46,128,206,224,109,141,188,59,73,193,213,
146,168,115,249,143,84,72,85,255,200,227,94,28,198,157,220,
248,156,14,46,114,208,117,177,128,28,43,10,182,206,137,43,
63,247,112,188,138,159,143,232,34,40,2,18,232,75,139,105,
197,182,179,91,228,160,121,35,195,163,35,116,202,172,225,41,
95,37,252,201,239,243,135,62,122,146,30,191,96,107,36,136,
66,63,3,49,4,137,48,72,143,97,54,17,37,230,72,252,
63,192,121,116,64,79,193,245,201,162,62,130,37,176,108,69,
247,89,52,110,49,62,135,95,83,73,152,52,2,250,160,151,
77,55,2,198,176,182,49,181,222,234,101,111,100,139,32,93,
84,171,30,145,88,92,217,246,243,122,255,85,50,108,65,177,
178,31,37,207,38,227,35,29,178,238,219,125,150,209,171,244,
172,152,211,82,220,185,69,195,202,144,54,34,193,142,200,208,
11,240,230,30,192,137,223,44,223,144,53,6,219,63,51,193,
81,30,249,174,19,91,254,104,24,234,126,100,18,98,206,208,
160,37,149,3,235,12,182,186,170,207,253,83,124,228,16,162,
242,177,134,45,82,220,244,83,119,96,94,134,65,189,54,169,
21,49,151,97,240,86,99,182,199,245,198,151,175,185,226,240,
245,155,183,9,167,38,90,13,93,124,226,186,124,80,35,240,
49,82,190,226,178,155,89,30,217,96,245,214,15,219,128,203,
234,108,6,249,234,203,94,59,187,227,216,216,250,232,150,79,
188,173,67,183,224,250,200,22,235,111,78,177,198,79,177,254,
230,20,90,231,203,79,29,252,177,244,218,99,219,102,15,148,
81,139,25,120,245,251,94,125,196,194,153,113,129,145,243,214,
2,117,192,190,217,3,101,84,37,107,198,23,50,138,158,183,
234,126,118,239,220,193,66,234,114,22,255,44,148,117,204,137,
241,253,243,111,148,27,57,223,122,155,243,173,55,156,111,189,
229,249,105,57,117,46,179,244,212,223,194,188,201,110,46,31,
32,49,66,111,140,230,97,244,198,229,209,4,242,15,79,32,
223,85,167,51,200,179,48,43,95,26,89,85,23,179,46,122,
63,200,167,254,71,158,138,178,219,78,188,65,74,93,27,89,
104,250,171,219,74,250,238,237,149,231,193,189,59,89,37,103,
14,149,29,245,116,61,58,212,211,245,136,175,96,109,164,132,
142,95,193,168,4,127,253,107,108,213,195,119,210,27,112,229,
125,20,119,98,143,233,251,64,244,35,14,244,125,174,48,83,
16,121,141,254,189,160,99,219,51,45,12,189,84,46,24,165,
169,130,81,152,208,185,213,158,198,23,85,209,40,148,166,69,
65,251,127,127,254,2,56,224,64,222,
};
EmbeddedPython embedded_m5_internal_enum_TimingExprOp(
"m5/internal/enum_TimingExprOp.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/build/x86/python/m5/internal/enum_TimingExprOp.py",
"m5.internal.enum_TimingExprOp",
data_m5_internal_enum_TimingExprOp,
1962,
5657);
} // anonymous namespace
| 57.578571
| 104
| 0.667907
|
billionshang
|
5c0e580eaed59257243f065ff4702d3e069c0041
| 246
|
cpp
|
C++
|
cpp/hello.cpp
|
voltrevo/project-euler
|
0db5451f72b1353b295e56f928c968801e054444
|
[
"MIT"
] | null | null | null |
cpp/hello.cpp
|
voltrevo/project-euler
|
0db5451f72b1353b295e56f928c968801e054444
|
[
"MIT"
] | null | null | null |
cpp/hello.cpp
|
voltrevo/project-euler
|
0db5451f72b1353b295e56f928c968801e054444
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i != 6; ++i)
cout << "Hello "[i] << ' ';
for (int i = 0; i != 6; ++i)
cout << *("World!" + i) << ' ';
cout << endl;
return 0;
}
| 15.375
| 39
| 0.390244
|
voltrevo
|
5c0f58021247e45903b7b462b8c643e455f8a267
| 75,637
|
cpp
|
C++
|
src/interpreter/Interpreter.cpp
|
continue-nature/yvm
|
6416cc5e60a76f64c4272e0dff909507f140b11e
|
[
"MIT"
] | 110
|
2019-04-10T08:57:54.000Z
|
2022-03-13T03:37:20.000Z
|
src/interpreter/Interpreter.cpp
|
racaljk/ssvm
|
dfa6fa64fbe8682f77430246dff7f5c2ed9c4e41
|
[
"MIT"
] | 4
|
2019-04-23T03:03:45.000Z
|
2021-12-31T09:55:53.000Z
|
src/interpreter/Interpreter.cpp
|
racaljk/ssvm
|
dfa6fa64fbe8682f77430246dff7f5c2ed9c4e41
|
[
"MIT"
] | 31
|
2019-05-05T01:21:44.000Z
|
2022-03-16T15:25:24.000Z
|
#include "../classfile/AccessFlag.h"
#include "../classfile/ClassFile.h"
#include "../misc/Debug.h"
#include "../misc/Option.h"
#include "../runtime/JavaClass.h"
#include "../runtime/JavaHeap.hpp"
#include "CallSite.h"
#include "Interpreter.hpp"
#include "MethodResolve.h"
#include "SymbolicRef.h"
#include <cassert>
#include <cmath>
#include <functional>
#include <iostream>
using namespace std;
#define IS_COMPUTATIONAL_TYPE_1(value) \
(typeid(*value) != typeid(JDouble) && typeid(*value) != typeid(JLong))
#define IS_COMPUTATIONAL_TYPE_2(value) \
(typeid(*value) == typeid(JDouble) || typeid(*value) == typeid(JLong))
#pragma warning(disable : 4715)
#pragma warning(disable : 4244)
Interpreter::~Interpreter() { delete frames; }
JType *Interpreter::execNativeMethod(const string &className,
const string &methodName,
const string &methodDescriptor) {
string nativeMethod(className);
nativeMethod.append(".");
nativeMethod.append(methodName);
nativeMethod.append(".");
nativeMethod.append(methodDescriptor);
if (yrt.nativeMethods.find(nativeMethod) != yrt.nativeMethods.end()) {
return ((*yrt.nativeMethods.find(nativeMethod)).second)(
&yrt, frames->top()->localSlots, frames->top()->maxLocal);
}
GC_SAFE_POINT
if (yrt.gc->shallGC()) {
yrt.gc->stopTheWorld();
yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP);
}
return nullptr;
}
JType *Interpreter::execByteCode(const JavaClass *jc, u1 *code, u4 codeLength,
u2 exceptLen, ExceptionTable *exceptTab) {
for (decltype(codeLength) op = 0; op < codeLength; op++) {
// If callee propagates a unhandled exception, try to handle it. When
// we can not handle it, propagates it to upper and returns
if (exception.hasUnhandledException()) {
op--;
auto *throwobj = frames->top()->pop<JObject>();
if (throwobj == nullptr) {
throw runtime_error("null pointer");
}
if (!hasInheritanceRelationship(
throwobj->jc,
yrt.ma->loadClassIfAbsent("java/lang/Throwable"))) {
throw runtime_error("it's not a throwable object");
}
if (handleException(jc, exceptLen, exceptTab, throwobj, op)) {
while (!frames->top()->emptyStack()) {
frames->top()->pop<JType>();
}
frames->top()->push(throwobj);
exception.sweepException();
} else {
return throwobj;
}
}
#ifdef YVM_DEBUG_SHOW_BYTECODE
for (int i = 0; i < frames.size(); i++) {
cout << "-";
}
Inspector::printOpcode(code, op);
#endif
// Interpreting through big switching
switch (code[op]) {
case op_nop: {
// DO NOTHING :-)
} break;
case op_aconst_null: {
frames->top()->push(nullptr);
} break;
case op_iconst_m1: {
frames->top()->push(new JInt(-1));
} break;
case op_iconst_0: {
frames->top()->push(new JInt(0));
} break;
case op_iconst_1: {
frames->top()->push(new JInt(1));
} break;
case op_iconst_2: {
frames->top()->push(new JInt(2));
} break;
case op_iconst_3: {
frames->top()->push(new JInt(3));
} break;
case op_iconst_4: {
frames->top()->push(new JInt(4));
} break;
case op_iconst_5: {
frames->top()->push(new JInt(5));
} break;
case op_lconst_0: {
frames->top()->push(new JLong(0));
} break;
case op_lconst_1: {
frames->top()->push(new JLong(1));
} break;
case op_fconst_0: {
frames->top()->push(new JFloat(0.0f));
} break;
case op_fconst_1: {
frames->top()->push(new JFloat(1.0f));
} break;
case op_fconst_2: {
frames->top()->push(new JFloat(2.0f));
} break;
case op_dconst_0: {
frames->top()->push(new JDouble(0.0));
} break;
case op_dconst_1: {
frames->top()->push(new JDouble(1.0));
} break;
case op_bipush: {
const u1 byte = consumeU1(code, op);
frames->top()->push(new JInt(byte));
} break;
case op_sipush: {
const u2 byte = consumeU2(code, op);
frames->top()->push(new JInt(byte));
} break;
case op_ldc: {
const u1 index = consumeU1(code, op);
loadConstantPoolItem2Stack(jc, static_cast<u2>(index));
} break;
case op_ldc_w: {
const u2 index = consumeU2(code, op);
loadConstantPoolItem2Stack(jc, index);
} break;
case op_ldc2_w: {
const u2 index = consumeU2(code, op);
if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Double)) {
auto val = dynamic_cast<CONSTANT_Double *>(
jc->raw.constPoolInfo[index])
->val;
JDouble *dval = new JDouble;
dval->val = val;
frames->top()->push(dval);
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Long)) {
auto val = dynamic_cast<CONSTANT_Long *>(
jc->raw.constPoolInfo[index])
->val;
JLong *lval = new JLong;
lval->val = val;
frames->top()->push(lval);
} else {
throw runtime_error(
"invalid symbolic reference index on "
"constant pool");
}
} break;
case op_iload: {
const u1 index = consumeU1(code, op);
frames->top()->load<JInt>(index);
} break;
case op_lload: {
const u1 index = consumeU1(code, op);
frames->top()->load<JLong>(index);
} break;
case op_fload: {
const u1 index = consumeU1(code, op);
frames->top()->load<JFloat>(index);
} break;
case op_dload: {
const u1 index = consumeU1(code, op);
frames->top()->load<JDouble>(index);
} break;
case op_aload: {
const u1 index = consumeU1(code, op);
frames->top()->load<JRef>(index);
} break;
case op_iload_0: {
frames->top()->load<JInt>(0);
} break;
case op_iload_1: {
frames->top()->load<JInt>(1);
} break;
case op_iload_2: {
frames->top()->load<JInt>(2);
} break;
case op_iload_3: {
frames->top()->load<JInt>(3);
} break;
case op_lload_0: {
frames->top()->load<JLong>(0);
} break;
case op_lload_1: {
frames->top()->load<JLong>(1);
} break;
case op_lload_2: {
frames->top()->load<JLong>(2);
} break;
case op_lload_3: {
frames->top()->load<JLong>(3);
} break;
case op_fload_0: {
frames->top()->load<JFloat>(0);
} break;
case op_fload_1: {
frames->top()->load<JFloat>(1);
} break;
case op_fload_2: {
frames->top()->load<JFloat>(2);
} break;
case op_fload_3: {
frames->top()->load<JFloat>(3);
} break;
case op_dload_0: {
frames->top()->load<JDouble>(0);
} break;
case op_dload_1: {
frames->top()->load<JDouble>(1);
} break;
case op_dload_2: {
frames->top()->load<JDouble>(2);
} break;
case op_dload_3: {
frames->top()->load<JDouble>(3);
} break;
case op_aload_0: {
frames->top()->load<JRef>(0);
} break;
case op_aload_1: {
frames->top()->load<JRef>(1);
} break;
case op_aload_2: {
frames->top()->load<JRef>(2);
} break;
case op_aload_3: {
frames->top()->load<JRef>(3);
} break;
case op_saload:
case op_caload:
case op_baload:
case op_iaload: {
auto *index = frames->top()->pop<JInt>();
const auto *arrref = frames->top()->pop<JArray>();
if (!arrref) {
throw runtime_error("nullpointerexception");
}
auto *elem = dynamic_cast<JInt *>(
yrt.jheap->getElement(*arrref, index->val));
frames->top()->push(elem);
} break;
case op_laload: {
auto *index = frames->top()->pop<JInt>();
const auto *arrref = frames->top()->pop<JArray>();
if (!arrref) {
throw runtime_error("nullpointerexception");
}
auto *elem = dynamic_cast<JLong *>(
yrt.jheap->getElement(*arrref, index->val));
frames->top()->push(elem);
} break;
case op_faload: {
auto *index = frames->top()->pop<JInt>();
const auto *arrref = frames->top()->pop<JArray>();
if (!arrref) {
throw runtime_error("nullpointerexception");
}
auto *elem = dynamic_cast<JFloat *>(
yrt.jheap->getElement(*arrref, index->val));
frames->top()->push(elem);
} break;
case op_daload: {
auto *index = frames->top()->pop<JInt>();
const auto *arrref = frames->top()->pop<JArray>();
if (!arrref) {
throw runtime_error("nullpointerexception");
}
auto *elem = dynamic_cast<JDouble *>(
yrt.jheap->getElement(*arrref, index->val));
frames->top()->push(elem);
} break;
case op_aaload: {
auto *index = frames->top()->pop<JInt>();
const auto *arrref = frames->top()->pop<JArray>();
if (!arrref) {
throw runtime_error("nullpointerexception");
}
auto *elem = dynamic_cast<JRef *>(
yrt.jheap->getElement(*arrref, index->val));
frames->top()->push(elem);
} break;
case op_istore: {
const u1 index = consumeU1(code, op);
frames->top()->store<JInt>(index);
} break;
case op_lstore: {
const u1 index = consumeU1(code, op);
frames->top()->store<JLong>(index);
} break;
case op_fstore: {
const u1 index = consumeU1(code, op);
frames->top()->store<JFloat>(index);
} break;
case op_dstore: {
const u1 index = consumeU1(code, op);
frames->top()->store<JDouble>(index);
} break;
case op_astore: {
const u1 index = consumeU1(code, op);
frames->top()->store<JRef>(index);
} break;
case op_istore_0: {
frames->top()->store<JInt>(0);
} break;
case op_istore_1: {
frames->top()->store<JInt>(1);
} break;
case op_istore_2: {
frames->top()->store<JInt>(2);
} break;
case op_istore_3: {
frames->top()->store<JInt>(3);
} break;
case op_lstore_0: {
frames->top()->store<JLong>(0);
} break;
case op_lstore_1: {
frames->top()->store<JLong>(1);
} break;
case op_lstore_2: {
frames->top()->store<JLong>(2);
} break;
case op_lstore_3: {
frames->top()->store<JLong>(3);
} break;
case op_fstore_0: {
frames->top()->store<JFloat>(0);
} break;
case op_fstore_1: {
frames->top()->store<JFloat>(1);
} break;
case op_fstore_2: {
frames->top()->store<JFloat>(2);
} break;
case op_fstore_3: {
frames->top()->store<JFloat>(3);
} break;
case op_dstore_0: {
frames->top()->store<JDouble>(0);
} break;
case op_dstore_1: {
frames->top()->store<JDouble>(1);
} break;
case op_dstore_2: {
frames->top()->store<JDouble>(2);
} break;
case op_dstore_3: {
frames->top()->store<JDouble>(3);
} break;
case op_astore_0: {
frames->top()->store<JRef>(0);
} break;
case op_astore_1: {
frames->top()->store<JRef>(1);
} break;
case op_astore_2: {
frames->top()->store<JRef>(2);
} break;
case op_astore_3: {
frames->top()->store<JRef>(3);
} break;
case op_iastore: {
auto *value = frames->top()->pop<JInt>();
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_lastore: {
auto *value = frames->top()->pop<JLong>();
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_fastore: {
auto *value = frames->top()->pop<JFloat>();
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_dastore: {
auto *value = frames->top()->pop<JDouble>();
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_aastore: {
auto *value = frames->top()->pop<JType>();
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_bastore: {
auto *value = frames->top()->pop<JInt>();
value->val = static_cast<int8_t>(value->val);
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_sastore:
case op_castore: {
auto *value = frames->top()->pop<JInt>();
value->val = static_cast<int16_t>(value->val);
auto *index = frames->top()->pop<JInt>();
auto *arrref = frames->top()->pop<JArray>();
if (arrref == nullptr) {
throw runtime_error("null pointer");
}
if (index->val > arrref->length || index->val < 0) {
throw runtime_error("array index out of bounds");
}
yrt.jheap->putElement(*arrref, index->val, value);
} break;
case op_pop: {
frames->top()->pop<JType>();
} break;
case op_pop2: {
frames->top()->pop<JType>();
frames->top()->pop<JType>();
} break;
case op_dup: {
JType *value = frames->top()->pop<JType>();
assert(typeid(*value) != typeid(JLong) &&
typeid(*value) != typeid(JDouble));
frames->top()->push(value);
frames->top()->push(cloneValue(value));
} break;
case op_dup_x1: {
JType *value1 = frames->top()->pop<JType>();
JType *value2 = frames->top()->pop<JType>();
assert(IS_COMPUTATIONAL_TYPE_1(value1));
assert(IS_COMPUTATIONAL_TYPE_1(value2));
frames->top()->push(cloneValue(value1));
frames->top()->push(value2);
frames->top()->push(value1);
} break;
case op_dup_x2: {
JType *value1 = frames->top()->pop<JType>();
JType *value2 = frames->top()->pop<JType>();
JType *value3 = frames->top()->pop<JType>();
if (IS_COMPUTATIONAL_TYPE_1(value1) &&
IS_COMPUTATIONAL_TYPE_1(value2) &&
IS_COMPUTATIONAL_TYPE_1(value3)) {
// use structure 1
frames->top()->push(cloneValue(value1));
frames->top()->push(value3);
frames->top()->push(value2);
frames->top()->push(value1);
} else if (IS_COMPUTATIONAL_TYPE_1(value1) &&
IS_COMPUTATIONAL_TYPE_2(value2)) {
// use structure 2
frames->top()->push(value3);
frames->top()->push(cloneValue(value1));
frames->top()->push(value2);
frames->top()->push(value1);
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_dup2: {
JType *value1 = frames->top()->pop<JType>();
JType *value2 = frames->top()->pop<JType>();
if (IS_COMPUTATIONAL_TYPE_1(value1) &&
IS_COMPUTATIONAL_TYPE_1(value2)) {
// use structure 1
frames->top()->push(cloneValue(value2));
frames->top()->push(cloneValue(value1));
frames->top()->push(value2);
frames->top()->push(value1);
} else if (IS_COMPUTATIONAL_TYPE_2(value1)) {
// use structure 2
frames->top()->push(value2);
frames->top()->push(cloneValue(value1));
frames->top()->push(value1);
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_dup2_x1: {
JType *value1 = frames->top()->pop<JType>();
JType *value2 = frames->top()->pop<JType>();
JType *value3 = frames->top()->pop<JType>();
if (IS_COMPUTATIONAL_TYPE_1(value1) &&
IS_COMPUTATIONAL_TYPE_1(value2) &&
IS_COMPUTATIONAL_TYPE_1(value3)) {
// use structure 1
frames->top()->push(cloneValue(value2));
frames->top()->push(cloneValue(value1));
frames->top()->push(value3);
frames->top()->push(value2);
frames->top()->push(value1);
} else if (IS_COMPUTATIONAL_TYPE_2(value1) &&
IS_COMPUTATIONAL_TYPE_1(value2)) {
// use structure 2
frames->top()->push(value3);
frames->top()->push(cloneValue(value1));
frames->top()->push(value2);
frames->top()->push(value1);
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_dup2_x2: {
JType *value1 = frames->top()->pop<JType>();
JType *value2 = frames->top()->pop<JType>();
JType *value3 = frames->top()->pop<JType>();
JType *value4 = frames->top()->pop<JType>();
if (IS_COMPUTATIONAL_TYPE_1(value1) &&
IS_COMPUTATIONAL_TYPE_1(value2) &&
IS_COMPUTATIONAL_TYPE_1(value3) &&
IS_COMPUTATIONAL_TYPE_1(value4)) {
// use structure 1
frames->top()->push(cloneValue(value2));
frames->top()->push(cloneValue(value1));
frames->top()->push(value4);
frames->top()->push(value3);
frames->top()->push(value2);
frames->top()->push(value1);
} else if (IS_COMPUTATIONAL_TYPE_2(value1) &&
IS_COMPUTATIONAL_TYPE_1(value2) &&
IS_COMPUTATIONAL_TYPE_1(value3)) {
// use structure 2
frames->top()->push(value4);
frames->top()->push(cloneValue(value1));
frames->top()->push(value4);
frames->top()->push(value2);
frames->top()->push(value1);
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_swap: {
JType *value1 = frames->top()->pop<JType>();
JType *value2 = frames->top()->pop<JType>();
assert(IS_COMPUTATIONAL_TYPE_1(value1));
assert(IS_COMPUTATIONAL_TYPE_1(value2));
if (typeid(*value1) == typeid(JInt) &&
typeid(*value2) == typeid(JInt)) {
swap(value1, value2);
} else if (typeid(*value1) == typeid(JInt) &&
typeid(*value2) == typeid(JFloat)) {
const int32_t temp = dynamic_cast<JInt *>(value1)->val;
dynamic_cast<JInt *>(value1)->val = static_cast<int32_t>(
dynamic_cast<JFloat *>(value2)->val);
dynamic_cast<JFloat *>(value2)->val =
static_cast<float>(temp);
} else if (typeid(*value1) == typeid(JFloat) &&
typeid(*value2) == typeid(JInt)) {
const float temp = dynamic_cast<JFloat *>(value1)->val;
dynamic_cast<JFloat *>(value1)->val =
static_cast<int32_t>(dynamic_cast<JInt *>(value2)->val);
dynamic_cast<JInt *>(value2)->val =
static_cast<int32_t>(temp);
} else if (typeid(*value1) == typeid(JFloat) &&
typeid(*value2) == typeid(JFloat)) {
swap(value1, value2);
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_iadd: {
binaryArithmetic<JInt>(plus<>());
} break;
case op_ladd: {
binaryArithmetic<JLong>(plus<>());
} break;
case op_fadd: {
binaryArithmetic<JFloat>(plus<>());
} break;
case op_dadd: {
binaryArithmetic<JDouble>(plus<>());
} break;
case op_isub: {
binaryArithmetic<JInt>(minus<>());
} break;
case op_lsub: {
binaryArithmetic<JLong>(minus<>());
} break;
case op_fsub: {
binaryArithmetic<JFloat>(minus<>());
} break;
case op_dsub: {
binaryArithmetic<JDouble>(minus<>());
} break;
case op_imul: {
binaryArithmetic<JInt>(multiplies<>());
} break;
case op_lmul: {
binaryArithmetic<JLong>(multiplies<>());
} break;
case op_fmul: {
binaryArithmetic<JFloat>(multiplies<>());
} break;
case op_dmul: {
binaryArithmetic<JDouble>(multiplies<>());
} break;
case op_idiv: {
binaryArithmetic<JInt>(divides<>());
} break;
case op_ldiv: {
binaryArithmetic<JLong>(divides<>());
} break;
case op_fdiv: {
binaryArithmetic<JFloat>(divides<>());
} break;
case op_ddiv: {
binaryArithmetic<JDouble>(divides<>());
} break;
case op_irem: {
binaryArithmetic<JInt>(modulus<>());
} break;
case op_lrem: {
binaryArithmetic<JLong>(modulus<>());
} break;
case op_frem: {
binaryArithmetic<JFloat>(std::fmod<float, float>);
} break;
case op_drem: {
binaryArithmetic<JFloat>(std::fmod<double, double>);
} break;
case op_ineg: {
unaryArithmetic<JInt>(negate<>());
} break;
case op_lneg: {
unaryArithmetic<JLong>(negate<>());
} break;
case op_fneg: {
unaryArithmetic<JFloat>(negate<>());
} break;
case op_dneg: {
unaryArithmetic<JDouble>(negate<>());
} break;
case op_ishl: {
binaryArithmetic<JInt>([](int32_t a, int32_t b) -> int32_t {
return a * pow(2, b & 0x1f);
});
} break;
case op_lshl: {
binaryArithmetic<JLong>([](int64_t a, int64_t b) -> int64_t {
return a * pow(2, b & 0x3f);
});
} break;
case op_ishr: {
binaryArithmetic<JInt>([](int32_t a, int32_t b) -> int32_t {
return floor(a / pow(2, b & 0x1f));
});
} break;
case op_lshr: {
binaryArithmetic<JLong>([](int64_t a, int64_t b) -> int64_t {
return floor(a / pow(2, b & 0x3f));
});
} break;
case op_iushr: {
binaryArithmetic<JInt>([](int32_t a, int32_t b) -> int32_t {
if (a > 0) {
return a >> (b & 0x1f);
} else if (a < 0) {
return (a >> (b & 0x1f)) + (2 << ~(b & 0x1f));
} else {
throw runtime_error("0 is not handled");
}
});
} break;
case op_lushr: {
binaryArithmetic<JLong>([](int64_t a, int64_t b) -> int64_t {
if (a > 0) {
return a >> (b & 0x3f);
} else if (a < 0) {
return (a >> (b & 0x1f)) + (2L << ~(b & 0x3f));
} else {
throw runtime_error("0 is not handled");
}
});
} break;
case op_iand: {
binaryArithmetic<JInt>(bit_and<>());
} break;
case op_land: {
binaryArithmetic<JLong>(bit_and<>());
} break;
case op_ior: {
binaryArithmetic<JInt>(bit_or<>());
} break;
case op_lor: {
binaryArithmetic<JLong>(bit_or<>());
} break;
case op_ixor: {
binaryArithmetic<JInt>(bit_xor<>());
} break;
case op_lxor: {
binaryArithmetic<JLong>(bit_xor<>());
} break;
case op_iinc: {
const u1 index = code[++op];
const int8_t count = code[++op];
const int32_t extendedCount = count;
if (IS_JINT(frames->top()->getLocalVariable(index))) {
dynamic_cast<JInt *>(frames->top()->getLocalVariable(index))
->val += extendedCount;
} else if (IS_JLong(frames->top()->getLocalVariable(index))) {
dynamic_cast<JLong *>(
frames->top()->getLocalVariable(index))
->val += extendedCount;
} else if (IS_JFloat(frames->top()->getLocalVariable(index))) {
dynamic_cast<JFloat *>(
frames->top()->getLocalVariable(index))
->val += extendedCount;
} else if (IS_JDouble(frames->top()->getLocalVariable(index))) {
dynamic_cast<JDouble *>(
frames->top()->getLocalVariable(index))
->val += extendedCount;
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_i2l: {
typeCast<JInt, JLong>();
} break;
case op_i2f: {
typeCast<JInt, JFloat>();
} break;
case op_i2d: {
typeCast<JInt, JDouble>();
} break;
case op_l2i: {
typeCast<JLong, JInt>();
} break;
case op_l2f: {
typeCast<JLong, JFloat>();
} break;
case op_l2d: {
typeCast<JLong, JDouble>();
} break;
case op_f2i: {
typeCast<JFloat, JInt>();
} break;
case op_f2l: {
typeCast<JFloat, JLong>();
} break;
case op_f2d: {
typeCast<JFloat, JDouble>();
} break;
case op_d2i: {
typeCast<JDouble, JInt>();
} break;
case op_d2l: {
typeCast<JDouble, JLong>();
} break;
case op_d2f: {
typeCast<JDouble, JFloat>();
} break;
case op_i2c:
case op_i2b: {
auto *value = frames->top()->pop<JInt>();
auto *result = new JInt;
result->val = (int8_t)(value->val);
frames->top()->push(result);
} break;
case op_i2s: {
auto *value = frames->top()->pop<JInt>();
auto *result = new JInt;
result->val = (int16_t)(value->val);
frames->top()->push(result);
} break;
case op_lcmp: {
auto *value2 = frames->top()->pop<JLong>();
auto *value1 = frames->top()->pop<JLong>();
if (value1->val > value2->val) {
auto *result = new JInt(1);
frames->top()->push(result);
} else if (value1->val == value2->val) {
auto *result = new JInt(0);
frames->top()->push(result);
} else {
auto *result = new JInt(-1);
frames->top()->push(result);
}
} break;
case op_fcmpg:
case op_fcmpl: {
auto *value2 = frames->top()->pop<JFloat>();
auto *value1 = frames->top()->pop<JFloat>();
if (value1->val > value2->val) {
auto *result = new JInt(1);
frames->top()->push(result);
} else if (abs(value1->val - value2->val) < 0.000001) {
auto *result = new JInt(0);
frames->top()->push(result);
} else {
auto *result = new JInt(-1);
frames->top()->push(result);
}
} break;
case op_dcmpl:
case op_dcmpg: {
auto *value2 = frames->top()->pop<JDouble>();
auto *value1 = frames->top()->pop<JDouble>();
if (value1->val > value2->val) {
auto *result = new JInt(1);
frames->top()->push(result);
} else if (abs(value1->val - value2->val) < 0.000000000001) {
auto *result = new JInt(0);
frames->top()->push(result);
} else {
auto *result = new JInt(-1);
frames->top()->push(result);
}
} break;
case op_ifeq: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value = frames->top()->pop<JInt>();
if (value->val == 0) {
op = currentOffset + branchindex;
}
} break;
case op_ifne: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value = frames->top()->pop<JInt>();
if (value->val != 0) {
op = currentOffset + branchindex;
}
} break;
case op_iflt: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value = frames->top()->pop<JInt>();
if (value->val < 0) {
op = currentOffset + branchindex;
}
} break;
case op_ifge: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value = frames->top()->pop<JInt>();
if (value->val >= 0) {
op = currentOffset + branchindex;
}
} break;
case op_ifgt: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value = frames->top()->pop<JInt>();
if (value->val > 0) {
op = currentOffset + branchindex;
}
} break;
case op_ifle: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value = frames->top()->pop<JInt>();
if (value->val <= 0) {
op = currentOffset + branchindex;
}
} break;
case op_if_icmpeq: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JInt>();
auto *value1 = frames->top()->pop<JInt>();
if (value1->val == value2->val) {
op = currentOffset + branchindex;
}
} break;
case op_if_icmpne: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JInt>();
auto *value1 = frames->top()->pop<JInt>();
if (value1->val != value2->val) {
op = currentOffset + branchindex;
}
} break;
case op_if_icmplt: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JInt>();
auto *value1 = frames->top()->pop<JInt>();
if (value1->val < value2->val) {
op = currentOffset + branchindex;
}
} break;
case op_if_icmpge: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JInt>();
auto *value1 = frames->top()->pop<JInt>();
if (value1->val >= value2->val) {
op = currentOffset + branchindex;
}
} break;
case op_if_icmpgt: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JInt>();
auto *value1 = frames->top()->pop<JInt>();
if (value1->val > value2->val) {
op = currentOffset + branchindex;
}
} break;
case op_if_icmple: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JInt>();
auto *value1 = frames->top()->pop<JInt>();
if (value1->val <= value2->val) {
op = currentOffset + branchindex;
}
} break;
case op_if_acmpeq: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JObject>();
auto *value1 = frames->top()->pop<JObject>();
if (value1->offset == value2->offset &&
value1->jc == value2->jc) {
op = currentOffset + branchindex;
}
} break;
case op_if_acmpne: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
auto *value2 = frames->top()->pop<JObject>();
auto *value1 = frames->top()->pop<JObject>();
if (value1->offset != value2->offset ||
value1->jc != value2->jc) {
op = currentOffset + branchindex;
}
} break;
case op_goto: {
u4 currentOffset = op - 1;
int16_t branchindex = consumeU2(code, op);
op = currentOffset + branchindex;
} break;
case op_jsr: {
throw runtime_error("unsupported opcode [jsr]");
} break;
case op_ret: {
throw runtime_error("unsupported opcode [ret]");
} break;
case op_tableswitch: {
u4 currentOffset = op - 1;
op++;
op++;
op++; // 3 bytes padding
int32_t defaultIndex = consumeU4(code, op);
int32_t low = consumeU4(code, op);
int32_t high = consumeU4(code, op);
vector<int32_t> jumpOffset;
FOR_EACH(i, high - low + 1) {
jumpOffset.push_back(consumeU4(code, op));
}
auto *index = frames->top()->pop<JInt>();
if (index->val < low || index->val > high) {
op = currentOffset + defaultIndex;
} else {
op = currentOffset + jumpOffset[index->val - low];
}
} break;
case op_lookupswitch: {
u4 currentOffset = op - 1;
op++;
op++;
op++; // 3 bytes padding
int32_t defaultIndex = consumeU4(code, op);
int32_t npair = consumeU4(code, op);
map<int32_t, int32_t> matchOffset;
FOR_EACH(i, npair) {
matchOffset.insert(
make_pair(consumeU4(code, op), consumeU4(code, op)));
}
auto *key = frames->top()->pop<JInt>();
auto res = matchOffset.find(key->val);
if (res != matchOffset.end()) {
op = currentOffset + (*res).second;
} else {
op = currentOffset + defaultIndex;
}
} break;
case op_ireturn: {
return cloneValue(frames->top()->pop<JInt>());
} break;
case op_lreturn: {
return cloneValue(frames->top()->pop<JLong>());
} break;
case op_freturn: {
return cloneValue(frames->top()->pop<JFloat>());
} break;
case op_dreturn: {
return cloneValue(frames->top()->pop<JDouble>());
} break;
case op_areturn: {
return cloneValue(frames->top()->pop<JType>());
} break;
case op_return: {
return nullptr;
} break;
case op_getstatic: {
const u2 index = consumeU2(code, op);
auto symbolicRef = parseFieldSymbolicReference(jc, index);
yrt.ma->linkClassIfAbsent(symbolicRef.jc->getClassName());
yrt.ma->initClassIfAbsent(*this,
symbolicRef.jc->getClassName());
JType *field = symbolicRef.jc->getStaticVar(
symbolicRef.name, symbolicRef.descriptor);
frames->top()->push(field);
} break;
case op_putstatic: {
u2 index = consumeU2(code, op);
JType *value = frames->top()->pop<JType>();
auto symbolicRef = parseFieldSymbolicReference(jc, index);
yrt.ma->linkClassIfAbsent(symbolicRef.jc->getClassName());
yrt.ma->initClassIfAbsent(*this,
symbolicRef.jc->getClassName());
symbolicRef.jc->setStaticVar(symbolicRef.name,
symbolicRef.descriptor, value);
} break;
case op_getfield: {
u2 index = consumeU2(code, op);
JObject *objectref = frames->top()->pop<JObject>();
auto symbolicRef = parseFieldSymbolicReference(jc, index);
JType *field = cloneValue(yrt.jheap->getFieldByName(
symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor,
objectref));
frames->top()->push(field);
} break;
case op_putfield: {
const u2 index = consumeU2(code, op);
JType *value = frames->top()->pop<JType>();
JObject *objectref = frames->top()->pop<JObject>();
auto symbolicRef = parseFieldSymbolicReference(jc, index);
yrt.jheap->putFieldByName(symbolicRef.jc, symbolicRef.name,
symbolicRef.descriptor, objectref,
value);
} break;
case op_invokevirtual: {
const u2 index = consumeU2(code, op);
assert(typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Methodref));
auto symbolicRef = parseMethodSymbolicReference(jc, index);
if (symbolicRef.name == "<init>") {
runtime_error(
"invoking method should not be instance "
"initialization method\n");
}
if (!IS_SIGNATURE_POLYMORPHIC_METHOD(
symbolicRef.jc->getClassName(), symbolicRef.name)) {
invokeVirtual(symbolicRef.name, symbolicRef.descriptor);
} else {
// TODO:TO BE IMPLEMENTED
}
} break;
case op_invokespecial: {
const u2 index = consumeU2(code, op);
SymbolicRef symbolicRef;
if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_InterfaceMethodref)) {
symbolicRef =
parseInterfaceMethodSymbolicReference(jc, index);
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Methodref)) {
symbolicRef = parseMethodSymbolicReference(jc, index);
} else {
SHOULD_NOT_REACH_HERE
}
// If all of the following are true, let C be the direct
// superclass of the current class :
JavaClass *symbolicRefClass = symbolicRef.jc;
if ("<init>" != symbolicRef.name) {
if (!IS_CLASS_INTERFACE(
symbolicRefClass->raw.accessFlags)) {
if (symbolicRefClass->getClassName() ==
jc->getSuperClassName()) {
if (IS_CLASS_SUPER(jc->raw.accessFlags)) {
invokeSpecial(yrt.ma->findJavaClass(
jc->getSuperClassName()),
symbolicRef.name,
symbolicRef.descriptor);
break;
}
}
}
}
// Otherwise let C be the symbolic reference class
invokeSpecial(symbolicRef.jc, symbolicRef.name,
symbolicRef.descriptor);
} break;
case op_invokestatic: {
// Invoke a class (static) method
const u2 index = consumeU2(code, op);
if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_InterfaceMethodref)) {
auto symbolicRef =
parseInterfaceMethodSymbolicReference(jc, index);
invokeStatic(symbolicRef.jc, symbolicRef.name,
symbolicRef.descriptor);
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Methodref)) {
auto symbolicRef = parseMethodSymbolicReference(jc, index);
invokeStatic(symbolicRef.jc, symbolicRef.name,
symbolicRef.descriptor);
} else {
SHOULD_NOT_REACH_HERE
}
} break;
case op_invokeinterface: {
const u2 index = consumeU2(code, op);
++op; // read count and discard
++op; // opcode padding 0;
if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_InterfaceMethodref)) {
auto symbolicRef =
parseInterfaceMethodSymbolicReference(jc, index);
invokeInterface(symbolicRef.jc, symbolicRef.name,
symbolicRef.descriptor);
}
} break;
case op_invokedynamic: {
throw runtime_error("unsupported opcode [invokedynamic]");
} break;
case op_new: {
const u2 index = consumeU2(code, op);
JObject *objectref = execNew(jc, index);
frames->top()->push(objectref);
} break;
case op_newarray: {
const u1 atype = code[++op];
JInt *count = frames->top()->pop<JInt>();
if (count->val < 0) {
throw runtime_error("negative array size");
}
JArray *arrayref = yrt.jheap->createPODArray(atype, count->val);
frames->top()->push(arrayref);
} break;
case op_anewarray: {
const u2 index = consumeU2(code, op);
auto symbolicRef = parseClassSymbolicReference(jc, index);
JInt *count = frames->top()->pop<JInt>();
if (count->val < 0) {
throw runtime_error("negative array size");
}
JArray *arrayref =
yrt.jheap->createObjectArray(*symbolicRef.jc, count->val);
frames->top()->push(arrayref);
} break;
case op_arraylength: {
JArray *arrayref = frames->top()->pop<JArray>();
if (arrayref == nullptr) {
throw runtime_error("null pointer\n");
}
JInt *length = new JInt;
length->val = arrayref->length;
frames->top()->push(length);
} break;
case op_athrow: {
auto *throwobj = frames->top()->pop<JObject>();
if (throwobj == nullptr) {
throw runtime_error("null pointer");
}
if (!hasInheritanceRelationship(
throwobj->jc,
yrt.ma->loadClassIfAbsent("java/lang/Throwable"))) {
throw runtime_error("it's not a throwable object");
}
if (handleException(jc, exceptLen, exceptTab, throwobj, op)) {
while (!frames->top()->emptyStack()) {
frames->top()->pop<JType>();
}
frames->top()->push(throwobj);
} else /* Exception can not handled within method handlers */ {
exception.markException();
exception.setThrowExceptionInfo(throwobj);
return throwobj;
}
} break;
case op_checkcast: {
throw runtime_error("unsupported opcode [checkcast]");
} break;
case op_instanceof: {
const u2 index = consumeU2(code, op);
auto *objectref = frames->top()->pop<JObject>();
if (objectref == nullptr) {
frames->top()->push(new JInt(0));
}
if (checkInstanceof(jc, index, objectref)) {
frames->top()->push(new JInt(1));
} else {
frames->top()->push(new JInt(0));
}
} break;
case op_monitorenter: {
JType *ref = frames->top()->pop<JType>();
if (ref == nullptr) {
throw runtime_error("null pointer");
}
if (!yrt.jheap->hasMonitor(ref)) {
dynamic_cast<JObject *>(ref)->offset =
yrt.jheap->createMonitor();
}
yrt.jheap->findMonitor(ref)->enter(this_thread::get_id());
} break;
case op_monitorexit: {
JType *ref = frames->top()->pop<JType>();
if (ref == nullptr) {
throw runtime_error("null pointer");
}
if (!yrt.jheap->hasMonitor(ref)) {
dynamic_cast<JObject *>(ref)->offset =
yrt.jheap->createMonitor();
}
yrt.jheap->findMonitor(ref)->exit();
} break;
case op_wide: {
throw runtime_error("unsupported opcode [wide]");
} break;
case op_multianewarray: {
throw runtime_error("unsupported opcode [multianewarray]");
} break;
case op_ifnull: {
u4 currentOffset = op - 1;
int16_t branchIndex = consumeU2(code, op);
JObject *value = frames->top()->pop<JObject>();
if (value == nullptr) {
op = currentOffset + branchIndex;
}
} break;
case op_ifnonnull: {
u4 currentOffset = op - 1;
int16_t branchIndex = consumeU2(code, op);
JObject *value = frames->top()->pop<JObject>();
if (value != nullptr) {
op = currentOffset + branchIndex;
}
} break;
case op_goto_w: {
u4 currentOffset = op - 1;
int32_t branchIndex = consumeU4(code, op);
op = currentOffset + branchIndex;
} break;
case op_jsr_w: {
throw runtime_error("unsupported opcode [jsr_w]");
} break;
case op_breakpoint:
case op_impdep1:
case op_impdep2: {
// Reserved opcodde
cerr << "Are you a dot.class hacker? Or you were entered a "
"strange region.";
exit(EXIT_FAILURE);
} break;
default:
cerr << "The YVM can not recognize this opcode. Bytecode file "
"was be corrupted.";
exit(EXIT_FAILURE);
}
}
return nullptr;
}
//--------------------------------------------------------------------------------
// This function does "ldc" opcode jc type of JavaClass, which indicate where
// to resolve
//--------------------------------------------------------------------------------
void Interpreter::loadConstantPoolItem2Stack(const JavaClass *jc, u2 index) {
if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Integer)) {
auto val =
dynamic_cast<CONSTANT_Integer *>(jc->raw.constPoolInfo[index])->val;
JInt *ival = new JInt;
ival->val = val;
frames->top()->push(ival);
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Float)) {
auto val =
dynamic_cast<CONSTANT_Float *>(jc->raw.constPoolInfo[index])->val;
JFloat *fval = new JFloat;
fval->val = val;
frames->top()->push(fval);
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_String)) {
auto val = jc->getString(
dynamic_cast<CONSTANT_String *>(jc->raw.constPoolInfo[index])
->stringIndex);
JObject *str = yrt.jheap->createObject(
*yrt.ma->loadClassIfAbsent("java/lang/String"));
JArray *value = yrt.jheap->createCharArray(val, val.length());
// Put string into str's field; according the source file of
// java.lang.Object, we know that its first field was used to store
// chars
yrt.jheap->putFieldByOffset(*str, 0, value);
frames->top()->push(str);
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_Class)) {
throw runtime_error("nonsupport region");
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_MethodType)) {
throw runtime_error("nonsupport region");
} else if (typeid(*jc->raw.constPoolInfo[index]) ==
typeid(CONSTANT_MethodHandle)) {
throw runtime_error("nonsupport region");
} else {
throw runtime_error(
"invalid symbolic reference index on constant "
"pool");
}
}
bool Interpreter::handleException(const JavaClass *jc, u2 exceptLen,
ExceptionTable *exceptTab,
const JObject *objectref, u4 &op) {
FOR_EACH(i, exceptLen) {
const string &catchTypeName =
jc->getString(dynamic_cast<CONSTANT_Class *>(
jc->raw.constPoolInfo[exceptTab[i].catchType])
->nameIndex);
if (hasInheritanceRelationship(
yrt.ma->findJavaClass(objectref->jc->getClassName()),
yrt.ma->findJavaClass(catchTypeName)) &&
exceptTab[i].startPC <= op && op < exceptTab[i].endPC) {
// start<=op<end
// If we found a proper exception handler, set current pc as
// handlerPC of this exception table item;
op = exceptTab[i].handlerPC - 1;
return true;
}
if (exceptTab[i].catchType == 0) {
op = exceptTab[i].handlerPC - 1;
return true;
}
}
return false;
}
JObject *Interpreter::execNew(const JavaClass *jc, u2 index) {
yrt.ma->linkClassIfAbsent(const_cast<JavaClass *>(jc)->getClassName());
yrt.ma->initClassIfAbsent(*this,
const_cast<JavaClass *>(jc)->getClassName());
if (typeid(*jc->raw.constPoolInfo[index]) != typeid(CONSTANT_Class)) {
throw runtime_error(
"operand index of new is not a class or "
"interface\n");
}
string className = jc->getString(
dynamic_cast<CONSTANT_Class *>(jc->raw.constPoolInfo[index])
->nameIndex);
JavaClass *newClass = yrt.ma->loadClassIfAbsent(className);
return yrt.jheap->createObject(*newClass);
}
bool Interpreter::checkInstanceof(const JavaClass *jc, u2 index,
JType *objectref) {
string TclassName =
(char *)dynamic_cast<CONSTANT_Utf8 *>(
jc->raw.constPoolInfo[dynamic_cast<CONSTANT_Class *>(
jc->raw.constPoolInfo[index])
->nameIndex])
->bytes;
constexpr short TYPE_ARRAY = 1;
constexpr short TYPE_CLASS = 2;
constexpr short TYPE_INTERFACE = 3;
short tType = 0;
if (TclassName.find('[') != string::npos) {
tType = TYPE_ARRAY;
} else {
if (IS_CLASS_INTERFACE(
yrt.ma->findJavaClass(TclassName)->raw.accessFlags)) {
tType = TYPE_INTERFACE;
} else {
tType = TYPE_CLASS;
}
}
if (typeid(objectref) == typeid(JObject)) {
if (!IS_CLASS_INTERFACE(
dynamic_cast<JObject *>(objectref)->jc->raw.accessFlags)) {
// If it's an ordinary class
if (tType == TYPE_CLASS) {
if (yrt.ma->findJavaClass(dynamic_cast<JObject *>(objectref)
->jc->getClassName())
->getClassName() == TclassName ||
yrt.ma->findJavaClass(dynamic_cast<JObject *>(objectref)
->jc->getSuperClassName())
->getClassName() == TclassName) {
return true;
}
} else if (tType == TYPE_INTERFACE) {
auto &&interfaceIdxs = dynamic_cast<JObject *>(objectref)
->jc->getInterfacesIndex();
FOR_EACH(i, interfaceIdxs.size()) {
string interfaceName =
dynamic_cast<JObject *>(objectref)->jc->getString(
dynamic_cast<CONSTANT_Class *>(
dynamic_cast<JObject *>(objectref)
->jc->raw.constPoolInfo[interfaceIdxs[i]])
->nameIndex);
if (interfaceName == TclassName) {
return true;
}
}
} else {
SHOULD_NOT_REACH_HERE
}
} else {
// Otherwise, it's an interface class
if (tType == TYPE_CLASS) {
if (TclassName == "java/lang/Object") {
return true;
}
} else if (tType == TYPE_INTERFACE) {
if (TclassName == dynamic_cast<JObject *>(objectref)
->jc->getClassName() ||
TclassName == dynamic_cast<JObject *>(objectref)
->jc->getSuperClassName()) {
return true;
}
} else {
SHOULD_NOT_REACH_HERE
}
}
} else if (typeid(objectref) == typeid(JArray)) {
if (tType == TYPE_CLASS) {
if (TclassName == "java/lang/Object") {
return true;
}
} else if (tType == TYPE_INTERFACE) {
auto *firstComponent = dynamic_cast<JObject *>(
yrt.jheap->getElement(*dynamic_cast<JArray *>(objectref), 0));
auto &&interfaceIdxs = firstComponent->jc->getInterfacesIndex();
FOR_EACH(i, interfaceIdxs.size()) {
if (firstComponent->jc->getString(
dynamic_cast<CONSTANT_Class *>(
firstComponent->jc->raw
.constPoolInfo[interfaceIdxs[i]])
->nameIndex) == TclassName) {
return true;
}
}
} else if (tType == TYPE_ARRAY) {
throw runtime_error("to be continue\n");
} else {
SHOULD_NOT_REACH_HERE
}
} else {
SHOULD_NOT_REACH_HERE
}
}
void Interpreter::pushMethodArguments(vector<int> ¶meter,
bool isObjectMethod) {
if (parameter.size() > 0) {
for (int localIndex = parameter.size() - (isObjectMethod ? 0 : 1),
paramIndex = parameter.size() - 1;
paramIndex >= 0; localIndex--, paramIndex--) {
if (parameter[paramIndex] == T_INT ||
parameter[paramIndex] == T_BOOLEAN ||
parameter[paramIndex] == T_CHAR ||
parameter[paramIndex] == T_BYTE ||
parameter[paramIndex] == T_SHORT) {
frames->top()->setLocalVariable(
localIndex, frames->nextFrame()->pop<JInt>());
} else if (parameter[paramIndex] == T_FLOAT) {
frames->top()->setLocalVariable(
localIndex, frames->nextFrame()->pop<JFloat>());
} else if (parameter[paramIndex] == T_DOUBLE) {
frames->top()->setLocalVariable(
localIndex, frames->nextFrame()->pop<JDouble>());
} else if (parameter[paramIndex] == T_LONG) {
frames->top()->setLocalVariable(
localIndex, frames->nextFrame()->pop<JLong>());
} else if (parameter[paramIndex] == T_EXTRA_ARRAY) {
frames->top()->setLocalVariable(
localIndex, frames->nextFrame()->pop<JArray>());
} else if (parameter[paramIndex] == T_EXTRA_OBJECT) {
frames->top()->setLocalVariable(
localIndex, frames->nextFrame()->pop<JObject>());
} else {
SHOULD_NOT_REACH_HERE;
}
}
}
if (isObjectMethod) {
frames->top()->setLocalVariable(0, frames->nextFrame()->pop<JObject>());
}
}
//--------------------------------------------------------------------------------
// Invoke by given name, this method was be used internally
//--------------------------------------------------------------------------------
void Interpreter::invokeByName(JavaClass *jc, const string &name,
const string &descriptor) {
const int returnType = get<0>(peelMethodParameterAndType(descriptor));
MethodInfo *m = jc->findMethod(name, descriptor);
CallSite csite = CallSite::makeCallSite(jc, m);
if (!csite.isCallable()) {
return;
}
frames->pushFrame(csite.maxLocal, csite.maxStack);
JType *returnValue{};
if (IS_METHOD_NATIVE(m->accessFlags)) {
returnValue =
cloneValue(execNativeMethod(jc->getClassName(), name, descriptor));
} else {
returnValue =
cloneValue(execByteCode(jc, csite.code, csite.codeLength,
csite.exceptionLen, csite.exception));
}
frames->popFrame();
// Since invokeByName() was merely used to call <clinit> and main method
// of running program, therefore, if an exception reached here, we don't
// need to push its value into upper frame again (In fact there is no more
// frame), we just print stack trace inforamtion to notice user and
// return directly
if (returnType != T_EXTRA_VOID) {
frames->top()->push(returnValue);
}
if (exception.hasUnhandledException()) {
exception.extendExceptionStackTrace(name);
exception.printStackTrace();
}
GC_SAFE_POINT
if (yrt.gc->shallGC()) {
yrt.gc->stopTheWorld();
yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP);
}
}
//--------------------------------------------------------------------------------
// Invoke interface method
//--------------------------------------------------------------------------------
void Interpreter::invokeInterface(const JavaClass *jc, const string &name,
const string &descriptor) {
auto parameterAndReturnType = peelMethodParameterAndType(descriptor);
const int returnType = get<0>(parameterAndReturnType);
auto parameter = get<1>(parameterAndReturnType);
auto csite = findInstanceMethod(jc, name, descriptor);
if (!csite.isCallable()) {
csite = findInstanceMethodOnSupers(jc, name, descriptor);
if (!csite.isCallable()) {
csite = findMaximallySpecifiedMethod(jc, name, descriptor);
if (!csite.isCallable()) {
throw runtime_error("can not find method " + name + " " +
descriptor);
}
}
}
if (IS_METHOD_NATIVE(csite.accessFlags)) {
csite.maxLocal = csite.maxStack = parameter.size() + 1;
}
frames->pushFrame(csite.maxLocal, csite.maxStack);
pushMethodArguments(parameter, true);
JType *returnValue{};
if (IS_METHOD_NATIVE(csite.accessFlags)) {
returnValue = cloneValue(
execNativeMethod(csite.jc->getClassName(), name, descriptor));
} else {
returnValue =
cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength,
csite.exceptionLen, csite.exception));
}
frames->popFrame();
if (returnType != T_EXTRA_VOID) {
frames->top()->push(returnValue);
}
if (exception.hasUnhandledException()) {
frames->top()->grow(1);
frames->top()->push(returnValue);
if (exception.hasUnhandledException()) {
exception.extendExceptionStackTrace(name);
}
}
GC_SAFE_POINT
if (yrt.gc->shallGC()) {
yrt.gc->stopTheWorld();
yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP);
}
}
//--------------------------------------------------------------------------------
// Invoke instance method; dispatch based on class
//--------------------------------------------------------------------------------
void Interpreter::invokeVirtual(const string &name, const string &descriptor) {
auto parameterAndReturnType = peelMethodParameterAndType(descriptor);
const int returnType = get<0>(parameterAndReturnType);
auto parameter = get<1>(parameterAndReturnType);
auto *thisRef =
(JObject *)frames->top()
->stackSlots[frames->top()->stackTop - parameter.size() - 1];
auto csite = findInstanceMethod(thisRef->jc, name, descriptor);
if (!csite.isCallable()) {
csite = findInstanceMethodOnSupers(thisRef->jc, name, descriptor);
if (!csite.isCallable()) {
csite = findMaximallySpecifiedMethod(thisRef->jc, name, descriptor);
if (!csite.isCallable()) {
throw runtime_error("can not find method " + name + " " +
descriptor);
}
}
}
if (IS_METHOD_NATIVE(csite.accessFlags)) {
csite.maxLocal = csite.maxStack = parameter.size() + 1;
}
frames->pushFrame(csite.maxLocal, csite.maxStack);
pushMethodArguments(parameter, true);
JType *returnValue{};
if (csite.isCallable()) {
if (IS_METHOD_NATIVE(csite.accessFlags)) {
returnValue = cloneValue(
execNativeMethod(csite.jc->getClassName(), name, descriptor));
} else {
returnValue =
cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength,
csite.exceptionLen, csite.exception));
}
} else {
throw runtime_error("can not find method to call");
}
frames->popFrame();
if (returnType != T_EXTRA_VOID) {
frames->top()->push(returnValue);
}
if (exception.hasUnhandledException()) {
frames->top()->grow(1);
frames->top()->push(returnValue);
if (exception.hasUnhandledException()) {
exception.extendExceptionStackTrace(name);
}
}
GC_SAFE_POINT
if (yrt.gc->shallGC()) {
yrt.gc->stopTheWorld();
yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP);
}
}
//--------------------------------------------------------------------------------
// Invoke instance method; special handling for superclass, private,
// and instance initialization method invocations
//--------------------------------------------------------------------------------
void Interpreter::invokeSpecial(const JavaClass *jc, const string &name,
const string &descriptor) {
auto parameterAndReturnType = peelMethodParameterAndType(descriptor);
const int returnType = get<0>(parameterAndReturnType);
auto parameter = get<1>(parameterAndReturnType);
auto csite = findInstanceMethod(jc, name, descriptor);
if (!csite.isCallable()) {
csite = findInstanceMethodOnSupers(jc, name, descriptor);
if (!csite.isCallable()) {
csite = findJavaLangObjectMethod(jc, name, descriptor);
if (!csite.isCallable()) {
csite = findMaximallySpecifiedMethod(jc, name, descriptor);
if (!csite.isCallable()) {
throw runtime_error("can not find method " + name + " " +
descriptor);
}
}
}
}
if (IS_METHOD_NATIVE(csite.accessFlags)) {
csite.maxLocal = csite.maxStack = parameter.size() + 1;
}
frames->pushFrame(csite.maxLocal, csite.maxStack);
pushMethodArguments(parameter, true);
JType *returnValue{};
if (IS_METHOD_NATIVE(csite.accessFlags)) {
returnValue = cloneValue(
execNativeMethod(csite.jc->getClassName(), name, descriptor));
} else {
returnValue =
cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength,
csite.exceptionLen, csite.exception));
}
frames->popFrame();
if (returnType != T_EXTRA_VOID) {
frames->top()->push(returnValue);
}
if (exception.hasUnhandledException()) {
frames->top()->grow(1);
frames->top()->push(returnValue);
if (exception.hasUnhandledException()) {
exception.extendExceptionStackTrace(name);
}
}
GC_SAFE_POINT
if (yrt.gc->shallGC()) {
yrt.gc->stopTheWorld();
yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP);
}
}
void Interpreter::invokeStatic(const JavaClass *jc, const string &name,
const string &descriptor) {
// Get instance method name and descriptor from CONSTANT_Methodref
// locating by index and get interface method parameter and return value
// descriptor
yrt.ma->linkClassIfAbsent(const_cast<JavaClass *>(jc)->getClassName());
yrt.ma->initClassIfAbsent(*this,
const_cast<JavaClass *>(jc)->getClassName());
auto parameterAndReturnType = peelMethodParameterAndType(descriptor);
const int returnType = get<0>(parameterAndReturnType);
auto parameter = get<1>(parameterAndReturnType);
auto csite = CallSite::makeCallSite(jc, jc->findMethod(name, descriptor));
if (!csite.isCallable()) {
throw runtime_error("can not find method " + name + " " + descriptor);
}
assert(IS_METHOD_STATIC(csite.accessFlags) == true);
assert(IS_METHOD_ABSTRACT(csite.accessFlags) == false);
assert("<init>" != name);
if (IS_METHOD_NATIVE(csite.accessFlags)) {
csite.maxLocal = csite.maxStack = parameter.size();
}
frames->pushFrame(csite.maxLocal, csite.maxStack);
pushMethodArguments(parameter, false);
JType *returnValue{};
if (IS_METHOD_NATIVE(csite.accessFlags)) {
returnValue = cloneValue(
execNativeMethod(csite.jc->getClassName(), name, descriptor));
} else {
returnValue =
cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength,
csite.exceptionLen, csite.exception));
}
frames->popFrame();
if (returnType != T_EXTRA_VOID) {
frames->top()->push(returnValue);
}
if (exception.hasUnhandledException()) {
frames->top()->grow(1);
frames->top()->push(returnValue);
if (exception.hasUnhandledException()) {
exception.extendExceptionStackTrace(name);
}
}
GC_SAFE_POINT
if (yrt.gc->shallGC()) {
yrt.gc->stopTheWorld();
yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP);
}
}
| 40.104454
| 82
| 0.464178
|
continue-nature
|
5c1015809f4e4a48c90df6c135764a90c7f180dc
| 2,593
|
cpp
|
C++
|
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
|
KetiLeeJeongHun/OpenHologram
|
c6cdddb5106fe0079d9810eea588d28aa71f0023
|
[
"BSD-2-Clause"
] | 17
|
2017-11-07T06:44:11.000Z
|
2021-11-14T05:06:08.000Z
|
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
|
KetiLeeJeongHun/OpenHologram
|
c6cdddb5106fe0079d9810eea588d28aa71f0023
|
[
"BSD-2-Clause"
] | 1
|
2017-09-26T04:35:31.000Z
|
2017-09-26T04:35:31.000Z
|
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
|
KetiLeeJeongHun/OpenHologram
|
c6cdddb5106fe0079d9810eea588d28aa71f0023
|
[
"BSD-2-Clause"
] | 9
|
2017-09-13T08:01:45.000Z
|
2020-04-28T10:11:14.000Z
|
#ifdef _OPENMP
#include<omp.h>
#endif
#include "WRP.h"
int OPHWRP::readxyz(string filename) //read point cloud
{
int dimen = 3;
ifstream infilee(filename);
string temp, temp2mat;
vector <string> temsplit;
if (!infilee)
{
cerr << "can not read the file";
return -1;
}
while (getline(infilee, temp))
{
istringstream LineBand(temp);
while (LineBand >> temp2mat)
{
// printf("temp2mat=%e\n", stof(temp2mat.data()));
vec_xyz.push_back(stod(temp2mat.data()));
}
}
int num = vec_xyz.size() / dimen;
obj_num = num;
cwoObjPoint *op = (cwoObjPoint*)malloc(num*sizeof(cwoObjPoint));
for (int i = 0; i < num; i++){
double x, y, z;
x = vec_xyz.at(dimen*i);
y = vec_xyz.at(dimen*i + 1);
z = vec_xyz.at(dimen*i + 2);
op[i].x = x;
op[i].y = y;
op[i].z = z;
}
obj = op;
return 0;
}
int OPHWRP::Setparameter(float m_wavelength, float m_pixelpitch, float m_resolution)
{
SetWaveLength(m_wavelength);
SetPitch(m_pixelpitch);
SetDstPitch(m_pixelpitch);
Create(m_resolution, m_resolution, 1);
return 0;
}
int OPHWRP::Fresnelpropagation(float z)
{
Diffract(z, CWO_FRESNEL_CONV);
return 0;
}
int OPHWRP::SavetoImage(char* filename)
{
SaveAsImage(filename, CWO_SAVE_AS_ARG);
return 0;
}
void OPHWRP::SingleWRP(float z) //generate WRP plane
{
float wn = GetWaveNum();
float wl = GetWaveLength();
int Nx = GetNx();
int Ny = GetNy();
float spx = GetPx(); //
float spy = GetPy();
float sox = GetOx();//point offset
float soy = GetOy();
float soz = GetOz();
float dpx = GetDstPx();//wrp pitch
float dpy = GetDstPy();
float dox = GetDstOx();//wrp offset
float doy = GetDstOy();
int Nx_h = Nx >> 1;
int Ny_h = Ny >> 1;
cwoObjPoint *pc = obj;
int num = obj_num;
#ifdef _OPENMP
omp_set_num_threads(GetThreads());
#pragma omp parallel for
#endif
for (int k = 0; k < num; k++){
float dz = z - pc[k].z;
float tw = (int)fabs(wl*dz / dpx / dpx / 2 + 0.5) * 2 - 1;
int w = (int)tw;
int tx = (int)(pc[k].x / dpx) + Nx_h;
int ty = (int)(pc[k].y / dpy) + Ny_h;
printf("num=%d, tx=%d, ty=%d, w=%d\n", k, tx, ty, w);
for (int wy = -w; wy < w; wy++){
for (int wx = -w; wx<w; wx++){//WRP coordinate
double dx = wx*dpx;
double dy = wy*dpy;
double dz = z - pc[k].z;
double sign = (dz>0.0) ? (1.0) : (-1.0);
double r = sign*sqrt(dx*dx + dy*dy + dz*dz);
cwoComplex tmp;
CWO_RE(tmp) = cosf(wn*r) / (r + 0.05);
CWO_IM(tmp) = sinf(wn*r) / (r + 0.05);
if (tx + wx >= 0 && tx + wx < Nx && ty + wy >= 0 && ty + wy < Ny)
AddPixel(wx + tx, wy + ty, tmp);
}
}
}
}
| 18.132867
| 84
| 0.59275
|
KetiLeeJeongHun
|
5c101ef567bb4dc304f721fc2f04dec87b513df2
| 5,698
|
hpp
|
C++
|
benchmarks/statistical/dataflow_declarations.hpp
|
vamatya/benchmarks
|
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
|
[
"BSL-1.0"
] | null | null | null |
benchmarks/statistical/dataflow_declarations.hpp
|
vamatya/benchmarks
|
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
|
[
"BSL-1.0"
] | null | null | null |
benchmarks/statistical/dataflow_declarations.hpp
|
vamatya/benchmarks
|
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2012 Daniel Kogler
//
// 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)
//this file simply enumerates a multitude of functions used to define the action
//used in the benchmark. Which function is used is decided based on input args
#include <hpx/hpx.hpp>
#include <hpx/hpx_init.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/actions.hpp>
#include <hpx/include/iostreams.hpp>
#include <hpx/include/components.hpp>
#include <hpx/util/high_resolution_timer.hpp>
#include <hpx/components/dataflow/dataflow.hpp>
#include <hpx/components/dataflow/dataflow_trigger.hpp>
#include <vector>
#include <string>
using std::vector;
using std::string;
using boost::program_options::variables_map;
using boost::program_options::options_description;
using boost::uint64_t;
using hpx::util::high_resolution_timer;
using hpx::cout;
using hpx::flush;
//global dummy variables of several different primitive types
int ivar = 1;
long lvar = 1;
float fvar = 1;
double dvar = 1;
///////////////////////////////////////////////////////////////////////////////
//forward declarations
template <typename Vector, typename Package, typename Result>
void run_empty(uint64_t number);
///////////////////////////////////////////////////////////////////////////////
//empty functions for plain_result_actions
template<typename A1>
A1 empty_thread(){
A1 dummy = 0;
return dummy;
}
template<typename A1>
A1 empty_thread(A1 arg1){;
return arg1;
}
template<typename A1>
A1 empty_thread(A1 arg1, A1 arg2){
return arg2;
}
template<typename A1>
A1 empty_thread(A1 arg1, A1 arg2, A1 arg3){
return arg3;
}
template<typename A1>
A1 empty_thread(A1 arg1, A1 arg2, A1 arg3, A1 arg4){
return arg4;
}
typedef hpx::actions::plain_result_action0<int, empty_thread> empty_actioni0;
HPX_REGISTER_PLAIN_ACTION(empty_actioni0);
typedef hpx::actions::plain_result_action0<long, empty_thread> empty_actionl0;
HPX_REGISTER_PLAIN_ACTION(empty_actionl0);
typedef hpx::actions::plain_result_action0<float, empty_thread> empty_actionf0;
HPX_REGISTER_PLAIN_ACTION(empty_actionf0);
typedef hpx::actions::plain_result_action0<double, empty_thread> empty_actiond0;
HPX_REGISTER_PLAIN_ACTION(empty_actiond0);
typedef hpx::actions::plain_result_action1<int, int, empty_thread>
empty_actioni1;
HPX_REGISTER_PLAIN_ACTION(empty_actioni1);
typedef hpx::actions::plain_result_action1<long, long, empty_thread>
empty_actionl1;
HPX_REGISTER_PLAIN_ACTION(empty_actionl1);
typedef hpx::actions::plain_result_action1<float, float, empty_thread>
empty_actionf1;
HPX_REGISTER_PLAIN_ACTION(empty_actionf1);
typedef hpx::actions::plain_result_action1<double, double, empty_thread>
empty_actiond1;
HPX_REGISTER_PLAIN_ACTION(empty_actiond1);
typedef hpx::actions::plain_result_action2<int, int, int, empty_thread>
empty_actioni2;
HPX_REGISTER_PLAIN_ACTION(empty_actioni2);
typedef hpx::actions::plain_result_action2<long, long, long, empty_thread>
empty_actionl2;
HPX_REGISTER_PLAIN_ACTION(empty_actionl2);
typedef hpx::actions::plain_result_action2<float, float, float, empty_thread>
empty_actionf2;
HPX_REGISTER_PLAIN_ACTION(empty_actionf2);
typedef hpx::actions::plain_result_action2<double, double, double, empty_thread>
empty_actiond2;
HPX_REGISTER_PLAIN_ACTION(empty_actiond2);
typedef hpx::actions::plain_result_action3<
int, int, int, int, empty_thread> empty_actioni3;
HPX_REGISTER_PLAIN_ACTION(empty_actioni3);
typedef hpx::actions::plain_result_action3<
long, long, long, long, empty_thread> empty_actionl3;
HPX_REGISTER_PLAIN_ACTION(empty_actionl3);
typedef hpx::actions::plain_result_action3<
float, float, float, float, empty_thread> empty_actionf3;
HPX_REGISTER_PLAIN_ACTION(empty_actionf3);
typedef hpx::actions::plain_result_action3<
double, double, double, double, empty_thread> empty_actiond3;
HPX_REGISTER_PLAIN_ACTION(empty_actiond3);
typedef hpx::actions::plain_result_action4<
int, int, int, int, int, empty_thread> empty_actioni4;
HPX_REGISTER_PLAIN_ACTION(empty_actioni4);
typedef hpx::actions::plain_result_action4<
long, long, long, long, long, empty_thread> empty_actionl4;
HPX_REGISTER_PLAIN_ACTION(empty_actionl4);
typedef hpx::actions::plain_result_action4<
float, float, float, float, float, empty_thread> empty_actionf4;
HPX_REGISTER_PLAIN_ACTION(empty_actionf4);
typedef hpx::actions::plain_result_action4<
double, double, double, double, double, empty_thread> empty_actiond4;
HPX_REGISTER_PLAIN_ACTION(empty_actiond4);
typedef hpx::lcos::dataflow<empty_actioni0> eflowi0;
typedef hpx::lcos::dataflow<empty_actionl0> eflowl0;
typedef hpx::lcos::dataflow<empty_actionf0> eflowf0;
typedef hpx::lcos::dataflow<empty_actiond0> eflowd0;
typedef hpx::lcos::dataflow<empty_actioni1> eflowi1;
typedef hpx::lcos::dataflow<empty_actionl1> eflowl1;
typedef hpx::lcos::dataflow<empty_actionf1> eflowf1;
typedef hpx::lcos::dataflow<empty_actiond1> eflowd1;
typedef hpx::lcos::dataflow<empty_actioni2> eflowi2;
typedef hpx::lcos::dataflow<empty_actionl2> eflowl2;
typedef hpx::lcos::dataflow<empty_actionf2> eflowf2;
typedef hpx::lcos::dataflow<empty_actiond2> eflowd2;
typedef hpx::lcos::dataflow<empty_actioni3> eflowi3;
typedef hpx::lcos::dataflow<empty_actionl3> eflowl3;
typedef hpx::lcos::dataflow<empty_actionf3> eflowf3;
typedef hpx::lcos::dataflow<empty_actiond3> eflowd3;
typedef hpx::lcos::dataflow<empty_actioni4> eflowi4;
typedef hpx::lcos::dataflow<empty_actionl4> eflowl4;
typedef hpx::lcos::dataflow<empty_actionf4> eflowf4;
typedef hpx::lcos::dataflow<empty_actiond4> eflowd4;
| 34.957055
| 81
| 0.777115
|
vamatya
|
5c11ebf22b456bb03e0c41dc3f4f23c87a67614b
| 495
|
cpp
|
C++
|
source/lab4/classic_newton.cpp
|
Jovvik/methopt-lab-1
|
2c3acaf653c7214a925ed1292b9d1d30a33d2737
|
[
"Unlicense"
] | null | null | null |
source/lab4/classic_newton.cpp
|
Jovvik/methopt-lab-1
|
2c3acaf653c7214a925ed1292b9d1d30a33d2737
|
[
"Unlicense"
] | null | null | null |
source/lab4/classic_newton.cpp
|
Jovvik/methopt-lab-1
|
2c3acaf653c7214a925ed1292b9d1d30a33d2737
|
[
"Unlicense"
] | null | null | null |
#include "lab4/classic_newton.h"
#include <lab3/solver.h>
#include <utility>
#include "iostream"
using namespace lab4;
ClassicNewton::ClassicNewton() : p(lab2::Vector({1})) {}
lab2::Vector ClassicNewton::iteration(lab2::NFunction& f, double) {
lab2::Vector x = get_points().back();
p = lab3::Solver::solve(f.hessian(x), f.grad(x) * (-1));
return x + p;
}
bool ClassicNewton::is_done(lab2::NFunction&, double epsilon) const {
return p.norm() < epsilon;
}
| 23.571429
| 76
| 0.644444
|
Jovvik
|
5c1530cf4db20b54211ff2453e929b1abe998a88
| 564
|
cpp
|
C++
|
src/dummy_server/src/dummy_server_handler.cpp
|
maxerMU/db-course
|
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
|
[
"Apache-2.0"
] | null | null | null |
src/dummy_server/src/dummy_server_handler.cpp
|
maxerMU/db-course
|
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
|
[
"Apache-2.0"
] | null | null | null |
src/dummy_server/src/dummy_server_handler.cpp
|
maxerMU/db-course
|
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
|
[
"Apache-2.0"
] | null | null | null |
#include "dummy_server_handler.h"
#include <iostream>
DummyServerHandler::DummyServerHandler(
const std::shared_ptr<BaseConfig> &config) {
append_string = config->get_string_field({"AppendString"});
}
void DummyServerHandler::handle_request(const std::shared_ptr<Request> &req) {
std::cout << req->get_body() << std::endl;
std::cout << req->get_target() << std::endl;
req_body = req->get_body();
}
void DummyServerHandler::make_response(const std::shared_ptr<Response> &resp) {
std::string res = req_body + append_string;
resp->set_body(res);
}
| 29.684211
| 79
| 0.723404
|
maxerMU
|
5c1579f5da212410199c1703479b91eda172214f
| 54,852
|
cpp
|
C++
|
modules/juce_gui_basics/layout/juce_FlexBox.cpp
|
dikadk/JUCE
|
514c6c8de8bd34c0663d1d691a034b48922af5c8
|
[
"ISC"
] | null | null | null |
modules/juce_gui_basics/layout/juce_FlexBox.cpp
|
dikadk/JUCE
|
514c6c8de8bd34c0663d1d691a034b48922af5c8
|
[
"ISC"
] | null | null | null |
modules/juce_gui_basics/layout/juce_FlexBox.cpp
|
dikadk/JUCE
|
514c6c8de8bd34c0663d1d691a034b48922af5c8
|
[
"ISC"
] | null | null | null |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
struct FlexBoxLayoutCalculation
{
using Coord = double;
enum class Axis
{
main,
cross
};
FlexBoxLayoutCalculation(FlexBox &fb, Coord w, Coord h)
: owner(fb), parentWidth(w), parentHeight(h), numItems(owner.items.size()),
isRowDirection(fb.flexDirection == FlexBox::Direction::row || fb.flexDirection == FlexBox::Direction::rowReverse),
containerLineLength(getContainerSize(Axis::main))
{
lineItems.calloc(numItems * numItems);
lineInfo.calloc(numItems);
}
struct ItemWithState
{
ItemWithState(FlexItem &source) noexcept : item(&source) {}
FlexItem *item;
Coord lockedWidth = 0, lockedHeight = 0;
Coord lockedMarginLeft = 0, lockedMarginRight = 0, lockedMarginTop = 0, lockedMarginBottom = 0;
Coord preferredWidth = 0, preferredHeight = 0;
bool locked = false;
void resetItemLockedSize() noexcept
{
lockedWidth = preferredWidth;
lockedHeight = preferredHeight;
lockedMarginLeft = getValueOrZeroIfAuto(item->margin.left);
lockedMarginRight = getValueOrZeroIfAuto(item->margin.right);
lockedMarginTop = getValueOrZeroIfAuto(item->margin.top);
lockedMarginBottom = getValueOrZeroIfAuto(item->margin.bottom);
}
};
struct RowInfo
{
int numItems;
Coord crossSize, lineY, totalLength;
};
FlexBox &owner;
const Coord parentWidth, parentHeight;
const int numItems;
const bool isRowDirection;
const Coord containerLineLength;
int numberOfRows = 1;
Coord containerCrossLength = 0;
HeapBlock<ItemWithState *> lineItems;
HeapBlock<RowInfo> lineInfo;
Array<ItemWithState> itemStates;
ItemWithState &getItem(int x, int y) const noexcept { return *lineItems[y * numItems + x]; }
static bool isAuto(Coord value) noexcept { return value == FlexItem::autoValue; }
static bool isAssigned(Coord value) noexcept { return value != FlexItem::notAssigned; }
static Coord getValueOrZeroIfAuto(Coord value) noexcept { return isAuto(value) ? Coord() : value; }
//==============================================================================
bool isSingleLine() const { return owner.flexWrap == FlexBox::Wrap::noWrap; }
template <typename Value>
Value &pickForAxis(Axis axis, Value &x, Value &y) const
{
return (isRowDirection ? axis == Axis::main : axis == Axis::cross) ? x : y;
}
auto &getStartMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->margin.left, item.item->margin.top);
}
auto &getEndMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->margin.right, item.item->margin.bottom);
}
auto &getStartLockedMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.lockedMarginLeft, item.lockedMarginTop);
}
auto &getEndLockedMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.lockedMarginRight, item.lockedMarginBottom);
}
auto &getLockedSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.lockedWidth, item.lockedHeight);
}
auto &getPreferredSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.preferredWidth, item.preferredHeight);
}
Coord getContainerSize(Axis axis) const
{
return pickForAxis(axis, parentWidth, parentHeight);
}
auto &getItemSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->width, item.item->height);
}
auto &getMinSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->minWidth, item.item->minHeight);
}
auto &getMaxSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->maxWidth, item.item->maxHeight);
}
//==============================================================================
void createStates()
{
itemStates.ensureStorageAllocated(numItems);
for (auto &item : owner.items)
itemStates.add(item);
std::stable_sort(itemStates.begin(), itemStates.end(),
[](const ItemWithState &i1, const ItemWithState &i2)
{ return i1.item->order < i2.item->order; });
for (auto &item : itemStates)
{
for (auto &axis : {Axis::main, Axis::cross})
getPreferredSize(axis, item) = computePreferredSize(axis, item);
}
}
void initialiseItems() noexcept
{
if (isSingleLine()) // for single-line, all items go in line 1
{
lineInfo[0].numItems = numItems;
int i = 0;
for (auto &item : itemStates)
{
item.resetItemLockedSize();
lineItems[i++] = &item;
}
}
else // if multi-line, group the flexbox items into multiple lines
{
auto currentLength = containerLineLength;
int column = 0, row = 0;
bool firstRow = true;
for (auto &item : itemStates)
{
item.resetItemLockedSize();
const auto flexitemLength = getItemMainSize(item);
if (flexitemLength > currentLength)
{
if (!firstRow)
row++;
if (row >= numItems)
break;
column = 0;
currentLength = containerLineLength;
numberOfRows = jmax(numberOfRows, row + 1);
}
currentLength -= flexitemLength;
lineItems[row * numItems + column] = &item;
++column;
lineInfo[row].numItems = jmax(lineInfo[row].numItems, column);
firstRow = false;
}
}
}
void resolveFlexibleLengths() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
resetRowItems(row);
for (int maxLoops = numItems; --maxLoops >= 0;)
{
resetUnlockedRowItems(row);
if (layoutRowItems(row))
break;
}
}
}
void resolveAutoMarginsOnMainAxis() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
Coord allFlexGrow = 0;
const auto numColumns = lineInfo[row].numItems;
const auto remainingLength = containerLineLength - lineInfo[row].totalLength;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAuto(getStartMargin(Axis::main, item)))
++allFlexGrow;
if (isAuto(getEndMargin(Axis::main, item)))
++allFlexGrow;
}
const auto changeUnitWidth = remainingLength / allFlexGrow;
if (changeUnitWidth > 0)
{
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAuto(getStartMargin(Axis::main, item)))
getStartLockedMargin(Axis::main, item) = changeUnitWidth;
if (isAuto(getEndMargin(Axis::main, item)))
getEndLockedMargin(Axis::main, item) = changeUnitWidth;
}
}
}
}
void calculateCrossSizesByLine() noexcept
{
// https://www.w3.org/TR/css-flexbox-1/#algo-cross-line
// If the flex container is single-line and has a definite cross size, the cross size of the
// flex line is the flex container’s inner cross size.
if (isSingleLine())
{
lineInfo[0].crossSize = getContainerSize(Axis::cross);
}
else
{
for (int row = 0; row < numberOfRows; ++row)
{
Coord maxSize = 0;
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
maxSize = jmax(maxSize, getItemCrossSize(getItem(column, row)));
lineInfo[row].crossSize = maxSize;
}
}
}
void calculateCrossSizeOfAllItems() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAssigned(item.item->maxHeight) && item.lockedHeight > item.item->maxHeight)
item.lockedHeight = item.item->maxHeight;
if (isAssigned(item.item->maxWidth) && item.lockedWidth > item.item->maxWidth)
item.lockedWidth = item.item->maxWidth;
}
}
}
void alignLinesPerAlignContent() noexcept
{
containerCrossLength = getContainerSize(Axis::cross);
if (owner.alignContent == FlexBox::AlignContent::flexStart)
{
for (int row = 0; row < numberOfRows; ++row)
for (int row2 = row; row2 < numberOfRows; ++row2)
lineInfo[row].lineY = row == 0 ? 0 : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
else if (owner.alignContent == FlexBox::AlignContent::flexEnd)
{
for (int row = 0; row < numberOfRows; ++row)
{
Coord crossHeights = 0;
for (int row2 = row; row2 < numberOfRows; ++row2)
crossHeights += lineInfo[row2].crossSize;
lineInfo[row].lineY = containerCrossLength - crossHeights;
}
}
else
{
Coord totalHeight = 0;
for (int row = 0; row < numberOfRows; ++row)
totalHeight += lineInfo[row].crossSize;
if (owner.alignContent == FlexBox::AlignContent::stretch)
{
const auto difference = jmax(Coord(), (containerCrossLength - totalHeight) / numberOfRows);
for (int row = 0; row < numberOfRows; ++row)
{
lineInfo[row].crossSize += difference;
lineInfo[row].lineY = row == 0 ? 0 : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
}
else if (owner.alignContent == FlexBox::AlignContent::center)
{
const auto additionalength = (containerCrossLength - totalHeight) / 2;
for (int row = 0; row < numberOfRows; ++row)
lineInfo[row].lineY = row == 0 ? additionalength : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
else if (owner.alignContent == FlexBox::AlignContent::spaceBetween)
{
const auto additionalength = numberOfRows <= 1 ? Coord() : jmax(Coord(), (containerCrossLength - totalHeight) / static_cast<Coord>(numberOfRows - 1));
lineInfo[0].lineY = 0;
for (int row = 1; row < numberOfRows; ++row)
lineInfo[row].lineY += additionalength + lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
else if (owner.alignContent == FlexBox::AlignContent::spaceAround)
{
const auto additionalength = numberOfRows <= 1 ? Coord() : jmax(Coord(), (containerCrossLength - totalHeight) / static_cast<Coord>(2 + (2 * (numberOfRows - 1))));
lineInfo[0].lineY = additionalength;
for (int row = 1; row < numberOfRows; ++row)
lineInfo[row].lineY += (2 * additionalength) + lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
}
}
void resolveAutoMarginsOnCrossAxis() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
const auto crossSizeForLine = lineInfo[row].crossSize;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
getStartLockedMargin(Axis::cross, item) = [&]
{
if (isAuto(getStartMargin(Axis::cross, item)) && isAuto(getEndMargin(Axis::cross, item)))
return (crossSizeForLine - getLockedSize(Axis::cross, item)) / 2;
if (isAuto(getStartMargin(Axis::cross, item)))
return crossSizeForLine - getLockedSize(Axis::cross, item) - getEndMargin(Axis::cross, item);
return getStartLockedMargin(Axis::cross, item);
}();
}
}
}
// Align all flex items along the cross-axis per align-self, if neither of the item’s cross-axis margins are auto.
void alignItemsInCrossAxisInLinesPerAlignSelf() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
const auto lineSize = lineInfo[row].crossSize;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAuto(getStartMargin(Axis::cross, item)) || isAuto(getEndMargin(Axis::cross, item)))
continue;
const auto alignment = [&]
{
switch (item.item->alignSelf)
{
case FlexItem::AlignSelf::stretch:
return FlexBox::AlignItems::stretch;
case FlexItem::AlignSelf::flexStart:
return FlexBox::AlignItems::flexStart;
case FlexItem::AlignSelf::flexEnd:
return FlexBox::AlignItems::flexEnd;
case FlexItem::AlignSelf::center:
return FlexBox::AlignItems::center;
case FlexItem::AlignSelf::autoAlign:
break;
}
return owner.alignItems;
}();
getStartLockedMargin(Axis::cross, item) = [&]
{
switch (alignment)
{
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-flex-start
// The cross-start margin edge of the flex item is placed flush with the
// cross-start edge of the line.
case FlexBox::AlignItems::flexStart:
return (Coord)getStartMargin(Axis::cross, item);
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-flex-end
// The cross-end margin edge of the flex item is placed flush with the cross-end
// edge of the line.
case FlexBox::AlignItems::flexEnd:
return lineSize - getLockedSize(Axis::cross, item) - getEndMargin(Axis::cross, item);
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-center
// The flex item’s margin box is centered in the cross axis within the line.
case FlexBox::AlignItems::center:
return getStartMargin(Axis::cross, item) + (lineSize - getLockedSize(Axis::cross, item) - getStartMargin(Axis::cross, item) - getEndMargin(Axis::cross, item)) / 2;
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-stretch
case FlexBox::AlignItems::stretch:
return (Coord)getStartMargin(Axis::cross, item);
}
jassertfalse;
return 0.0;
}();
if (alignment == FlexBox::AlignItems::stretch)
{
auto newSize = isAssigned(getItemSize(Axis::cross, item)) ? computePreferredSize(Axis::cross, item)
: lineSize - getStartMargin(Axis::cross, item) - getEndMargin(Axis::cross, item);
if (isAssigned(getMaxSize(Axis::cross, item)))
newSize = jmin(newSize, (Coord)getMaxSize(Axis::cross, item));
if (isAssigned(getMinSize(Axis::cross, item)))
newSize = jmax(newSize, (Coord)getMinSize(Axis::cross, item));
getLockedSize(Axis::cross, item) = newSize;
}
}
}
}
void alignItemsByJustifyContent() noexcept
{
Coord additionalMarginRight = 0, additionalMarginLeft = 0;
recalculateTotalItemLengthPerLineArray();
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
Coord x = 0;
if (owner.justifyContent == FlexBox::JustifyContent::flexEnd)
{
x = containerLineLength - lineInfo[row].totalLength;
}
else if (owner.justifyContent == FlexBox::JustifyContent::center)
{
x = (containerLineLength - lineInfo[row].totalLength) / 2;
}
else if (owner.justifyContent == FlexBox::JustifyContent::spaceBetween)
{
additionalMarginRight = jmax(Coord(), (containerLineLength - lineInfo[row].totalLength) / jmax(1, numColumns - 1));
}
else if (owner.justifyContent == FlexBox::JustifyContent::spaceAround)
{
additionalMarginLeft = additionalMarginRight = jmax(Coord(), (containerLineLength - lineInfo[row].totalLength) / jmax(1, 2 * numColumns));
}
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
getStartLockedMargin(Axis::main, item) += additionalMarginLeft;
getEndLockedMargin(Axis::main, item) += additionalMarginRight;
item.item->currentBounds.setPosition(isRowDirection ? (float)(x + item.lockedMarginLeft)
: (float)item.lockedMarginLeft,
isRowDirection ? (float)item.lockedMarginTop
: (float)(x + item.lockedMarginTop));
x += getItemMainSize(item);
}
}
}
void layoutAllItems() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto lineY = lineInfo[row].lineY;
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isRowDirection)
item.item->currentBounds.setY((float)(lineY + item.lockedMarginTop));
else
item.item->currentBounds.setX((float)(lineY + item.lockedMarginLeft));
item.item->currentBounds.setSize((float)item.lockedWidth,
(float)item.lockedHeight);
}
}
reverseLocations();
reverseWrap();
}
private:
void resetRowItems(const int row) noexcept
{
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
resetItem(getItem(column, row));
}
void resetUnlockedRowItems(const int row) noexcept
{
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (!item.locked)
resetItem(item);
}
}
void resetItem(ItemWithState &item) noexcept
{
item.locked = false;
for (auto &axis : {Axis::main, Axis::cross})
getLockedSize(axis, item) = computePreferredSize(axis, item);
}
bool layoutRowItems(const int row) noexcept
{
const auto numColumns = lineInfo[row].numItems;
auto flexContainerLength = containerLineLength;
Coord totalItemsLength = 0, totalFlexGrow = 0, totalFlexShrink = 0;
for (int column = 0; column < numColumns; ++column)
{
const auto &item = getItem(column, row);
if (item.locked)
{
flexContainerLength -= getItemMainSize(item);
}
else
{
totalItemsLength += getItemMainSize(item);
totalFlexGrow += item.item->flexGrow;
totalFlexShrink += item.item->flexShrink;
}
}
Coord changeUnit = 0;
const auto difference = flexContainerLength - totalItemsLength;
const bool positiveFlexibility = difference > 0;
if (positiveFlexibility)
{
if (totalFlexGrow != 0.0)
changeUnit = difference / totalFlexGrow;
}
else
{
if (totalFlexShrink != 0.0)
changeUnit = difference / totalFlexShrink;
}
bool ok = true;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (!item.locked)
if (!addToItemLength(item, (positiveFlexibility ? item.item->flexGrow : item.item->flexShrink) * changeUnit, row))
ok = false;
}
return ok;
}
void recalculateTotalItemLengthPerLineArray() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
lineInfo[row].totalLength = 0;
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
lineInfo[row].totalLength += getItemMainSize(getItem(column, row));
}
}
void reverseLocations() noexcept
{
if (owner.flexDirection == FlexBox::Direction::rowReverse)
{
for (auto &item : owner.items)
item.currentBounds.setX((float)(containerLineLength - item.currentBounds.getRight()));
}
else if (owner.flexDirection == FlexBox::Direction::columnReverse)
{
for (auto &item : owner.items)
item.currentBounds.setY((float)(containerLineLength - item.currentBounds.getBottom()));
}
}
void reverseWrap() noexcept
{
if (owner.flexWrap == FlexBox::Wrap::wrapReverse)
{
if (isRowDirection)
{
for (auto &item : owner.items)
item.currentBounds.setY((float)(containerCrossLength - item.currentBounds.getBottom()));
}
else
{
for (auto &item : owner.items)
item.currentBounds.setX((float)(containerCrossLength - item.currentBounds.getRight()));
}
}
}
Coord getItemMainSize(const ItemWithState &item) const noexcept
{
return isRowDirection ? item.lockedWidth + item.lockedMarginLeft + item.lockedMarginRight
: item.lockedHeight + item.lockedMarginTop + item.lockedMarginBottom;
}
Coord getItemCrossSize(const ItemWithState &item) const noexcept
{
return isRowDirection ? item.lockedHeight + item.lockedMarginTop + item.lockedMarginBottom
: item.lockedWidth + item.lockedMarginLeft + item.lockedMarginRight;
}
bool addToItemLength(ItemWithState &item, const Coord length, int row) const noexcept
{
bool ok = false;
const auto prefSize = computePreferredSize(Axis::main, item);
const auto pickForMainAxis = [this](auto &a, auto &b) -> auto & { return pickForAxis(Axis::main, a, b); };
if (isAssigned(pickForMainAxis(item.item->maxWidth, item.item->maxHeight)) && pickForMainAxis(item.item->maxWidth, item.item->maxHeight) < prefSize + length)
{
pickForMainAxis(item.lockedWidth, item.lockedHeight) = pickForMainAxis(item.item->maxWidth, item.item->maxHeight);
item.locked = true;
}
else if (isAssigned(prefSize) && pickForMainAxis(item.item->minWidth, item.item->minHeight) > prefSize + length)
{
pickForMainAxis(item.lockedWidth, item.lockedHeight) = pickForMainAxis(item.item->minWidth, item.item->minHeight);
item.locked = true;
}
else
{
ok = true;
pickForMainAxis(item.lockedWidth, item.lockedHeight) = prefSize + length;
}
lineInfo[row].totalLength += pickForMainAxis(item.lockedWidth, item.lockedHeight) + pickForMainAxis(item.lockedMarginLeft, item.lockedMarginTop) + pickForMainAxis(item.lockedMarginRight, item.lockedMarginBottom);
return ok;
}
Coord computePreferredSize(Axis axis, ItemWithState &itemWithState) const noexcept
{
const auto &item = *itemWithState.item;
auto preferredSize = (item.flexBasis > 0 && axis == Axis::main) ? item.flexBasis
: (isAssigned(getItemSize(axis, itemWithState)) ? getItemSize(axis, itemWithState)
: getMinSize(axis, itemWithState));
const auto minSize = getMinSize(axis, itemWithState);
if (isAssigned(minSize) && preferredSize < minSize)
return minSize;
const auto maxSize = getMaxSize(axis, itemWithState);
if (isAssigned(maxSize) && maxSize < preferredSize)
return maxSize;
return preferredSize;
}
};
//==============================================================================
FlexBox::FlexBox() noexcept = default;
FlexBox::~FlexBox() noexcept = default;
FlexBox::FlexBox(JustifyContent jc) noexcept : justifyContent(jc) {}
FlexBox::FlexBox(Direction d, Wrap w, AlignContent ac, AlignItems ai, JustifyContent jc) noexcept
: flexDirection(d),
flexWrap(w),
alignContent(ac),
alignItems(ai),
justifyContent(jc)
{
}
void FlexBox::performLayout(Rectangle<float> targetArea)
{
if (!items.isEmpty())
{
FlexBoxLayoutCalculation layout(*this, targetArea.getWidth(), targetArea.getHeight());
layout.createStates();
layout.initialiseItems();
layout.resolveFlexibleLengths();
layout.resolveAutoMarginsOnMainAxis();
layout.calculateCrossSizesByLine();
layout.calculateCrossSizeOfAllItems();
layout.alignLinesPerAlignContent();
layout.resolveAutoMarginsOnCrossAxis();
layout.alignItemsInCrossAxisInLinesPerAlignSelf();
layout.alignItemsByJustifyContent();
layout.layoutAllItems();
for (auto &item : items)
{
item.currentBounds += targetArea.getPosition();
if (auto *comp = item.associatedComponent)
comp->setBounds(Rectangle<int>::leftTopRightBottom((int)item.currentBounds.getX(),
(int)item.currentBounds.getY(),
(int)item.currentBounds.getRight(),
(int)item.currentBounds.getBottom()));
if (auto *box = item.associatedFlexBox)
box->performLayout(item.currentBounds);
}
}
}
void FlexBox::performLayout(Rectangle<int> targetArea)
{
performLayout(targetArea.toFloat());
}
//==============================================================================
FlexItem::FlexItem() noexcept {}
FlexItem::FlexItem(float w, float h) noexcept : currentBounds(w, h), minWidth(w), minHeight(h) {}
FlexItem::FlexItem(float w, float h, Component &c) noexcept : FlexItem(w, h) { associatedComponent = &c; }
FlexItem::FlexItem(float w, float h, FlexBox &fb) noexcept : FlexItem(w, h) { associatedFlexBox = &fb; }
FlexItem::FlexItem(Component &c) noexcept : associatedComponent(&c) {}
FlexItem::FlexItem(FlexBox &fb) noexcept : associatedFlexBox(&fb) {}
FlexItem::Margin::Margin() noexcept : left(), right(), top(), bottom() {}
FlexItem::Margin::Margin(float v) noexcept : left(v), right(v), top(v), bottom(v) {}
FlexItem::Margin::Margin(float t, float r, float b, float l) noexcept : left(l), right(r), top(t), bottom(b) {}
//==============================================================================
FlexItem FlexItem::withFlex(float newFlexGrow) const noexcept
{
auto fi = *this;
fi.flexGrow = newFlexGrow;
return fi;
}
FlexItem FlexItem::withFlex(float newFlexGrow, float newFlexShrink) const noexcept
{
auto fi = withFlex(newFlexGrow);
fi.flexShrink = newFlexShrink;
return fi;
}
FlexItem FlexItem::withFlex(float newFlexGrow, float newFlexShrink, float newFlexBasis) const noexcept
{
auto fi = withFlex(newFlexGrow, newFlexShrink);
fi.flexBasis = newFlexBasis;
return fi;
}
FlexItem FlexItem::withWidth(float newWidth) const noexcept
{
auto fi = *this;
fi.width = newWidth;
return fi;
}
FlexItem FlexItem::withMinWidth(float newMinWidth) const noexcept
{
auto fi = *this;
fi.minWidth = newMinWidth;
return fi;
}
FlexItem FlexItem::withMaxWidth(float newMaxWidth) const noexcept
{
auto fi = *this;
fi.maxWidth = newMaxWidth;
return fi;
}
FlexItem FlexItem::withMinHeight(float newMinHeight) const noexcept
{
auto fi = *this;
fi.minHeight = newMinHeight;
return fi;
}
FlexItem FlexItem::withMaxHeight(float newMaxHeight) const noexcept
{
auto fi = *this;
fi.maxHeight = newMaxHeight;
return fi;
}
FlexItem FlexItem::withHeight(float newHeight) const noexcept
{
auto fi = *this;
fi.height = newHeight;
return fi;
}
FlexItem FlexItem::withMargin(Margin m) const noexcept
{
auto fi = *this;
fi.margin = m;
return fi;
}
FlexItem FlexItem::withOrder(int newOrder) const noexcept
{
auto fi = *this;
fi.order = newOrder;
return fi;
}
FlexItem FlexItem::withAlignSelf(AlignSelf a) const noexcept
{
auto fi = *this;
fi.alignSelf = a;
return fi;
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
class FlexBoxTests : public UnitTest
{
public:
FlexBoxTests() : UnitTest("FlexBox", UnitTestCategories::gui) {}
void runTest() override
{
using AlignSelf = FlexItem::AlignSelf;
using Direction = FlexBox::Direction;
const Rectangle<float> rect(10.0f, 20.0f, 300.0f, 200.0f);
const auto doLayout = [&rect](Direction direction, Array<FlexItem> items)
{
juce::FlexBox flex;
flex.flexDirection = direction;
flex.items = std::move(items);
flex.performLayout(rect);
return flex;
};
beginTest("flex item with mostly auto properties");
{
const auto test = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem{}.withAlignSelf(alignment)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f});
}
beginTest("flex item with specified width and height");
{
constexpr auto w = 50.0f;
constexpr auto h = 60.0f;
const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withWidth(w).withHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom() - h, w, h});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getY() + (rect.getHeight() - h) * 0.5f, w, h});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - w, rect.getY(), w, h});
test(Direction::column, AlignSelf::center, {rect.getX() + (rect.getWidth() - w) * 0.5f, rect.getY(), w, h});
}
beginTest("flex item with oversized width and height");
{
const auto w = rect.getWidth() * 2;
const auto h = rect.getHeight() * 2;
const auto test = [this, &doLayout, &w, &h](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withWidth(w).withHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
const Rectangle<float> baseRow(rect.getX(), rect.getY(), rect.getWidth(), h);
test(Direction::row, AlignSelf::autoAlign, baseRow);
test(Direction::row, AlignSelf::stretch, baseRow);
test(Direction::row, AlignSelf::flexStart, baseRow);
test(Direction::row, AlignSelf::flexEnd, baseRow.withBottomY(rect.getBottom()));
test(Direction::row, AlignSelf::center, baseRow.withCentre(rect.getCentre()));
const Rectangle<float> baseColumn(rect.getX(), rect.getY(), w, rect.getHeight());
test(Direction::column, AlignSelf::autoAlign, baseColumn);
test(Direction::column, AlignSelf::stretch, baseColumn);
test(Direction::column, AlignSelf::flexStart, baseColumn);
test(Direction::column, AlignSelf::flexEnd, baseColumn.withRightX(rect.getRight()));
test(Direction::column, AlignSelf::center, baseColumn.withCentre(rect.getCentre()));
}
beginTest("flex item with minimum width and height");
{
constexpr auto w = 50.0f;
constexpr auto h = 60.0f;
const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMinWidth(w).withMinHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, rect.getHeight()});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), w, rect.getHeight()});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom() - h, w, h});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getY() + (rect.getHeight() - h) * 0.5f, w, h});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), h});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), h});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - w, rect.getY(), w, h});
test(Direction::column, AlignSelf::center, {rect.getX() + (rect.getWidth() - w) * 0.5f, rect.getY(), w, h});
}
beginTest("flex item with maximum width and height");
{
constexpr auto w = 50.0f;
constexpr auto h = 60.0f;
const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMaxWidth(w).withMaxHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, h});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, h});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, 0.0f});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), w, 0.0f});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f});
}
beginTest("flex item with specified flex");
{
const auto test = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withFlex(1.0f)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), rect.getWidth(), 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, rect.getHeight()});
}
beginTest("flex item with margin");
{
const FlexItem::Margin margin(10.0f, 20.0f, 30.0f, 40.0f);
const auto test = [this, &doLayout, &margin](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin(margin)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
const auto remainingHeight = rect.getHeight() - margin.top - margin.bottom;
const auto remainingWidth = rect.getWidth() - margin.left - margin.right;
test(Direction::row, AlignSelf::autoAlign, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, remainingHeight});
test(Direction::row, AlignSelf::stretch, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, remainingHeight});
test(Direction::row, AlignSelf::flexStart, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX() + margin.left, rect.getBottom() - margin.bottom, 0.0f, 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX() + margin.left, rect.getY() + margin.top + remainingHeight * 0.5f, 0.0f, 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX() + margin.left, rect.getY() + margin.top, remainingWidth, 0.0f});
test(Direction::column, AlignSelf::stretch, {rect.getX() + margin.left, rect.getY() + margin.top, remainingWidth, 0.0f});
test(Direction::column, AlignSelf::flexStart, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, 0.0f});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - margin.right, rect.getY() + margin.top, 0.0f, 0.0f});
test(Direction::column, AlignSelf::center, {rect.getX() + margin.left + remainingWidth * 0.5f, rect.getY() + margin.top, 0.0f, 0.0f});
}
const AlignSelf alignments[]{AlignSelf::autoAlign,
AlignSelf::stretch,
AlignSelf::flexStart,
AlignSelf::flexEnd,
AlignSelf::center};
beginTest("flex item with auto margin");
{
for (const auto &alignment : alignments)
{
for (const auto &direction : {Direction::row, Direction::column})
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin((float)FlexItem::autoValue)});
expect(flex.items.getFirst().currentBounds == Rectangle<float>(rect.getCentre(), rect.getCentre()));
}
}
const auto testTop = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({(float)FlexItem::autoValue, 0.0f, 0.0f, 0.0f})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
for (const auto &alignment : alignments)
testTop(Direction::row, alignment, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
testTop(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f});
testTop(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f});
testTop(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
testTop(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getBottom(), 0.0f, 0.0f});
testTop(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getBottom(), 0.0f, 0.0f});
const auto testBottom = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, 0.0f, (float)FlexItem::autoValue, 0.0f})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
for (const auto &alignment : alignments)
testBottom(Direction::row, alignment, {rect.getX(), rect.getY(), 0.0f, 0.0f});
testBottom(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
testBottom(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
testBottom(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
testBottom(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
testBottom(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f});
const auto testLeft = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, 0.0f, 0.0f, (float)FlexItem::autoValue})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
testLeft(Direction::row, AlignSelf::autoAlign, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()});
testLeft(Direction::row, AlignSelf::stretch, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()});
testLeft(Direction::row, AlignSelf::flexStart, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
testLeft(Direction::row, AlignSelf::flexEnd, {rect.getRight(), rect.getBottom(), 0.0f, 0.0f});
testLeft(Direction::row, AlignSelf::center, {rect.getRight(), rect.getCentreY(), 0.0f, 0.0f});
for (const auto &alignment : alignments)
testLeft(Direction::column, alignment, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
const auto testRight = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, (float)FlexItem::autoValue, 0.0f, 0.0f})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
testRight(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
testRight(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
testRight(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
testRight(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
testRight(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f});
for (const auto &alignment : alignments)
testRight(Direction::column, alignment, {rect.getX(), rect.getY(), 0.0f, 0.0f});
}
beginTest("in a multiline layout, items too large to fit on the main axis are given a line to themselves");
{
const auto spacer = 10.0f;
for (const auto alignment : alignments)
{
juce::FlexBox flex;
flex.flexWrap = FlexBox::Wrap::wrap;
flex.items = {FlexItem().withAlignSelf(alignment).withWidth(spacer).withHeight(spacer),
FlexItem().withAlignSelf(alignment).withWidth(rect.getWidth() * 2).withHeight(rect.getHeight()),
FlexItem().withAlignSelf(alignment).withWidth(spacer).withHeight(spacer)};
flex.performLayout(rect);
expect(flex.items[0].currentBounds == Rectangle<float>(rect.getX(), rect.getY(), spacer, spacer));
expect(flex.items[1].currentBounds == Rectangle<float>(rect.getX(), rect.getY() + spacer, rect.getWidth(), rect.getHeight()));
expect(flex.items[2].currentBounds == Rectangle<float>(rect.getX(), rect.getBottom() + spacer, 10.0f, 10.0f));
}
}
}
};
static FlexBoxTests flexBoxTests;
#endif
} // namespace juce
| 46.563667
| 225
| 0.518887
|
dikadk
|
5c1d185ee8efa07f9a35db7b874ca2d7bd117211
| 483
|
cpp
|
C++
|
ZorkGame/ZorkGame/ZorkGame.cpp
|
PabloSanchezTrujillo/Zork
|
f861f56df8c37a126c9f90147efbc75c91a04f47
|
[
"MIT"
] | null | null | null |
ZorkGame/ZorkGame/ZorkGame.cpp
|
PabloSanchezTrujillo/Zork
|
f861f56df8c37a126c9f90147efbc75c91a04f47
|
[
"MIT"
] | null | null | null |
ZorkGame/ZorkGame/ZorkGame.cpp
|
PabloSanchezTrujillo/Zork
|
f861f56df8c37a126c9f90147efbc75c91a04f47
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "World.h"
using namespace std;
int main()
{
World* house = new World();
cout << "You are in the: " << house->getPlayer()->getLocation()->getName() << ". "
<< house->getPlayer()->getLocation()->getDescription() << endl;
cout << "\n";
// GameLoop
while(!house->getPlayer()->isPlayerOutside()) {
for(Entity* entity : house->getEntities()) {
entity->update();
}
}
cout << "The end." << endl;
cout << "\n";
system("pause");
return 0;
}
| 19.32
| 83
| 0.594203
|
PabloSanchezTrujillo
|
5c1dbca35795cb3a90df53cc6d6c751addffd42a
| 452
|
cpp
|
C++
|
misc.cpp
|
bannid/CardGame
|
c5df2adb7a96df506fa24544cd8499076bb3ebbc
|
[
"Zlib"
] | null | null | null |
misc.cpp
|
bannid/CardGame
|
c5df2adb7a96df506fa24544cd8499076bb3ebbc
|
[
"Zlib"
] | null | null | null |
misc.cpp
|
bannid/CardGame
|
c5df2adb7a96df506fa24544cd8499076bb3ebbc
|
[
"Zlib"
] | null | null | null |
#include "misc.h"
float LinearInterpolation(float first, float second, float weight){
float result = weight * second + (1.0f - weight) * first;
return result;
}
float CosineInterpolation(float first, float second, float weight){
float modifiedWeight = (1 - cos(weight * 3.14))/2.0f;
modifiedWeight = pow(modifiedWeight, 0.2f);
float result = modifiedWeight * second + (1.0f - modifiedWeight) * first;
return result;
}
| 28.25
| 78
| 0.679204
|
bannid
|
5c1dd2542f6af6e2d960967edc4454c44d4afaa9
| 4,650
|
cpp
|
C++
|
tests/core/RemoteNodeTest.cpp
|
cybergarage/round-cc
|
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
|
[
"BSD-3-Clause"
] | null | null | null |
tests/core/RemoteNodeTest.cpp
|
cybergarage/round-cc
|
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
|
[
"BSD-3-Clause"
] | null | null | null |
tests/core/RemoteNodeTest.cpp
|
cybergarage/round-cc
|
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
|
[
"BSD-3-Clause"
] | null | null | null |
/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <string.h>
#include <round/core/RemoteNode.h>
#include <round/Server.h>
#include "TestNode.h"
#include "TestServer.h"
using namespace std;
using namespace Round;
BOOST_AUTO_TEST_SUITE(node)
BOOST_AUTO_TEST_CASE(RoundRemoteNodeConstructorTest) {
for (int n = 0; n < 200; n+=10) {
stringstream addr;
addr << n << "." << n << "." << n << "." << n;
RemoteNode remoteNode(addr.str(), n);
Error error;
std::string remoteAddr;
BOOST_CHECK(remoteNode.getRequestAddress(&remoteAddr, &error));
BOOST_CHECK_EQUAL(addr.str().compare(remoteAddr), 0);
int remotePort;
BOOST_CHECK(remoteNode.getRequestPort(&remotePort, &error));
BOOST_CHECK_EQUAL(n, remotePort);
BOOST_CHECK_EQUAL(remoteNode.hasClusterName(), false);
}
}
BOOST_AUTO_TEST_CASE(RoundRemoteNodeCopyConstructorTest) {
for (int n = 0; n < 200; n+=10) {
stringstream addr;
addr << n << "." << n << "." << n << "." << n;
RemoteNode testNode(addr.str(), n);
RemoteNode remoteNode(&testNode);
Error error;
std::string remoteAddr;
BOOST_CHECK(remoteNode.getRequestAddress(&remoteAddr, &error));
BOOST_CHECK_EQUAL(addr.str().compare(remoteAddr), 0);
int remotePort;
BOOST_CHECK(remoteNode.getRequestPort(&remotePort, &error));
BOOST_CHECK_EQUAL(n, remotePort);
BOOST_CHECK_EQUAL(remoteNode.hasClusterName(), false);
}
}
BOOST_AUTO_TEST_CASE(RoundRemoteNodeSetterTest) {
for (int n = 0; n < 200; n+=10) {
RemoteNode remoteNode;
stringstream addr;
addr << n << "." << n << "." << n << "." << n;
BOOST_CHECK(remoteNode.setRequestAddress(addr.str()));
int port = n;
BOOST_CHECK(remoteNode.setRequestPort(port));
stringstream cluster;
cluster << "cluster" << n;
BOOST_CHECK(remoteNode.setClusterName(cluster.str()));
Error error;
std::string remoteAddr;
BOOST_CHECK(remoteNode.getRequestAddress(&remoteAddr, &error));
BOOST_CHECK_EQUAL(addr.str().compare(remoteAddr), 0);
int remotePort;
BOOST_CHECK(remoteNode.getRequestPort(&remotePort, &error));
BOOST_CHECK_EQUAL(port, remotePort);
std::string remoteCluster;
BOOST_CHECK(remoteNode.getClusterName(&remoteCluster, &error));
BOOST_CHECK_EQUAL(cluster.str().compare(remoteCluster), 0);
}
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(rpc)
BOOST_AUTO_TEST_CASE(RemoteNodeScriptManagerTest) {
Error err;
TestServer serverNode;
BOOST_CHECK(serverNode.start(&err));
std::string serverIp;
BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err));
int serverPort;
BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err));
RemoteNode node(serverIp, serverPort);
NodeTestController nodeTestController;
nodeTestController.runScriptManagerTest(&node);
BOOST_CHECK(serverNode.stop(&err));
}
BOOST_AUTO_TEST_CASE(RemoteNodeAliasManagerTest) {
Error err;
TestServer serverNode;
BOOST_CHECK(serverNode.start(&err));
std::string serverIp;
BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err));
int serverPort;
BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err));
RemoteNode node(serverIp, serverPort);
NodeTestController nodeTestController;
nodeTestController.runAliasManagerTest(&node);
BOOST_CHECK(serverNode.stop(&err));
}
BOOST_AUTO_TEST_CASE(RemoteNodeRouteManagerTest) {
Error err;
TestServer serverNode;
BOOST_CHECK(serverNode.start(&err));
std::string serverIp;
BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err));
int serverPort;
BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err));
RemoteNode node(serverIp, serverPort);
NodeTestController nodeTestController;
nodeTestController.runRouteManagerTest(&node);
BOOST_CHECK(serverNode.stop(&err));
}
BOOST_AUTO_TEST_CASE(RemoteNodeSystemMethodTest) {
Error err;
TestServer serverNode;
BOOST_CHECK(serverNode.start(&err));
std::string serverIp;
BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err));
int serverPort;
BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err));
RemoteNode node(serverIp, serverPort);
NodeTestController nodeTestController;
nodeTestController.runSystemMethodTest(&node);
BOOST_CHECK(serverNode.stop(&err));
}
BOOST_AUTO_TEST_SUITE_END()
| 25.690608
| 68
| 0.693763
|
cybergarage
|
5c201c7101b0d40c9e79c696d239e37debac77e5
| 826
|
cpp
|
C++
|
LeetCode/338.Counting_Bits.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 9
|
2017-10-08T16:22:03.000Z
|
2021-08-20T09:32:17.000Z
|
LeetCode/338.Counting_Bits.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | null | null | null |
LeetCode/338.Counting_Bits.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 2
|
2018-01-15T16:35:44.000Z
|
2019-03-21T18:30:04.000Z
|
class Solution {
public:
vector<int> countBits(int num) {
vector<int>ans;
int two[30];
int now;
int SIZE = 30;
two[0] = 1;
for(int i = 1; i < SIZE; i++)
two[i] = two[i - 1] * 2;
ans.push_back(0);
if(num == 0) return ans;
ans.push_back(1);
if(num == 1) return ans;
for(int i = 2; i <= num; i++) {
bool flag = false;
for(int j = 0; j < SIZE; j++) {
if(two[j] == i) {
ans.push_back(1);
flag = true;
break;
} else if(i > two[j]) {
now = two[j];
}
}
if(!flag) ans.push_back(ans[i - now] + 1);
}
return ans;
}
};
| 25.030303
| 54
| 0.349879
|
w181496
|
5c2593ad5f628d6b76fbef2e0291fcc06a85e5bd
| 618
|
cxx
|
C++
|
phys-services/private/phys-services/I3FileOMKey2MBIDFactory.cxx
|
hschwane/offline_production
|
e14a6493782f613b8bbe64217559765d5213dc1e
|
[
"MIT"
] | 1
|
2020-12-24T22:00:01.000Z
|
2020-12-24T22:00:01.000Z
|
phys-services/private/phys-services/I3FileOMKey2MBIDFactory.cxx
|
hschwane/offline_production
|
e14a6493782f613b8bbe64217559765d5213dc1e
|
[
"MIT"
] | null | null | null |
phys-services/private/phys-services/I3FileOMKey2MBIDFactory.cxx
|
hschwane/offline_production
|
e14a6493782f613b8bbe64217559765d5213dc1e
|
[
"MIT"
] | 3
|
2020-07-17T09:20:29.000Z
|
2021-03-30T16:44:18.000Z
|
#include "phys-services/I3FileOMKey2MBIDFactory.h"
#include "phys-services/I3FileOMKey2MBID.h"
I3_SERVICE_FACTORY(I3FileOMKey2MBIDFactory);
I3FileOMKey2MBIDFactory::I3FileOMKey2MBIDFactory(const I3Context& context)
: I3ServiceFactory(context)
{
AddParameter("Infile",
"The file to read the OMKey to MBID conversions",
infile_);
}
bool
I3FileOMKey2MBIDFactory::InstallService(I3Context& services)
{
if(!service_)
service_ = I3OMKey2MBIDPtr ( new I3FileOMKey2MBID(infile_));
return services.Put(service_);
}
void I3FileOMKey2MBIDFactory::Configure()
{
GetParameter("Infile",infile_);
}
| 23.769231
| 74
| 0.770227
|
hschwane
|
5c26e96cdadb3a82867cfd4e722783b4e51e1851
| 4,730
|
cpp
|
C++
|
Test/NfcCxTests/Simulation/NciHciDataPacket.cpp
|
Bhaskers-Blu-Org2/NFC-Class-Extension-Driver
|
77c80d6d2c8f7876e68e3df847a926a045d81711
|
[
"MIT"
] | 32
|
2015-11-19T07:23:11.000Z
|
2019-04-08T18:50:08.000Z
|
Test/NfcCxTests/Simulation/NciHciDataPacket.cpp
|
Bhaskers-Blu-Org2/NFC-Class-Extension-Driver
|
77c80d6d2c8f7876e68e3df847a926a045d81711
|
[
"MIT"
] | 33
|
2015-11-12T08:23:52.000Z
|
2018-12-06T02:34:07.000Z
|
Test/NfcCxTests/Simulation/NciHciDataPacket.cpp
|
Microsoft/NFC-Class-Extension-Driver
|
77c80d6d2c8f7876e68e3df847a926a045d81711
|
[
"MIT"
] | 28
|
2015-08-11T14:34:10.000Z
|
2018-07-26T14:15:53.000Z
|
//
// Copyright (c) Microsoft Corporation. All Rights Reserved
//
#include "Precomp.h"
#include <array>
#include "NciHciDataPacket.h"
NciHciDataPacket::NciHciDataPacket(
_In_ uint8_t connectionId,
_In_ uint8_t pipeId,
_In_ phHciNfc_MsgType_t messageType,
_In_ uint8_t instruction,
_In_ std::initializer_list<uint8_t> payload)
:
NciHciDataPacket(connectionId, pipeId, messageType, instruction, payload.begin(), uint8_t(payload.size()), true)
{
}
NciHciDataPacket::NciHciDataPacket(
_In_ uint8_t connectionId,
_In_ uint8_t pipeId,
_In_ phHciNfc_MsgType_t messageType,
_In_ uint8_t instruction,
_In_ std::initializer_list<uint8_t> payload,
_In_ bool finalPacket)
:
NciHciDataPacket(connectionId, pipeId, messageType, instruction, payload.begin(), uint8_t(payload.size()), finalPacket)
{
}
NciHciDataPacket::NciHciDataPacket(
_In_ uint8_t connectionId,
_In_ uint8_t pipeId,
_In_ phHciNfc_MsgType_t messageType,
_In_ uint8_t instruction,
_In_reads_(payloadLength) const uint8_t* payload,
_In_ uint8_t payloadLength,
_In_ bool finalPacket)
:
NciDataPacket(connectionId, GenerateFirstPacket(pipeId, messageType, instruction, payload, payloadLength, finalPacket).data(), CalculateFirstPacketLength(payloadLength), true)
{
}
NciHciDataPacket::NciHciDataPacket(
_In_ uint8_t connectionId,
_In_ uint8_t pipeId,
_In_ std::initializer_list<uint8_t> payload)
:
NciHciDataPacket(connectionId, pipeId, payload.begin(), uint8_t(payload.size()), true)
{
}
NciHciDataPacket::NciHciDataPacket(
_In_ uint8_t connectionId,
_In_ uint8_t pipeId,
_In_ std::initializer_list<uint8_t> payload,
_In_ bool finalPacket)
:
NciHciDataPacket(connectionId, pipeId, payload.begin(), uint8_t(payload.size()), finalPacket)
{
}
NciHciDataPacket::NciHciDataPacket(
_In_ uint8_t connectionId,
_In_ uint8_t pipeId,
_In_reads_(payloadLength) const uint8_t* payload,
_In_ uint8_t payloadLength,
_In_ bool finalPacket)
:
NciDataPacket(connectionId, GenerateSubsequentPacket(pipeId, payload, payloadLength, finalPacket).data(), CalculateSubsequentPacketLength(payloadLength), true)
{
}
constexpr uint8_t
NciHciDataPacket::GenerateHcpHeader(bool isFinalPacket, uint8_t pipeId)
{
// ETSI Host Controller Interface (HCI), Version 12.1.0, Section 5.1, HCP packets
constexpr uint8_t chainBit = 0x80; // bit 8
constexpr uint8_t instructionMask = 0x7F; // bits [0,7]
return (isFinalPacket ? chainBit : 0x00) |
(pipeId & instructionMask);
}
std::array<uint8_t, NciPacketRaw::MaxPayloadLength>
NciHciDataPacket::GenerateFirstPacket(
_In_ uint8_t pipeId,
_In_ phHciNfc_MsgType_t messageType,
_In_ uint8_t instruction,
_In_reads_(payloadLength) const uint8_t* payload,
_In_ uint8_t payloadLength,
_In_ bool finalPacket)
{
std::array<uint8_t, NciPacketRaw::MaxPayloadLength> packet = {};
// Add HCP packet header
packet[0] = GenerateHcpHeader(finalPacket, pipeId);
// Add HCP message header
// ETSI Host Controller Interface (HCI), Version 12.1.0, Section 5.2, HCP message structure
constexpr uint8_t messageTypeBitShift = 6;
constexpr uint8_t messageTypeBitMask = 0xC0; // bits [7,8]
constexpr uint8_t instructionBitMask = 0x3F; // bits [0,6]
packet[1] = ((messageType << messageTypeBitShift) & messageTypeBitMask) |
(instruction & instructionBitMask);
// Ensure HCI payload isn't too big.
if (payloadLength > NciHciDataPacket::MaxFirstPayloadSize)
{
throw std::exception("NciHciDataPacket payload is too big.");
}
// Copy payload.
std::copy(payload, payload + payloadLength, packet.data() + 2);
return packet;
}
constexpr uint8_t
NciHciDataPacket::CalculateFirstPacketLength(uint8_t payloadLength)
{
return payloadLength + 2; // Add 2 bytes for HCP header + HCP message header
}
std::array<uint8_t, NciPacketRaw::MaxPayloadLength>
NciHciDataPacket::GenerateSubsequentPacket(
_In_ uint8_t pipeId,
_In_reads_(payloadLength) const uint8_t* payload,
_In_ uint8_t payloadLength,
_In_ bool finalPacket)
{
std::array<uint8_t, NciPacketRaw::MaxPayloadLength> packet = {};
// Add HCP packet header
packet[0] = GenerateHcpHeader(finalPacket, pipeId);
if (payloadLength > NciHciDataPacket::MaxSubsequentPayloadSize)
{
throw std::exception("NciHciDataPacket payload is too big.");
}
std::copy(payload, payload + payloadLength, packet.data() + 1);
return packet;
}
constexpr uint8_t
NciHciDataPacket::CalculateSubsequentPacketLength(uint8_t payloadLength)
{
return payloadLength + 1; // Add 1 byte for HCP header
}
| 30.915033
| 179
| 0.734672
|
Bhaskers-Blu-Org2
|
5c271252cbafd78ad5faa7c1951f52283703ad04
| 3,350
|
hpp
|
C++
|
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
|
voxie-viewer/voxie
|
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
|
[
"MIT"
] | 4
|
2016-06-03T18:41:43.000Z
|
2020-04-17T20:28:58.000Z
|
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
|
voxie-viewer/voxie
|
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
|
[
"MIT"
] | null | null | null |
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
|
voxie-viewer/voxie
|
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2014-2022 The Voxie Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <VoxieClient/DBusUtil.hpp>
#include <QtDBus/QDBusArgument>
#include <QtDBus/QDBusVariant>
namespace vx {
namespace DBusNumericUtilIntern {
template <typename ValueType, typename ResultType>
bool dbusTryGetNumberFromArgumentValue(const QDBusArgument& arg,
ResultType& result) {
if (dbusGetSignature<ValueType>() == dbusGetArgumentSignature(arg)) {
result =
static_cast<ResultType>(dbusGetArgumentValueUnchecked<ValueType>(arg));
return true;
} else {
return false;
}
}
template <typename ValueType, typename ResultType>
bool dbusTryGetNumber(const QVariant& var, ResultType& result) {
if (var.userType() == qMetaTypeId<QDBusArgument>()) {
QDBusArgument arg = var.value<QDBusArgument>();
return dbusTryGetNumberFromArgumentValue<ValueType>(arg, result);
} else if (var.userType() == qMetaTypeId<ValueType>()) {
result = static_cast<ResultType>(var.value<ValueType>());
return true;
} else {
return false;
}
}
} // namespace DBusNumericUtilIntern
// Helper function for extracting any-type numbers from DBus variants and
// converting them to the desired target type
template <typename T>
T dbusGetNumber(const QDBusVariant& variant) {
using namespace DBusNumericUtilIntern;
QVariant qVariant = variant.variant();
T result = T();
// Try every numeric type
bool success = dbusTryGetNumber<double>(qVariant, result) ||
dbusTryGetNumber<qint64>(qVariant, result) ||
dbusTryGetNumber<quint64>(qVariant, result) ||
dbusTryGetNumber<qint32>(qVariant, result) ||
dbusTryGetNumber<quint32>(qVariant, result) ||
dbusTryGetNumber<qint16>(qVariant, result) ||
dbusTryGetNumber<quint16>(qVariant, result) ||
dbusTryGetNumber<quint8>(qVariant, result) ||
dbusTryGetNumber<bool>(qVariant, result);
if (success) {
return result;
} else {
throw Exception(
"de.uni_stuttgart.Voxie.Error",
QString() + "Unexpected DBus variant, expected a numeric type, got " +
QMetaType::typeName(qVariant.userType()));
}
}
} // namespace vx
| 36.413043
| 80
| 0.702687
|
voxie-viewer
|