hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
bca410e19d825d674530aa5860e7ab881d68aec4
10,594
cpp
C++
CUDA/CudaDeviceInfo/cudadeviceinfo.cpp
nicolasrosa/StereoVision
16f042258846a9a098888553d45e7bf3485edbae
[ "MIT" ]
9
2016-04-06T02:48:16.000Z
2021-01-29T23:11:05.000Z
CUDA/CudaDeviceInfo/cudadeviceinfo.cpp
nicolasrosa/StereoVision
16f042258846a9a098888553d45e7bf3485edbae
[ "MIT" ]
null
null
null
CUDA/CudaDeviceInfo/cudadeviceinfo.cpp
nicolasrosa/StereoVision
16f042258846a9a098888553d45e7bf3485edbae
[ "MIT" ]
3
2017-01-11T16:34:35.000Z
2019-08-27T15:50:30.000Z
#include "opencv2/opencv.hpp" #include "opencv2/core/cuda.hpp" #include <iostream> using namespace std; using namespace cv; /* @ function main */ int main( int argc, char *argv[] ) { // CUDA device count int nDeviceCount = 0; nDeviceCount = cuda::getCudaEnabledDeviceCount(); // CUDA device index int nCurrentDeviceIndex = 0; nCurrentDeviceIndex = cuda::getDevice(); // CUDA device info cuda::DeviceInfo deviceInfo = cuda::DeviceInfo( nCurrentDeviceIndex ); // CUDA device name const char* deviceName = deviceInfo.name(); // global memory available on device in bytes const size_t deviceTotalGlobMem = deviceInfo.totalGlobalMem(); // shared memory available per block in bytes const size_t deviceSharedMemPerBlock = deviceInfo.sharedMemPerBlock(); // 32-bit registers available per block const int nDeviceegsPerBlock = deviceInfo.regsPerBlock(); // warp size in threads const int nDeviceWarpSize = deviceInfo.warpSize(); // maximum pitch in bytes allowed by memory copies const size_t deviceMemPitch = deviceInfo.memPitch(); // maximum threads per block int nMaxThreadPerBlock = deviceInfo.maxThreadsPerBlock(); // maximum size of each dimension of a block const Vec3i deviceMaxThreadsDim = deviceInfo.maxThreadsDim(); // maximum size of each dimension of a grid const Vec3i deviceMaxGridSize = deviceInfo.maxGridSize(); // clock frequency in kilohertz const int nDeviceClockRate = deviceInfo.clockRate(); // constant memory available on device in bytes const size_t deviceTotalConstMem = deviceInfo.totalConstMem(); // major compute capability const int nDeiveMajorVersion = deviceInfo.majorVersion(); // minor compute capability const int nDeiveMinorVersion = deviceInfo.minorVersion(); // pitch alignment requirement for texture references bound to pitched memory const size_t devicetexturePitchAlignment = deviceInfo.texturePitchAlignment(); // number of multiprocessors on device const int nDeviceMultiProcessorCount = deviceInfo.multiProcessorCount(); // specified whether there is a run time limit on kernels const bool bKernelExecTimeoutEnabled = deviceInfo.kernelExecTimeoutEnabled(); string tmp1 = bKernelExecTimeoutEnabled ? "true" : "false"; // device is integrated as opposed to discrete const bool bIDeviceIntegrated = deviceInfo.integrated(); string tmp2 = bIDeviceIntegrated? "true" : "false"; // device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer const bool bCanMapHostMemory = deviceInfo.canMapHostMemory(); string tmp3 = bCanMapHostMemory? "true" : "false"; // maximum 1D texture size const int nMaxTex1D = deviceInfo.maxTexture1D(); // maximum 1D mipmapped texture size const int nMaxTexture1DMipmap = deviceInfo.maxTexture1DMipmap(); // maximum size for 1D textures bound to linear memory const int nMaxTexture1DLinear = deviceInfo.maxTexture1DLinear(); // maximum 2D texture dimensions const Vec2i deviceMaxTex2D = deviceInfo.maxTexture2D(); // maximum 2D mipmapped texture dimensions const Vec2i deviceMaxTex2DMipmap = deviceInfo.maxTexture2DMipmap(); // maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory const Vec3i deviceMaxTex2DLinear = deviceInfo.maxTexture2DLinear(); // maximum 2D texture dimensions if texture gather operations have to be performed const Vec2i deviceMaxTex2DGather = deviceInfo.maxTexture2DGather(); // maximum 3D texture dimensions const Vec3i deviceMaxTex3D = deviceInfo.maxTexture3D(); // maximum Cubemap texture dimensions const int deviceMaximumTexCubemap = deviceInfo.maxTextureCubemap(); // maximum 1D layered texture dimensions const Vec2i deviceMaxTex1DLayered = deviceInfo.maxTexture1DLayered(); // maximum 2D layered texture dimensions const Vec3i deviceMaxTex2DLayered = deviceInfo.maxTexture2DLayered(); // maximum Cubemap layered texture dimensions const Vec2i deviceMaxTexCubemapLayered = deviceInfo.maxTextureCubemapLayered(); // maximum 1D surface size const int deviceMaxSurface1D = deviceInfo.maxSurface1D(); // maximum 2D surface dimensions const Vec2i deviceMaxSurface2D = deviceInfo.maxSurface2D(); // maximum 3D surface dimensions const Vec3i deviceMaxSurface3D = deviceInfo.maxSurface3D(); // maximum 1D layered surface dimensions const Vec2i deviceMaxSurf1DLayered = deviceInfo.maxSurface1DLayered(); // maximum 2D layered surface dimensions const Vec3i deviceMaxSurf2DLayered = deviceInfo.maxSurface2DLayered(); // maximum Cubemap surface dimensions const int deviceMaxSurfCubemap = deviceInfo.maxSurfaceCubemap(); // maximum Cubemap layered surface dimensions const Vec2i deviceMaxSurfCubemapLayered = deviceInfo.maxSurfaceCubemapLayered(); // alignment requirements for surfaces const size_t deviceSurfAlignment = deviceInfo.surfaceAlignment(); // device can possibly execute multiple kernels concurrently const bool bConKernels = deviceInfo.concurrentKernels(); string tmp4 = bConKernels? "true" : "false"; // device has ECC support enabled const bool bECCEnabled = deviceInfo.ECCEnabled(); string tmp5 = bECCEnabled? "true" : "false"; // PCI bus ID of the device const int devicePciBusId = deviceInfo.pciBusID(); // PCI device ID of the device const int devicePciDeviceId = deviceInfo.pciDeviceID(); // PCI domain ID of the device const int devicePciDomainId = deviceInfo.pciDomainID(); // true if device is a Tesla device using TCC driver, false otherwise const bool deviceTccDriver = deviceInfo.tccDriver(); // number of asynchronous engines const int deviceAsyncEngineCount = deviceInfo.asyncEngineCount(); // device shares a unified address space with the host const bool bUnifiedAddressing = deviceInfo.unifiedAddressing(); string tmp6 = bUnifiedAddressing? "true" : "false"; // peak memory clock frequency in kilohertz const int deviceMemClockRate = deviceInfo.memoryClockRate(); // global memory bus width in bits const int deviceMemBusWidth = deviceInfo.memoryBusWidth(); // size of L2 cache in bytes const int deviceL2CacheSize = deviceInfo.l2CacheSize(); // maximum resident threads per multiprocessor const int deviceMaxThreadsPerMultiProcessor = deviceInfo.maxThreadsPerMultiProcessor(); // checks whether the CUDA module can be run on the given device const bool bIsCompatible = deviceInfo.isCompatible(); string tmp7 = bIsCompatible? "true" : "false"; // print the results cout << "CUDA Enabled Device Count: " << nDeviceCount << endl; cout << "CUDA Device Index: " << nCurrentDeviceIndex << endl; cout << "Device Name: " << deviceName << endl; cout << "Device Total Global Memory: " << deviceTotalGlobMem << endl; cout << "Device Shared Memory Per Block: " << deviceSharedMemPerBlock << endl; cout << "Device Registry Per BlocK: " << nDeviceegsPerBlock << endl; cout << "Device Warp Size: " << nDeviceWarpSize << endl; cout << "Device Memory Pitch: " << deviceMemPitch << endl; cout << "Maximum Threads Per Block: " << nMaxThreadPerBlock << endl; cout << "Maximum Threads Dimension: " << deviceMaxThreadsDim << endl; cout << "Maximum Grid Size: " << deviceMaxGridSize << endl; cout << "Device Clock Rate: " << nDeviceClockRate << endl; cout << "Device Total Constant Memory: " << deviceTotalConstMem << endl; cout << "Device Major Version: " << nDeiveMajorVersion << endl; cout << "Device Minor Version: " << nDeiveMinorVersion << endl; cout << "Device Texture Pitch Alignment: " << devicetexturePitchAlignment << endl; cout << "Device Multi Processor Count: " << nDeviceMultiProcessorCount << endl; cout << "Device Kernel Execution Timeout Enabled?: " << tmp1 << endl; cout << "Device Integrated?: " << tmp2 << endl; cout << "Device Can Map Host Memory?: " << tmp3 << endl; cout << "Device Maximum Texture 1D: " << nMaxTex1D << endl; cout << "Device maximum Texture 1D Mipmap: " << nMaxTexture1DMipmap << endl; cout << "Device Maximum Texture 1D Linear: " << nMaxTexture1DLinear << endl; cout << "Device Maximum Texture 2D: " << deviceMaxTex2D << endl; cout << "Device Maximum Texture 2D Mipmap: " << deviceMaxTex2DMipmap << endl; cout << "Device Maximum Texture 2D Linear: " << deviceMaxTex2DLinear << endl; cout << "Device Maximum Texutre 2D Gather: " << deviceMaxTex2DGather << endl; cout << "Device Maximum Texture 3D: " << deviceMaxTex3D << endl; cout << "Device Maximum Texture Cubemap: " << deviceMaximumTexCubemap << endl; cout << "Device Maximum Texture 1D Layered: " << deviceMaxTex1DLayered << endl; cout << "Device Maximum Texture 2D Layered: " << deviceMaxTex2DLayered << endl; cout << "Device Maximum Texture Cubemap Layered: " << deviceMaxTexCubemapLayered << endl; cout << "Device Maximum Surface 1D: " << deviceMaxSurface1D << endl; cout << "Device Maximum Surface 2D: " << deviceMaxSurface2D << endl; cout << "Device Maximum Surface 3D: " << deviceMaxSurface3D << endl; cout << "Device Maximum Surface 1D Layered: " << deviceMaxSurf1DLayered << endl; cout << "Device Maximum Surface 2D Layered: " << deviceMaxSurf2DLayered << endl; cout << "Device Maximum Surface Cubemap: " << deviceMaxSurfCubemap << endl; cout << "Device Maximum Surface Cubemap Layered: " << deviceMaxSurfCubemapLayered << endl; cout << "Device Surfce Alignment: " << deviceSurfAlignment << endl; cout << "Concurrent Kernels?: " << tmp4 << endl; cout << "ECC Enabled?: " << tmp5 << endl; cout << "Device PCI Bus ID: " << devicePciBusId << endl; cout << "Device PCI Device ID: " << devicePciDeviceId << endl; cout << "Device PCI Domain ID: " << devicePciDomainId << endl; cout << "Device TCC Driver: " << deviceTccDriver << endl; cout << "Device Async Engine Count: " << deviceAsyncEngineCount << endl; cout << "Device Unified Addressing?: " << tmp6 << endl; cout << "Device Memory Clock Rate: " << deviceMemClockRate << endl; cout << "Device Memory Bus Width: " << deviceMemBusWidth << endl; cout << "Device L2 Cache Size: " << deviceL2CacheSize << endl; cout << "Device Maximum Threads Per Multi Processor: " << deviceMaxThreadsPerMultiProcessor << endl; cout << "Is Compatible?: " << tmp7 << endl; return 0; }
43.958506
104
0.709741
[ "3d" ]
bca9b99272cdc3523aaeaa2b336cb06bcef800a9
7,657
cpp
C++
OilSpillage/UI/Elements/ItemSelector.cpp
Xemrion/Exam-work
7243f8db9951a0cdaebcfb5804df737a4d795b10
[ "Apache-2.0" ]
3
2020-04-25T22:23:07.000Z
2022-03-03T17:44:00.000Z
OilSpillage/UI/Elements/ItemSelector.cpp
Xemrion/Exam-work
7243f8db9951a0cdaebcfb5804df737a4d795b10
[ "Apache-2.0" ]
null
null
null
OilSpillage/UI/Elements/ItemSelector.cpp
Xemrion/Exam-work
7243f8db9951a0cdaebcfb5804df737a4d795b10
[ "Apache-2.0" ]
null
null
null
#include "ItemSelector.h" #include "../../game.h" #include "../UserInterface.h" Vector2 ItemSelector::size = Vector2(736, 192); void ItemSelector::addTextbox() { int selectedIndex = this->selectedIndex[this->selectedType] - this->startIndex[this->selectedType]; Container::Slot* slot = Container::playerInventory->getItemSlot(static_cast<ItemType>(this->selectedType), this->selectedIndex[this->selectedType]); this->textBox = std::make_unique<TextBox>("-- " + slot->getItem()->getName() + " --\n" + slot->getItem()->getDescription(), Color(Colors::White), Vector2(), ArrowPlacement::BOTTOM); this->textBox->setPosition(this->position + Vector2(145.0f + 96.0f * selectedIndex - this->textBox->getSize().x * 0.5f, -this->textBox->getSize().y + 40.0f)); } ItemSelector::ItemSelector(Vector2 position) : Element(position), drawTextBox(true), used(nullptr), selectedTypeLastDraw(-1), selectedIndexLastDraw(-1), startIndexLastDraw(-1), selectedType(0), selectedIndex{ 0 }, startIndex{ 0 }, transforms{ Matrix() }, rotationTimers{ 0 } { Game::getGraphics().loadTexture("UI/itemSelectorBG"); Game::getGraphics().loadTexture("UI/itemSelectorIndicator"); this->textureBG = Game::getGraphics().getTexturePointer("UI/itemSelectorBG"); this->textureIndicator = Game::getGraphics().getTexturePointer("UI/itemSelectorIndicator"); assert(textureBG && "Texture failed to load!"); assert(textureIndicator && "Texture failed to load!"); } ItemSelector::~ItemSelector() { } void ItemSelector::draw(bool selected) { UserInterface::getSpriteBatch()->Draw(this->textureBG->getShaderResView(), this->position); UserInterface::getSpriteBatch()->Draw(this->textureIndicator->getShaderResView(), this->position + Vector2(96.0f + 96.0f * (this->selectedIndex[this->selectedType] - this->startIndex[this->selectedType]), 47.0f)); std::vector<Container::Slot*>* list = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType)); for (int i = 0; i < Slots::SIZEOF && list->size() > 0; i++) { if (this->used[i] == nullptr) continue; for (int j = 0; j < min(list->size() - this->startIndex[this->selectedType], ItemSelector::tileLength); j++) { if (this->used[i] == list->at(this->startIndex[this->selectedType] + j)) { UserInterface::getFontArial()->DrawString(UserInterface::getSpriteBatch(), "Used", this->position + Vector2(145.0f + 96.0f * j, 128.0f), Colors::White, 0.0f, Vector2::Zero, 0.2f); } } } if (this->textBox && this->drawTextBox) { this->textBox->draw(false); } } void ItemSelector::update(float deltaTime) { std::vector<Container::Slot*>* list = nullptr; if (this->selectedTypeLastDraw == -1 && Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType))->size() > 0) { this->addTextbox(); } if (this->selectedTypeLastDraw != this->selectedType || this->startIndexLastDraw != this->startIndex[this->selectedType]) { if (this->selectedTypeLastDraw != -1) { list = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedTypeLastDraw)); for (int i = 0; i < min(list->size() - this->startIndexLastDraw, ItemSelector::tileLength); i++) { GameObject* object = list->at(this->startIndexLastDraw + i)->getItem()->getObject(); if (object) { Game::getGraphics().removeFromUIDraw(object, &transforms[i]); } } } list = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType)); for (int i = 0; i < min(list->size() - this->startIndex[this->selectedType], ItemSelector::tileLength); i++) { GameObject* object = list->at(this->startIndex[this->selectedType] + i)->getItem()->getObject(); if (object) { rotationTimers[i] = 190 * XM_PI/180; rotation[i] = Quaternion::CreateFromYawPitchRoll(XM_PI+ 0.3f, 0.26f, 0.0f); transforms[i] = Item::generateTransform(object, this->position + Vector2(145.0f + 96.0f * i, 140.0f)); Game::getGraphics().addToUIDraw(object, &transforms[i]); } } } int selectedIndex = this->selectedIndex[this->selectedType] - this->startIndex[this->selectedType]; list = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType)); for (int i = 0; i < min(list->size(), ItemSelector::tileLength); i++) { GameObject* object = list->at(this->startIndex[this->selectedType] + i)->getItem()->getObject(); if (object == nullptr) continue; if (i == selectedIndex) { rotationTimers[i] = std::fmodf(rotationTimers[i] + deltaTime * 4, XM_2PI); rotation[i] = Quaternion::Slerp(rotation[i], Quaternion::CreateFromYawPitchRoll(rotationTimers[i],0,0), deltaTime * 10); transforms[i] = Item::generateTransform(object, this->position + Vector2(145.0f + 96.0f * i, 140.0f), Vector3(1.5f), rotation[i], true); Game::getGraphics().setSelectedUI(object,&transforms[i]); } else { rotationTimers[i] = Game::lerp(rotationTimers[i], 190 * XM_PI / 180, deltaTime * 4); rotation[i] = Quaternion::Slerp(rotation[i], Quaternion::CreateFromYawPitchRoll(XM_PI + 0.3f, 0.26f, 0.0f), deltaTime * 4); transforms[i] = Item::generateTransform(object, this->position + Vector2(145.0f + 96.0f * i, 140.0f), Vector3(1.5f), rotation[i],true); } } this->selectedTypeLastDraw = this->selectedType; this->selectedIndexLastDraw = this->selectedIndex[this->selectedType]; this->startIndexLastDraw = this->startIndex[this->selectedType]; } void ItemSelector::setDrawTextBox(bool value) { this->drawTextBox = value; } void ItemSelector::changeSelectedType(bool down) { if (down) { this->selectedType = (this->selectedType + 1) % ItemType::TYPES_SIZEOF; } else { this->selectedType = (this->selectedType - 1 + ItemType::TYPES_SIZEOF) % ItemType::TYPES_SIZEOF; } int listSize = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType))->size(); if (listSize > 0) { this->addTextbox(); } else { this->textBox.reset(); } } void ItemSelector::changeSelectedIndex(bool right) { int listSize = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType))->size(); if (listSize == 0) { this->selectedIndex[this->selectedType] = 0; return; } if (right) { this->selectedIndex[this->selectedType] = (this->selectedIndex[this->selectedType] + 1) % listSize; } else { this->selectedIndex[this->selectedType] = (this->selectedIndex[this->selectedType] - 1 + listSize) % listSize; } if (this->selectedIndex[this->selectedType] < this->startIndex[this->selectedType]) { this->startIndex[this->selectedType] = this->selectedIndex[this->selectedType]; } else if (this->selectedIndex[this->selectedType] >= this->startIndex[this->selectedType] + ItemSelector::tileLength) { this->startIndex[this->selectedType] = this->selectedIndex[this->selectedType] - (ItemSelector::tileLength - 1); } this->addTextbox(); } ItemType ItemSelector::getSelectedType() const { return static_cast<ItemType>(this->selectedType); } Container::Slot* ItemSelector::getSelectedSlot() const { return Container::playerInventory->getItemSlot(static_cast<ItemType>(this->selectedType), this->selectedIndex[this->selectedType]); } bool ItemSelector::isSelectedValid() const { int listSize = Container::playerInventory->getItemStack(static_cast<ItemType>(this->selectedType))->size(); return this->selectedIndex[this->selectedType] >= 0 && this->selectedIndex[this->selectedType] < listSize; } void ItemSelector::setUsed(Container::Slot** used) { this->used = used; } void ItemSelector::unloadTextures() { Game::getGraphics().unloadTexture("UI/itemSelectorBG"); Game::getGraphics().unloadTexture("UI/itemSelectorIndicator"); }
36.8125
274
0.709024
[ "object", "vector" ]
bcb34f451937f0899045aee6466bf6b63e9c6d54
553
cpp
C++
ZeroEngine/Bullet.cpp
bamtoll09/GROWN
0f2098bce97a739f9b786d487136aa44f1b6a227
[ "MIT" ]
null
null
null
ZeroEngine/Bullet.cpp
bamtoll09/GROWN
0f2098bce97a739f9b786d487136aa44f1b6a227
[ "MIT" ]
null
null
null
ZeroEngine/Bullet.cpp
bamtoll09/GROWN
0f2098bce97a739f9b786d487136aa44f1b6a227
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Bullet.h" Bullet::Bullet(void) :available(true), speed(500.f), update(true) { bullet = new ZeroSprite("%s", "exresource/bullet.png"); this->SetWidth(bullet->Width()); this->SetHeight(bullet->Height()); PushScene(bullet); } Bullet::~Bullet(void) { } void Bullet::Update(float eTime) { ZeroIScene::Update(eTime); if (update) { if (this->Pos().x >= 3072 || this->Pos().x <= -25) SetErase(true); this->AddPosX(speed * eTime); } } void Bullet::Render() { ZeroIScene::Render(); bullet -> Render(); }
14.945946
56
0.632911
[ "render" ]
bcb66e0e5c6cfbfe35afcdb313fd5282f5e5ea59
14,619
cpp
C++
Tests/GeometryShop/regression/ebio.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
1
2021-05-20T13:04:05.000Z
2021-05-20T13:04:05.000Z
Tests/GeometryShop/regression/ebio.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
Tests/GeometryShop/regression/ebio.cpp
malvarado27/Amrex
8d5c7a37695e7dc899386bfd1f6ac28221984976
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "AMReX_BaseIVFactory.H" #include "AMReX_EBIndexSpace.H" #include "AMReX_EBISLayout.H" #include "AMReX_BoxIterator.H" #include "AMReX_ParmParse.H" #include "AMReX_GeometryShop.H" #include "AMReX_WrappedGShop.H" #include "AMReX_EBCellFAB.H" #include "AMReX_EBLevelGrid.H" #include "AMReX_LayoutData.H" #include "AMReX_EBCellFactory.H" #include "AMReX_VoFIterator.H" #include "AMReX_EBArith.H" #include "AMReX_AllRegularService.H" #include "AMReX_PlaneIF.H" #include "AMReX_SPMD.H" #include "AMReX_Print.H" #include "AMReX_EBFluxFactory.H" #include "AMReX_EBFluxFAB.H" #include "AMReX_EBCellFactory.H" #include "AMReX_EBCellFAB.H" #include "AMReX_IrregFABFactory.H" #include "AMReX_BaseEBCellFactory.H" #include "AMReX_IrregFAB.H" #include "AMReX_EBDataVarMacros.H" #include "AMReX_FabArrayIO.H" #include "AMReX_parstream.H" namespace amrex { void dumpIFFAB(const BaseIFFAB<Real>* a_iffab) { int ncomp = a_iffab->nComp(); const Vector<FaceIndex>& faces = a_iffab->getFaces(); for(int iface = 0; iface < faces.size(); iface++) { amrex::Print() << iface << " " << faces[iface] << ":"; for(int icomp = 0; icomp < ncomp; icomp++) { amrex::Print() << (*a_iffab)(faces[iface], icomp) << " "; } amrex::Print() << endl; } } void dumpFaces(Vector<FaceIndex>* a_iffab) { const Vector<FaceIndex>& faces = *a_iffab; for(int iface = 0; iface < faces.size(); iface++) { amrex::Print() << faces[iface]; amrex::Print() << endl; } } //[((14,5)):0; ((15,5)):0] void pointFAData( FabArray<EBData>* a_data) { IntVect ivlo(D_DECL(14, 5, 0)); IntVect ivhi(D_DECL(15, 5, 0)); FaceIndex debface(VolIndex(ivlo, 0), VolIndex(ivhi,0)); FabArray<EBData>& datamf = *a_data; int ibox =0; for(MFIter mfi(datamf); mfi.isValid(); ++mfi) { EBData& ebdata = datamf[mfi]; const BaseIFFAB<Real>& facefab = ebdata.getFaceData(0); const Vector<FaceIndex>& faces = facefab.getFaces(); for(int iface = 0; iface < faces.size(); iface++) { if(faces[iface] == debface) { amrex::Print() << "ibox = " << ibox << ", iface = " << iface << " " << faces[iface] << ":"; int ncomp = facefab.nComp(); for(int icomp = 0; icomp < ncomp; icomp++) { amrex::Print() << facefab(faces[iface], icomp) << " "; } amrex::Print() << endl; } } ibox++; } } void pointData( EBData* a_data) { IntVect ivlo(D_DECL(14, 5, 0)); IntVect ivhi(D_DECL(15, 5, 0)); FaceIndex debface(VolIndex(ivlo, 0), VolIndex(ivhi,0)); EBData& ebdata = *a_data; const BaseIFFAB<Real>& facefab = ebdata.getFaceData(0); const Vector<FaceIndex>& faces = facefab.getFaces(); for(int iface = 0; iface < faces.size(); iface++) { if(faces[iface] == debface) { amrex::Print() << " iface = " << iface << " " << faces[iface] << ":"; int ncomp = facefab.nComp(); for(int icomp = 0; icomp < ncomp; icomp++) { amrex::Print() << facefab(faces[iface], icomp) << " "; } amrex::Print() << endl; } } } void donotcallpls() { dumpIFFAB(NULL); dumpFaces(NULL); pointData(NULL); pointFAData(NULL); } /***************/ int makeGeometry(Box& a_domain, Real& a_dx, int igeom) { int eekflag = 0; int maxbox; //parse input file ParmParse pp; pp.get("maxboxsize", maxbox); RealVect origin = RealVect::Zero; std::vector<int> n_cell; pp.getarr("n_cell", n_cell, 0, SpaceDim); IntVect lo = IntVect::TheZeroVector(); IntVect hi; for (int ivec = 0; ivec < SpaceDim; ivec++) { if (n_cell[ivec] <= 0) { amrex::Print() << " bogus number of cells input = " << n_cell[ivec]; return(-1); } hi[ivec] = n_cell[ivec] - 1; } a_domain.setSmall(lo); a_domain.setBig(hi); Real prob_hi; pp.get("prob_hi",prob_hi); a_dx = prob_hi/n_cell[0]; int whichgeom; pp.get("which_geom",whichgeom); if (whichgeom == 0) { //allregular amrex::Print() << "all regular geometry" << "\n"; AllRegularService regserv; EBIndexSpace* ebisPtr = AMReX_EBIS::instance(); ebisPtr->define(a_domain, origin, a_dx, regserv, maxbox); } else if (whichgeom == 1) { amrex::Print() << "ramp geometry" << "\n"; int upDir; int indepVar; Real startPt; Real slope; pp.get("up_dir",upDir); pp.get("indep_var",indepVar); pp.get("start_pt", startPt); pp.get("ramp_slope", slope); RealVect normal = RealVect::Zero; normal[upDir] = 1.0; normal[indepVar] = -slope; RealVect point = RealVect::Zero; point[upDir] = -slope*startPt; bool normalInside = true; PlaneIF ramp(normal,point,normalInside); if(igeom == 0) { amrex::Print() << "using GeometryShop for geom gen" << endl; GeometryShop workshop(ramp,0, a_dx); //this generates the new EBIS EBIndexSpace* ebisPtr = AMReX_EBIS::instance(); ebisPtr->define(a_domain, origin, a_dx, workshop, maxbox); } else { amrex::Print() << "using WrappedGShop for geom gen" << endl; WrappedGShop workshop(ramp,0, a_dx); //this generates the new EBIS EBIndexSpace* ebisPtr = AMReX_EBIS::instance(); ebisPtr->define(a_domain, origin, a_dx, workshop, maxbox); } } else { //bogus which_geom amrex::Print() << " bogus which_geom input = " << whichgeom << "\n"; eekflag = 33; } return eekflag; } /****/ int checkGraphs( const FabArray<EBGraph > & a_ebg1, const FabArray<EBGraph > & a_ebg2, const EBLevelGrid & a_eblg) { for(MFIter mfi(a_eblg.getDBL(), a_eblg.getDM()); mfi.isValid(); ++mfi) { EBGraph ebg1 = a_ebg1[mfi]; EBGraph ebg2 = a_ebg2[mfi]; if(ebg1.getDomain() != ebg2.getDomain()) { amrex::Print() << "checkgraph: domain mismatch" << endl; return -1; } if(ebg1.getRegion() != ebg2.getRegion()) { amrex::Print() << "checkgraph: region mismatch" << endl; return -2; } const Box& grid = a_eblg.getDBL()[mfi]; IntVectSet ivs(grid); VoFIterator vofit1(ivs, ebg1); VoFIterator vofit2(ivs, ebg2); vector<VolIndex> vvof1 = vofit1.getVector(); vector<VolIndex> vvof2 = vofit2.getVector(); if(vvof1.size() != vvof2.size()) { amrex::Print() << "checkgraph: vector vof size mismatch" << endl; return -3; } for(int ivec = 0; ivec < vvof1.size(); ivec++) { if(vvof1[ivec] != vvof2[ivec]) { amrex::Print() << "checkgraph: vof mismatch at ivec = "<< ivec << endl; return -4; } } for(int facedir = 0; facedir < SpaceDim; facedir++) { FaceIterator faceit1(ivs, ebg1, facedir, FaceStop::SurroundingWithBoundary); FaceIterator faceit2(ivs, ebg2, facedir, FaceStop::SurroundingWithBoundary); vector<FaceIndex> vfac1 = faceit1.getVector(); vector<FaceIndex> vfac2 = faceit2.getVector(); if(vfac1.size() != vfac2.size()) { amrex::Print() << "checkgraph: vector face size mismatch" << endl; return -5; } for(int ivec = 0; ivec < vfac1.size(); ivec++) { if(vfac1[ivec] != vfac2[ivec]) { amrex::Print() << "checkgraph: face mismatch at ivec = "<< ivec << endl; return -6; } } } } return 0; } /****/ int checkData( const FabArray<EBData> & a_ebd1, const FabArray<EBData> & a_ebd2, const EBLevelGrid & a_eblg) { int ibox = 0; for(MFIter mfi(a_eblg.getDBL(), a_eblg.getDM()); mfi.isValid(); ++mfi) { EBData ebd1 = a_ebd1[mfi]; EBData ebd2 = a_ebd2[mfi]; if(ebd1.getRegion() != ebd2.getRegion()) { amrex::Print() << "checkdata: region mismatch" << endl; return -2; } //check the volume data BaseIVFAB<Real>& vdata1 = ebd1.getVolData(); BaseIVFAB<Real>& vdata2 = ebd2.getVolData(); if((vdata1.nComp() != V_VOLNUMBER) || (vdata2.nComp() != V_VOLNUMBER)) { amrex::Print() << "checkdata: vdata comps wrong" << endl; return -5; } const vector<VolIndex>& vvof1 = vdata1.getVoFs(); const vector<VolIndex>& vvof2 = vdata2.getVoFs(); if(vvof1.size() != vvof2.size()) { amrex::Print() << "checkdata: vector vof size mismatch" << endl; return -3; } for(int ivec = 0; ivec < vvof1.size(); ivec++) { if(vvof1[ivec] != vvof2[ivec]) { amrex::Print() << "checkvof: vof mismatch at ivec = "<< ivec << endl; return -4; } for(int icomp = 0; icomp < V_VOLNUMBER; icomp++) { Real val1 = vdata1(vvof1[ivec], icomp); Real val2 = vdata2(vvof2[ivec], icomp); Real tol = 1.0e-9; if(std::abs(val1-val2) > tol) { amrex::Print() << "bad vof = " << vvof1[ivec] << endl; amrex::Print() << "checkvof: vof value mismatch at ivec, ivar = "<< ivec << ","<< icomp<< endl; amrex::Print() << "val1 = " << val1 << ", val2 =" << val2 << endl; return -6; } } } //check the face data //int idir = 0; //if(0) for(int idir = 0; idir < SpaceDim; idir++) { BaseIFFAB<Real>& fdata1 = ebd1.getFaceData(idir); BaseIFFAB<Real>& fdata2 = ebd2.getFaceData(idir); if((fdata1.nComp() != F_FACENUMBER) || (fdata2.nComp() != F_FACENUMBER)) { amrex::Print() << "checkdata: fdata comps wrong" << endl; return -7; } const vector<FaceIndex>& vfac1 = fdata1.getFaces(); const vector<FaceIndex>& vfac2 = fdata2.getFaces(); if(vfac1.size() != vfac2.size()) { amrex::Print() << "checkdata: vector face size mismatch" << endl; return -8; } for(int ivec = 0; ivec < vfac1.size(); ivec++) { if(vfac1[ivec] != vfac2[ivec]) { amrex::Print() << "checkvof: vof mismatch at ivec = "<< ivec << endl; return -9; } const FaceIndex& face = vfac1[ivec]; Box reg = ebd1.getRegion(); if((reg.contains(face.gridIndex(Side::Lo))) || (reg.contains(face.gridIndex(Side::Hi)))) { for(int icomp = 0; icomp < F_FACENUMBER; icomp++) { Real val1 = fdata1(vfac1[ivec], icomp); Real val2 = fdata2(vfac2[ivec], icomp); Real tol = 1.0e-9; if(std::abs(val1-val2) > tol) { amrex::Print() << "bad face = " << vfac1[ivec] << endl; amrex::Print() << "eblg domain = " << a_eblg.getDomain() << endl; amrex::Print() << "ebd1 region = " << ebd1.getRegion() << endl; amrex::Print() << "ebd2 region = " << ebd2.getRegion() << endl; amrex::Print() << "val1 = " << val1 << ", val2 =" << val2 << endl; amrex::Print() << "checkvof: face value mismatch at ivec, ivar = "<< ivec << ","<< icomp<< endl; return -10; } } } } } ibox++; } return 0; } /***************/ int testEBIO(int igeom) { Box domain; Real dx; //make the initial geometry amrex::AllPrint() << "making EBIS" << endl; makeGeometry(domain, dx, igeom); //extract all the info we can from the singleton EBIndexSpace* ebisPtr = AMReX_EBIS::instance(); int numLevelsIn = ebisPtr->getNumLevels(); vector<Box> domainsIn = ebisPtr->getDomains(); int nCellMaxIn = ebisPtr->getNCellMax(); amrex::AllPrint() << "making eblgIn EBLevelGrids" << endl; vector<EBLevelGrid> eblgIn(numLevelsIn); for(int ilev = 0; ilev < numLevelsIn; ilev++) { Box domlev = domainsIn[ilev]; BoxArray ba(domlev); ba.maxSize(nCellMaxIn); DistributionMapping dm(ba); eblgIn[ilev]= EBLevelGrid(ba, dm, domain, 2); } amrex::AllPrint() << "writing EBIS" << endl; //write the singleton and erase it. ebisPtr->write("ebis.plt"); ebisPtr->clear(); //now read it back in and get all that info again amrex::AllPrint() << "reading EBIS" << endl; ebisPtr->read("ebis.plt"); int numLevelsOut = ebisPtr->getNumLevels(); vector<Box> domainsOut = ebisPtr->getDomains(); int nCellMaxOut = ebisPtr->getNCellMax(); amrex::AllPrint() << "making eblgOut EBLevelGrids" << endl; vector<EBLevelGrid> eblgOut(numLevelsOut); for(int ilev = 0; ilev < numLevelsOut; ilev++) { Box domlev = domainsOut[ilev]; BoxArray ba(domlev); ba.maxSize(nCellMaxOut); DistributionMapping dm = eblgIn[ilev].getDM(); eblgOut[ilev]= EBLevelGrid(ba, dm, domain, 2); } amrex::Print() << "checking EBIS" << endl; //now check that in==out if(numLevelsOut != numLevelsIn) { amrex::Print() << "num levels mismatch" << endl; return -1; } if(nCellMaxOut != nCellMaxIn) { amrex::Print() << "ncell max mismatch" << endl; return -2; } for(int ilev = 0; ilev < numLevelsIn; ilev++) { if(domainsIn[ilev] != domainsOut[ilev]) { amrex::Print() << "domains mismatch" << endl; return -3; } EBISLayout ebislIn = eblgIn [ilev].getEBISL(); EBISLayout ebislOut = eblgOut[ilev].getEBISL(); int retgraph = checkGraphs(*ebislIn.getAllGraphs(), *ebislOut.getAllGraphs(), eblgIn[ilev]); if(retgraph != 0) { amrex::Print() << "graph mismatch" << endl; return retgraph; } int retdata = checkData( *ebislIn.getAllData (), *ebislOut.getAllData (), eblgIn[ilev]); if(retdata != 0) { amrex::Print() << "data mismatch" << endl; return retdata; } } return 0; } } /***************/ int main(int argc, char* argv[]) { int retval = 0; amrex::Initialize(argc,argv); for(int igeom = 0; igeom <= 1; igeom++) { retval = amrex::testEBIO(igeom); if(retval != 0) { amrex::Print() << "EBIndexSpace I/O test failed with code " << retval << "\n"; } } amrex::Print() << "EBIndexSpace I/O test passed \n"; amrex::Finalize(); return retval; }
29.355422
113
0.551816
[ "geometry", "vector" ]
bcbce956a8c807f913bb7e71c26a5bdda02eb094
7,551
hpp
C++
framework/areg/component/private/EventConsumerMap.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/component/private/EventConsumerMap.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/component/private/EventConsumerMap.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
#pragma once /************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/component/private/EventConsumerMap.hpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, Event Consumer Resources Object declaration. * This Resource Map object contains information of Event Consumers * ************************************************************************/ /************************************************************************ * Includes ************************************************************************/ #include "areg/base/TERuntimeResourceMap.hpp" #include "areg/base/Containers.hpp" #include "areg/base/TEResourceMap.hpp" /************************************************************************ * Declared classes ************************************************************************/ class EventConsumerList; /************************************************************************ * Dependencies ************************************************************************/ class IEEventConsumer; /************************************************************************ * \brief In this file are declared Event Consumer contain classes: * 1. EventConsumerList -- List of Event Consumers * 2. EventConsumerMap -- Map of Event Consumer. * These are helper classes used in Dispatcher object. * For details, see description bellow. ************************************************************************/ ////////////////////////////////////////////////////////////////////////// // EventConsumerList class declaration ////////////////////////////////////////////////////////////////////////// using ImplEventConsumerList = TEListImpl<IEEventConsumer *>; using EventConsumerListBase = TELinkedList<IEEventConsumer *, IEEventConsumer *, ImplEventConsumerList>; /** * \brief Event Consumer List is a helper class containing * Event Consumer objects. It is used in Dispatcher, when * collecting list of Consumers, which are registered * to dispatch certain Event Object. * For use, see implementation of EventDispatcherBase class **/ class EventConsumerList : public EventConsumerListBase { ////////////////////////////////////////////////////////////////////////// // Constructor / Destructor ////////////////////////////////////////////////////////////////////////// public: /** * \brief Default Constructor. Initializes empty list **/ EventConsumerList( void ) = default; /** * \brief Copy constructor. * \param src The source of data to copy. **/ EventConsumerList(const EventConsumerList & src) = default; /** * \brief Move constructor. * \param src The source of data to move. **/ EventConsumerList( EventConsumerList && src ) noexcept = default; /** * \brief Destructor **/ ~EventConsumerList( void ); ////////////////////////////////////////////////////////////////////////// // Operations ////////////////////////////////////////////////////////////////////////// public: /** * \brief Assigns entries from given source. * \param src THe source of event consumer list. */ inline EventConsumerList & operator = (const EventConsumerList & src ) = default; /** * \brief Assigns entries from given source. * \param src THe source of event consumer list. */ inline EventConsumerList & operator = ( EventConsumerList && src ) noexcept = default; /** * \brief Adds Event Consumer object to the list. Returns true, * if Event Consumer object is added to the list. The function does not * check whether the Event Consumer already exists in the list or not. * To check whether there is already Event Consumer in the list * call existConsumer() method. * \param whichConsumer The Event Consumer object to add to the list. * \return Returns true if Event Consumer is added to the list. **/ bool addConsumer( IEEventConsumer & whichConsumer ); /** * \brief Removes Event Consumer object from the List. The function will * search for the Event Consumer object by pointer and remove * the first match. The function does not check whether there is still * same Event Consumer exist in the list or not. * To check whether there is already Event Consumer in the list * call existConsumer() method. * \param whichConsumer The Event Consumer object to remove from the list. * \return Returns true if Event Consumer was removed from the list. **/ bool removeConsumer( IEEventConsumer & whichConsumer ); /** * \brief Removes all Event Consumers from the list. **/ void removeAllConsumers( void ); /** * \brief Returns true, if the specified Event Consumer already exists in the list. * The lookup will be done by pointer address value. * \param whichConsumer The Event Consumer object to search. * \return Returns true, if the specified Event Consumer already exists in the list. **/ inline bool existConsumer( IEEventConsumer & whichConsumer ) const; }; ////////////////////////////////////////////////////////////////////////// // EventConsumerMap class declaration ////////////////////////////////////////////////////////////////////////// class ImplEventConsumerMap : public TEResourceMapImpl<RuntimeClassID, EventConsumerList> { public: /** * \brief Called when all resources are removed. * \param Key The Key value of resource * \param Resource Pointer to resource object **/ void implCleanResource( RuntimeClassID & Key, EventConsumerList * Resource ); }; /** * \brief Event Consumer Map is a helper class containing * Event Consumer List objects registered for certain Events, * which are Runtime type of objects. The Key value of the map * is Runtime object and the Values are Consumer Event List objects. * It is used in Dispatcher, when a Consumer is registered for Event. * For use, see implementation of EventDispatcherBase class **/ using EventConsumerMap = TELockRuntimeResourceMap<EventConsumerList, ImplEventConsumerMap>; ////////////////////////////////////////////////////////////////////////// // Inline functions implementation ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // EventConsumerList class inline functions ////////////////////////////////////////////////////////////////////////// inline bool EventConsumerList::existConsumer( IEEventConsumer & whichConsumer ) const { return (EventConsumerListBase::find( &whichConsumer, nullptr) != nullptr); }
44.417647
104
0.533572
[ "object" ]
bcbd5f80517fe250afdf4d16cc189c3f1724b476
5,885
hxx
C++
main/framework/inc/uielement/menubarmerger.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/framework/inc/uielement/menubarmerger.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/framework/inc/uielement/menubarmerger.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_MENUBARMERGER_HXX_ #define __FRAMEWORK_UIELEMENT_MENUBARMERGER_HXX_ #include <com/sun/star/beans/PropertyValue.hpp> #include <rtl/ustring.hxx> #include <vcl/menu.hxx> namespace framework { struct AddonMenuItem; typedef ::std::vector< AddonMenuItem > AddonMenuContainer; struct AddonMenuItem { ::rtl::OUString aTitle; ::rtl::OUString aURL; ::rtl::OUString aTarget; ::rtl::OUString aImageId; ::rtl::OUString aContext; AddonMenuContainer aSubMenu; }; enum RPResultInfo { RP_OK, RP_POPUPMENU_NOT_FOUND, RP_MENUITEM_NOT_FOUND, RP_MENUITEM_INSTEAD_OF_POPUPMENU_FOUND }; struct ReferencePathInfo { Menu* pPopupMenu; sal_uInt16 nPos; sal_Int32 nLevel; RPResultInfo eResult; }; class MenuBarMerger { public: static bool IsCorrectContext( const ::rtl::OUString& aContext, const ::rtl::OUString& aModuleIdentifier ); static void RetrieveReferencePath( const ::rtl::OUString&, std::vector< ::rtl::OUString >& aReferencePath ); static ReferencePathInfo FindReferencePath( const std::vector< ::rtl::OUString >& aReferencePath, Menu* pMenu ); static sal_uInt16 FindMenuItem( const ::rtl::OUString& rCmd, Menu* pMenu ); static void GetMenuEntry( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rAddonMenuEntry, AddonMenuItem& aAddonMenu ); static void GetSubMenu( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > >& rSubMenuEntries, AddonMenuContainer& rSubMenu ); static bool ProcessMergeOperation( Menu* pMenu, sal_uInt16 nPos, sal_uInt16& rItemId, const ::rtl::OUString& rMergeCommand, const ::rtl::OUString& rMergeCommandParameter, const ::rtl::OUString& rModuleIdentifier, const AddonMenuContainer& rAddonMenuItems ); static bool ProcessFallbackOperation( const ReferencePathInfo& aRefPathInfo, sal_uInt16& rItemId, const ::rtl::OUString& rMergeCommand, const ::rtl::OUString& rMergeFallback, const ::std::vector< ::rtl::OUString >& rReferencePath, const ::rtl::OUString& rModuleIdentifier, const AddonMenuContainer& rAddonMenuItems ); static bool ProcessFallbackOperation(); static bool MergeMenuItems( Menu* pMenu, sal_uInt16 nPos, sal_uInt16 nModIndex, sal_uInt16& rItemId, const ::rtl::OUString& rModuleIdentifier, const AddonMenuContainer& rAddonMenuItems ); static bool ReplaceMenuItem( Menu* pMenu, sal_uInt16 nPos, sal_uInt16& rItemId, const ::rtl::OUString& rModuleIdentifier, const AddonMenuContainer& rAddonMenuItems ); static bool RemoveMenuItems( Menu* pMenu, sal_uInt16 nPos, const ::rtl::OUString& rMergeCommandParameter ); static bool CreateSubMenu( Menu* pSubMenu, sal_uInt16& nItemId, const ::rtl::OUString& rModuleIdentifier, const AddonMenuContainer& rAddonSubMenu ); private: MenuBarMerger(); MenuBarMerger( const MenuBarMerger& ); MenuBarMerger& operator=( const MenuBarMerger& ); }; } // namespace framework #endif // __FRAMEWORK_UIELEMENT_MENUBARMERGER_HXX_
48.636364
170
0.494138
[ "vector" ]
bcbf4b921040e9efe8af76477d8e5fec00041fb6
6,183
cxx
C++
inetcore/winhttp/tools/w3spoof/om/session/scriptsite.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/winhttp/tools/w3spoof/om/session/scriptsite.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/winhttp/tools/w3spoof/om/session/scriptsite.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Copyright (c) 2000 Microsoft Corporation Module Name: scriptsite.cxx Abstract: Implements the IActiveScriptSite interface for the session object. Author: Paul M Midgen (pmidge) 10-October-2000 Revision History: 10-October-2000 pmidge Created =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--*/ #include "common.h" extern LPWSTR g_wszRuntimeObjectName; //----------------------------------------------------------------------------- // IActiveScriptSite //----------------------------------------------------------------------------- HRESULT __stdcall CSession::GetLCID(LCID* plcid) { DEBUG_ENTER(( DBG_SESSION, rt_hresult, "CSession::GetLCID", "this=%#x; plcid=%#x", this, plcid )); HRESULT hr = S_OK; if( !plcid ) { hr = E_POINTER; } else { *plcid = MAKELCID( MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), SORT_DEFAULT ); } DEBUG_LEAVE(hr); return hr; } HRESULT __stdcall CSession::GetItemInfo(LPCOLESTR pstrName, DWORD dwReturnMask, IUnknown** ppunk, ITypeInfo** ppti) { DEBUG_ENTER(( DBG_SESSION, rt_hresult, "CSession::GetItemInfo", "this=%#x; name=%S; retmask=%#x; ppunk=%#x; ppti=%#x", this, pstrName, dwReturnMask, ppunk, ppti )); HRESULT hr = S_OK; if( !pstrName ) { hr = E_INVALIDARG; goto quit; } if( dwReturnMask & SCRIPTINFO_IUNKNOWN ) { if( !_wcsicmp(pstrName, g_wszRuntimeObjectName) ) { IW3SpoofRuntime* pw3srt = NULL; if( SUCCEEDED(m_pw3s->GetRuntime(&pw3srt)) ) { hr = pw3srt->QueryInterface(IID_IUnknown, (void**) ppunk); } else { hr = E_FAIL; *ppunk = NULL; } SAFERELEASE(pw3srt); } else { hr = QueryInterface(IID_IUnknown, (void**) ppunk); } } else if( dwReturnMask & SCRIPTINFO_ITYPEINFO ) { hr = GetTypeInfoFromName(pstrName, m_ptl, ppti); if( FAILED(hr) ) { *ppti = NULL; } } quit: DEBUG_LEAVE(hr); return hr; } HRESULT __stdcall CSession::GetDocVersionString(BSTR* pbstrVersion) { DEBUG_TRACE(SESSION, ("NOTIMPL: IActiveScriptSite::GetDocVersionString()")); return E_NOTIMPL; } HRESULT __stdcall CSession::OnScriptTerminate(const VARIANT* pvarResult, const EXCEPINFO* pei) { DEBUG_TRACE(SESSION, ("NOTIMPL: IActiveScriptSite::OnScriptTerminate()")); return E_NOTIMPL; } HRESULT __stdcall CSession::OnStateChange(SCRIPTSTATE ss) { DEBUG_TRACE(SESSION, ("new script state %s", MapStateToString(ss))); return S_OK; } HRESULT __stdcall CSession::OnScriptError(IActiveScriptError* piase) { DEBUG_ENTER(( DBG_SESSION, rt_hresult, "CSession::OnScriptError", "this=%#x; piase=%#x", this, piase )); HRESULT hr = S_OK; DWORD n = 0L; DWORD cookie = 0L; ULONG line = 0L; LONG pos = 0L; BSTR bstr = SysAllocStringLen(NULL, 256); WCHAR* tmp = NULL; EXCEPINFO ex; if( FAILED(piase->GetSourceLineText(&bstr)) ) { SysFreeString(bstr); bstr = SysAllocString(L"source not available"); } else { for(wcstok(bstr, L"\n"); n<line; n++) { tmp = wcstok(NULL, L"\n"); } } piase->GetExceptionInfo(&ex); piase->GetSourcePosition(&cookie, &line, &pos); ++line; DEBUG_TRACE(SESSION, ("********* SCRIPT ERROR *********")); DEBUG_TRACE(SESSION, (" session: %x", cookie)); DEBUG_TRACE(SESSION, (" line # : %d", line)); DEBUG_TRACE(SESSION, (" char # : %d", pos)); DEBUG_TRACE(SESSION, (" source : %S", ex.bstrSource)); DEBUG_TRACE(SESSION, (" error : %S", ex.bstrDescription)); DEBUG_TRACE(SESSION, (" hresult: 0x%0.8X [%s]", ex.scode, MapHResultToString(ex.scode))); DEBUG_TRACE(SESSION, (" code : %S", tmp ? tmp : bstr)); DEBUG_TRACE(SESSION, ("********************************")); if( m_socketobj ) { WCHAR* buf = new WCHAR[4096]; LPWSTR script = NULL; ISocket* ps = NULL; m_pw3s->GetScriptPath(m_wszClient, &script); wsprintfW( buf, L"HTTP/1.1 500 Server Error\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n" \ L"<HTML><BODY style=\"font-family:courier new;\">\r\n" \ L"<B>W3Spoof Script Error</B>\r\n" \ L"<XMP>\r\n" \ L"session: %#x\r\n" \ L"handler: %S\r\n" \ L"client : %s\r\n" \ L"file : %s\r\n" \ L"error : %s (%s)\r\n" \ L"hresult: 0x%0.8X [%S]\r\n" \ L"line # : %d\r\n" \ L"char # : %d\r\n" \ L"code : %s\r\n" \ L"</XMP>\r\n" \ L"</BODY></HTML>", cookie, MapScriptDispidToString(m_CurrentHandler), m_wszClientId, script, ex.bstrSource, ex.bstrDescription, ex.scode, MapHResultToString(ex.scode), line, pos, tmp ? tmp : bstr ); NEWVARIANT(error); V_VT(&error) = VT_BSTR; V_BSTR(&error) = __widetobstr(buf); m_socketobj->QueryInterface(IID_ISocket, (void**) &ps); ps->Send(error); VariantClear(&error); SAFERELEASE(ps); SAFEDELETEBUF(buf); } SysFreeString(bstr); DEBUG_LEAVE(hr); return hr; } HRESULT __stdcall CSession::OnEnterScript(void) { DEBUG_TRACE(SESSION, ("****** ENTER %s HANDLER ******", MapScriptDispidToString(m_CurrentHandler))); return E_NOTIMPL; } HRESULT __stdcall CSession::OnLeaveScript(void) { DEBUG_TRACE(SESSION, ("****** LEAVE %s HANDLER ******", MapScriptDispidToString(m_CurrentHandler))); return E_NOTIMPL; }
21.925532
103
0.51496
[ "object" ]
346739af8e905d242f0441d80284d88f103ad5b2
681
cpp
C++
Scripts/501_std.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
17
2018-08-23T08:53:56.000Z
2021-04-17T00:06:13.000Z
Scripts/501_std.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
Scripts/501_std.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findMode(TreeNode* root) { vector<int> res; int mx = 0, cnt = 1; TreeNode *pre = NULL; inorder(root, pre, cnt, mx, res); return res; } void inorder(TreeNode* node, TreeNode*& pre, int& cnt, int& mx, vector<int>& res) { if (!node) return; inorder(node->left, pre, cnt, mx, res); if (pre) { cnt = (node->val == pre->val) ? cnt + 1 : 1; } if (cnt >= mx) { if (cnt > mx) res.clear(); res.push_back(node->val); mx = cnt; } pre = node; inorder(node->right, pre, cnt, mx, res); } };
28.375
87
0.465492
[ "vector" ]
346901c2afdbab68c324f5f4f2c1a6ff4b362420
1,388
cpp
C++
aws-cpp-sdk-eks/source/model/ListFargateProfilesResult.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-eks/source/model/ListFargateProfilesResult.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-eks/source/model/ListFargateProfilesResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/eks/model/ListFargateProfilesResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::EKS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListFargateProfilesResult::ListFargateProfilesResult() { } ListFargateProfilesResult::ListFargateProfilesResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListFargateProfilesResult& ListFargateProfilesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("fargateProfileNames")) { Array<JsonView> fargateProfileNamesJsonList = jsonValue.GetArray("fargateProfileNames"); for(unsigned fargateProfileNamesIndex = 0; fargateProfileNamesIndex < fargateProfileNamesJsonList.GetLength(); ++fargateProfileNamesIndex) { m_fargateProfileNames.push_back(fargateProfileNamesJsonList[fargateProfileNamesIndex].AsString()); } } if(jsonValue.ValueExists("nextToken")) { m_nextToken = jsonValue.GetString("nextToken"); } return *this; }
27.76
142
0.773055
[ "model" ]
34696a79cd51f819e238943fe8c4531ab2d31039
4,922
cpp
C++
MyProgram/2DOverlay/Source.cpp
shihyu/openvr
44310f0ecdcdbfba442ff1bc140b03211432fb1b
[ "BSD-3-Clause" ]
2
2018-07-30T07:46:41.000Z
2019-03-21T13:00:23.000Z
MyProgram/2DOverlay/Source.cpp
KHeresy/openvr
f644fc67c96132d9fe5a67d42a27ccc6bcf5595c
[ "BSD-3-Clause" ]
null
null
null
MyProgram/2DOverlay/Source.cpp
KHeresy/openvr
f644fc67c96132d9fe5a67d42a27ccc6bcf5595c
[ "BSD-3-Clause" ]
4
2016-06-26T07:26:51.000Z
2018-10-05T05:48:30.000Z
// A test program to use 'overlay' in OpenVR // STD Headers #include <chrono> #include <iostream> #include <string> #include <sstream> #include <thread> // OpenVR #include <openvr.h> #pragma comment(lib,"openvr_api.lib") // OpenCV #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #ifdef _DEBUG #pragma comment(lib,"opencv_world330d.lib") #else #pragma comment(lib,"opencv_world330.lib") #endif std::string GetInformation(vr::IVRSystem* pVRSystem, vr::ETrackedDeviceProperty eProp) { char aText[128]; vr::TrackedPropertyError eTPErr; pVRSystem->GetStringTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, eProp, aText, sizeof(aText), &eTPErr); if (eTPErr == vr::TrackedProp_Success) { return std::string(aText); } return ""; } int main(int argc, char** argv) { vr::EVRInitError eError = vr::VRInitError_None; // Initial VR System vr::IVRSystem* pVRSystem = vr::VR_Init(&eError, vr::VRApplication_Scene); if (eError != vr::VRInitError_None) { std::cerr << vr::VR_GetVRInitErrorAsEnglishDescription(eError) << std::endl; return 1; } // Get some information { std::cout << "\nDevice Information\n"; std::cout << " System Name: " << GetInformation(pVRSystem, vr::Prop_TrackingSystemName_String) << "\n"; std::cout << " Manufacturer Name: " << GetInformation(pVRSystem, vr::Prop_ManufacturerName_String) << "\n"; std::cout << " Model Number: " << GetInformation(pVRSystem, vr::Prop_ModelNumber_String) << "\n"; std::cout << " Serial Number: " << GetInformation(pVRSystem, vr::Prop_SerialNumber_String) << "\n"; std::cout << " Render Model Name: " << GetInformation(pVRSystem, vr::Prop_RenderModelName_String) << "\n"; } // Get VR Overlay vr::IVROverlay* pVROverlay = vr::VROverlay(); vr::VROverlayHandle_t hdlBigImage = 0, hdlInfoImage = 0; cv::Mat imInfo(100, 300, CV_8UC4); if (pVROverlay != nullptr) { // create overlay 1 if (pVROverlay->CreateOverlay("BigImage", "A Big Image wall", &hdlBigImage) == vr::VROverlayError_None) { // Size and position pVROverlay->SetOverlayWidthInMeters(hdlBigImage, 3.0f); vr::HmdMatrix34_t matTransform = { 1,0,0,0, 0,1,0,0, 0,0,1,-3 }; pVROverlay->SetOverlayTransformAbsolute(hdlBigImage, vr::TrackingUniverseSeated, &matTransform); // non-used pVROverlay->SetOverlayColor(hdlBigImage, 1.0f, 1.0f, 1.0f); pVROverlay->SetOverlayAlpha(hdlBigImage, 1.0f); pVROverlay->SetOverlayInputMethod(hdlBigImage, vr::VROverlayInputMethod_Mouse); // show it! pVROverlay->ShowOverlay(hdlBigImage); // set image, load from file pVROverlay->SetOverlayFromFile(hdlBigImage, "E:\\testb.jpg"); } // create overlay 2 if (pVROverlay->CreateOverlay("InfoImage", "Information Image", &hdlInfoImage) == vr::VROverlayError_None) { // Size and position pVROverlay->SetOverlayWidthInMeters(hdlInfoImage, 0.1f); vr::HmdMatrix34_t matTransform = { 1,0,0,0, 0,1,0,0.1, 0,0,1,0 }; pVROverlay->SetOverlayTransformTrackedDeviceRelative(hdlInfoImage, 1, &matTransform); // non-used pVROverlay->SetOverlayColor(hdlInfoImage, 1.0f, 1.0f, 1.0f); pVROverlay->SetOverlayAlpha(hdlInfoImage, 1.0f); pVROverlay->SetOverlayInputMethod(hdlInfoImage, vr::VROverlayInputMethod_None); // show it! pVROverlay->ShowOverlay(hdlInfoImage); // set image image // This code faile if image too large // Should be the bug of OpenVR: https://github.com/ValveSoftware/openvr/issues/46 pVROverlay->SetOverlayRaw(hdlInfoImage, imInfo.data, imInfo.cols, imInfo.rows, imInfo.channels()); } } vr::VRControllerState_t mCState; vr::TrackedDevicePose_t mCPose; while (true) { imInfo.setTo(128); for (vr::TrackedDeviceIndex_t uDeviceIdx = 1; uDeviceIdx < vr::k_unControllerStateAxisCount; ++uDeviceIdx) { if (pVRSystem->IsTrackedDeviceConnected(uDeviceIdx)) { // tell OpenVR to make some events for us pVROverlay->HandleControllerOverlayInteractionAsMouse(hdlBigImage, uDeviceIdx); // get information of controller pVRSystem->GetControllerStateWithPose(vr::TrackingUniverseStanding, uDeviceIdx, &mCState, sizeof(mCState), &mCPose); std::ostringstream oss; oss << uDeviceIdx << " (" << mCPose.eTrackingResult << ") - " << mCState.ulButtonPressed; cv::putText(imInfo, oss.str(), cv::Point( 2, 50 * uDeviceIdx - 10), cv::FONT_HERSHEY_PLAIN, 2, cv::Scalar( 0,0,0,255), 5 ); } else { break; } } // update hdlInfoImage, may flick if (pVROverlay->IsOverlayVisible(hdlInfoImage)) { pVROverlay->SetOverlayRaw(hdlInfoImage, imInfo.data, imInfo.cols, imInfo.rows, imInfo.channels()); } vr::VREvent_t eVREvent; while (pVROverlay->PollNextOverlayEvent(hdlBigImage, &eVREvent, sizeof(eVREvent))) { } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } //vr::IVRCompositor* pCompositor = vr::VRCompositor(); vr::VR_Shutdown(); }
31.551282
127
0.70703
[ "render", "model" ]
346ea9c6d08614c731590be21e59ebf6d3c82347
2,875
cpp
C++
src/Correctors/Best.cpp
dsiuta/Comps
2071279280d33946e975de25deedc60f1881eda0
[ "BSD-3-Clause" ]
null
null
null
src/Correctors/Best.cpp
dsiuta/Comps
2071279280d33946e975de25deedc60f1881eda0
[ "BSD-3-Clause" ]
null
null
null
src/Correctors/Best.cpp
dsiuta/Comps
2071279280d33946e975de25deedc60f1881eda0
[ "BSD-3-Clause" ]
null
null
null
#include "Best.h" #include "../Obs.h" #include "../Parameters.h" CorrectorBest::CorrectorBest(const Options& iOptions, const Data& iData) : Corrector(iOptions, iData), mNum(1) { //! How many of the best members should be used? iOptions.getValue("num", mNum); iOptions.check(); } void CorrectorBest::correctCore(const Parameters& iParameters, Ensemble& iUnCorrected) const { // Default to missing std::vector<float> values(1,Global::MV); if(iParameters.size() == iUnCorrected.size()) { int N = iParameters.size(); // Sort ensemble based on skill std::vector<std::pair<float,float> > pairs; // fcst, score for(int n = 0; n < N; n++) { if(Global::isValid(iParameters[n])) pairs.push_back(std::pair<float,float>(iUnCorrected[n], iParameters[n])); } std::sort(pairs.begin(), pairs.end(), Global::sort_pair_second<int, float>()); // Create new ensemble if(pairs.size() > 0) { int num = std::min(mNum, (int) pairs.size()); values.resize(num); for(int i = 0; i < num; i++) { values[i] = pairs[i].first; } } } iUnCorrected.setValues(values); } void CorrectorBest::getDefaultParametersCore(Parameters& iParameters) const { std::vector<float> param(1); param[0] = Global::MV; iParameters.setAllParameters(param); } void CorrectorBest::updateParametersCore(const std::vector<Ensemble>& iUnCorrected, const std::vector<Obs>& iObs, Parameters& iParameters) const { if(iUnCorrected.size() == 0) return; // Resize parameters if wrong size int N = iUnCorrected[0].size(); if(iParameters.size() != N) { std::vector<float> values(N, Global::MV); iParameters.setAllParameters(values); } // Compute today's errors std::vector<float> todaysError(N, 0); std::vector<int> counter(N, 0); for(int t = 0; t < iObs.size(); t++) { Ensemble ens = iUnCorrected[t]; if(ens.size() != N) { std::stringstream ss; ss << "CorrectorBest: Ensembles do not have constant size (sizes: " << N << " and " << ens.size() << ") "; ss << "Cannot update parameters."; Global::logger->write(ss.str(), Logger::warning); return; } float obs = iObs[t].getValue(); if(Global::isValid(obs)) { for(int i = 0; i < N; i++) { float fcst = ens[i]; if(Global::isValid(fcst)) { todaysError[i] += fabs(fcst - obs); counter[i]++; } } } } // Update for(int i = 0; i < N; i++) { if(counter[i] > 0) { if(Global::isValid(iParameters[i])) { iParameters[i] = combine(iParameters[i], todaysError[i]/counter[i]); } else { iParameters[i] = todaysError[i]/counter[i]; } } } }
30.913978
115
0.570087
[ "vector" ]
3484288d5dc51e9493c8dd6695b9cceaf5a95ff7
2,936
hpp
C++
include/mex_cv_4b.hpp
davin11/GNLM
73ec2a9b4a1091e7e00283f2dfc6ebc6fdfb3679
[ "BSD-4-Clause-UC" ]
7
2018-12-18T12:31:13.000Z
2022-02-22T16:39:42.000Z
include/mex_cv_4b.hpp
davin11/GNLM
73ec2a9b4a1091e7e00283f2dfc6ebc6fdfb3679
[ "BSD-4-Clause-UC" ]
1
2020-05-04T04:37:19.000Z
2020-05-04T04:37:19.000Z
include/mex_cv_4b.hpp
davin11/GNLM
73ec2a9b4a1091e7e00283f2dfc6ebc6fdfb3679
[ "BSD-4-Clause-UC" ]
4
2020-11-05T13:14:53.000Z
2022-03-20T11:06:15.000Z
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // Copyright (c) 2012 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA'). // All rights reserved. // This software should be used, reproduced and modified only for informational and nonprofit purposes. // // By downloading and/or using any of these files, you implicitly agree to all the // terms of the license, as specified in the document LICENSE.txt // (included in this package) and online at // http://www.grip.unina.it/download/LICENSE_OPEN.txt // //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #ifdef MATLAB_MEX_FILE #ifndef MEX_CV_4B_HPP #define MEX_CV_4B_HPP #include <opencv/cv.h> #include "mex.h" #include "matrix.h" #include <vector> template <int K> void mx2cv(const mxArray* mx, cv::Mat_< cv::Vec<float, K> > &mat) { // check the type if( ! mxIsDouble(mx) ) mexErrMsgTxt("The array must be double"); // get the matrix size mwSize D = mxGetNumberOfDimensions(mx); if (D<3) mexErrMsgTxt("The array must be 3d"); const size_t* DD = mxGetDimensions(mx); mwSize M = DD[0]; mwSize N = DD[1]; mwSize KK = DD[2]; mwSize Slide = M*N; if (KK>K) mexErrMsgTxt("The array has too bands"); //mexPrintf(" %d x %d x %d \n", M,N,DD[2]); cv::Vec<float, K> elem; for(int k=0; k<K; k++) elem[k] = 0.0; // create the matrix mat.create(M,N); //mexPrintf("\n %d %d %d %d \n",mat.elemSize(),mat.step1(),mat.rows,mat.cols ); // fill the matrix double* mx_real = mxGetPr(mx); for(int n=0; n < N; n++) { for(int m=0; m < M; m++) { for(int k=0; k<KK; k++) elem[k] = (float)(*(mx_real+k*Slide)); mat(m,n) = elem; //mexPrintf(" (%d %d) %f x %f x %f x %f \n", m,n, elem[0],elem[1],elem[2],elem[3]); mx_real++; } } } mxArray* cv2mx(const cv::Mat_< cv::Vec<float, 4> > mat) { // get the matrix size mwSize M = mat.rows;//-3; mwSize N = mat.cols; //-3; mwSize dims[] = {M, N, 4}; mwSize Slide2 = M*N; mwSize Slide3 = 2*Slide2; mwSize Slide4 = 3*Slide2; mexPrintf(" %d x %d x %d \n", M,N,4); // create the matrix mxArray* mx = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL); // fill the matrix double* mx_real = mxGetPr(mx); for(int n=0; n < N; n++) for(int m=0; m < M; m++) { cv::Vec<float, 4> elem = mat(m,n); *(mx_real+Slide4) = (double)elem[3]; *(mx_real+Slide3) = (double)elem[2]; *(mx_real+Slide2) = (double)elem[1]; *(mx_real ) = (double)elem[0]; mx_real++; //mexPrintf(" (%d %d) %f x %f x %f x %f \n", m,n, elem[0],elem[1],elem[2],elem[3]); } return mx; } #endif #endif
31.234043
106
0.521117
[ "vector", "3d" ]
348b133f18875fe36aa202f08ac0b1cfc4f8614b
4,658
cpp
C++
src/CNFA.cpp
alexander-smoktal/pattern-engine
49a500008c278d8f9ee3ca233418aee68fb9e8d2
[ "Apache-2.0" ]
null
null
null
src/CNFA.cpp
alexander-smoktal/pattern-engine
49a500008c278d8f9ee3ca233418aee68fb9e8d2
[ "Apache-2.0" ]
null
null
null
src/CNFA.cpp
alexander-smoktal/pattern-engine
49a500008c278d8f9ee3ca233418aee68fb9e8d2
[ "Apache-2.0" ]
null
null
null
#include "CNFA.h" CNFA::CNFA(const std::shared_ptr<CState> &start_state, const std::shared_ptr<CState> &end_state) : _start_state(start_state) , _final_state(end_state) { _final_state->setIsFinalState(true); } CNFA::~CNFA() { // NFA start state is the only entry point for the NFA graph. If we are going to // destroy entry state, we resolve graph cyclic dependency first. if (_start_state.use_count() == 1) { _start_state->deinit(); } } void CNFA::addState(const std::shared_ptr<CState> &state, std::unordered_set<std::shared_ptr<CState>> &state_set) { if (state_set.count(state)) { return; } state_set.insert(state); for (const auto &eps : state->epsilonTransitions()) { addState(eps, state_set); } } void CNFA::addMultistate(const std::shared_ptr<CState> &state, std::vector<std::shared_ptr<CState>> &state_vector) { state_vector.push_back(state); for (const auto &eps : state->epsilonTransitions()) { addMultistate(eps, state_vector); } } bool CNFA::match(const std::string &source) const { if (!source.size()) { throw std::invalid_argument("Empty string"); } // current_states contain intermediate states across all string parsing std::unordered_set<std::shared_ptr<CState>> current_states; addState(_start_state, current_states); for (const auto &character : source) { std::unordered_set<std::shared_ptr<CState>> next_states; // For each state check if it accepts the character. If so, move transition for the character into the intermediate states for (const auto &state : current_states) { if (state->transitions().count(character)) { auto transition_state = state->transitions().at(character); addState(transition_state, next_states); } } current_states = next_states; } // Check if any of current states is a final state. If so, string fully matches the pattern for (const auto &state : current_states) { if (state->isFinalState()) { return true; } } return false; } int CNFA::countGroups(const std::string &source) const { if (!source.size()) { throw std::invalid_argument("Empty string"); } int result{ 0 }; // current_states contain intermediate states across all string parsing std::unordered_set<std::shared_ptr<CState>> current_states; for (const auto &character : source) { // The function itself is very similar to the match function. The differences are that we add own start state // for each characetter to see if we may start matching here. Also we check for finite states during iteration addState(_start_state, current_states); std::unordered_set<std::shared_ptr<CState>> next_states; // For each state check if it accepts the character. If so, move transition for the character into the intermediate states for (const auto &state : current_states) { if (state->transitions().count(character)) { auto transition_state = state->transitions().at(character); // Here we check if we get final state, which means we got a match. // Here we reset states to initial to start new group matching if (transition_state->isFinalState()) { ++result; next_states.clear(); next_states.insert(_start_state); break; } else { addState(transition_state, next_states); } } } current_states = next_states; } return result; } int CNFA::count(const std::string &source) const { if (!source.size()) { throw std::invalid_argument("Empty string"); } int result{ 0 }; // current_states contain intermediate states across all string parsing std::vector<std::shared_ptr<CState>> current_states; for (const auto &character : source) { // The function itself is very similar to the match function. The differences are that we add own start state // for each characetter to see if we may start matching here. Also we check for finite states during iteration. // Note: we use multistates here to search for overlapping matches. addMultistate(_start_state, current_states); std::vector<std::shared_ptr<CState>> next_states; // For each state check if it accepts the character. If so, move transition for the character into the intermediate states for (const auto &state : current_states) { if (state->transitions().count(character)) { auto transition_state = state->transitions().at(character); addMultistate(transition_state, next_states); // Here we check if we get final state, which means we got a match if (transition_state->isFinalState()) { ++result; } } } current_states = next_states; } return result; } std::string CNFA::toString() const { std::unordered_set<size_t> set; return _start_state->toString(set); }
30.246753
124
0.719622
[ "vector" ]
3496bfb3f77d2383a67c565f60f34309913b4253
76,157
cpp
C++
AuditRules.cpp
kovdan01/OMS-Auditd-Plugin
529db434129f43f5763a405eb3357bedad757968
[ "MIT" ]
13
2019-07-01T04:58:51.000Z
2022-01-28T13:38:02.000Z
AuditRules.cpp
kovdan01/OMS-Auditd-Plugin
529db434129f43f5763a405eb3357bedad757968
[ "MIT" ]
16
2019-05-08T00:40:43.000Z
2021-07-27T23:11:26.000Z
AuditRules.cpp
kovdan01/OMS-Auditd-Plugin
529db434129f43f5763a405eb3357bedad757968
[ "MIT" ]
9
2019-12-19T00:06:53.000Z
2021-12-03T09:45:20.000Z
/* microsoft-oms-auditd-plugin Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "AuditRules.h" #include "Translate.h" #include "StringUtils.h" #include "KernelInfo.h" #include "FileUtils.h" #include "UserDB.h" #include <algorithm> #include <sstream> #include <unistd.h> #include <climits> #include <system_error> #include <pwd.h> #include <fcntl.h> #include <iostream> // Character that seperates key in AUDIT_FILTERKEY field in rules // This value mirrors what is defined for AUDIT_KEY_SEPARATOR in libaudit.h #define KEY_SEP 0x01 // This value mirrors what is defined for AUDIT_FILTER_MASK in libaudit.h // It is a mask of AUDIT_FILTER_* values defined in /usr/include/linux/audit.h // AUDIT_FILTER_PREPEND is excluded from thye mask. #define FILTER_MASK 0x7 #define AUDITD_RULES_FILE "/etc/audit/audit.rules" #define AUDITD_RULES_DIR "/etc/audit/rules.d" #define AUOMS_RULES_FILE_NAME "auoms.rules" #define AUOMS_AUDITD_RULES_FILE "/etc/audit/rules.d/auoms.rules" #define AUGENRULES_HEADER "## This file is automatically generated from" #define AUOMS_AUDITD_RULES_FILE_START_MARKER "#### START OF OMS AUDIT RULES ####" #define AUOMS_AUDITD_RULES_FILE_END_MARKER "#### END OF OMS AUDIT RULES ####" static std::string clean_path(const std::string& path) { std::string ret = path; while(ret.back() == '/') { ret.resize(ret.size()-1); } return ret; } static bool check_path(const std::string& path, std::string error) { if (path.size() >= PATH_MAX) { error = "path is too big"; return false; } if (path[0] != '/') { error = "path must start with '/'"; return false; } auto idx = path.rfind('/'); if (idx == std::string::npos) { return true; } if (path.size()-idx > NAME_MAX) { error = "The base name of the path is too big"; return false; } if (path.find("..") != std::string::npos) { error = "relative path notation is not supported"; return false; } if (path.find("*") != std::string::npos || path.find("?") != std::string::npos) { error = "wildcard notation is not supported"; return false; } return true; } bool AuditRule::IsDataValid(const void* data, size_t len) { auto rule = reinterpret_cast<const audit_rule_data*>(data); if (len < sizeof(audit_rule_data) || len < sizeof(audit_rule_data)+rule->buflen || rule->field_count >= AUDIT_MAX_FIELDS) { return false; } uint32_t offset = 0; for (int i = 0; i < rule->field_count; ++i) { switch (rule->fields[i] & ~AUDIT_OPERATORS) { case AUDIT_SUBJ_USER: /* fallthrough */ case AUDIT_SUBJ_ROLE: /* fallthrough */ case AUDIT_SUBJ_TYPE: /* fallthrough */ case AUDIT_SUBJ_SEN: /* fallthrough */ case AUDIT_SUBJ_CLR: /* fallthrough */ case AUDIT_OBJ_USER: /* fallthrough */ case AUDIT_OBJ_ROLE: /* fallthrough */ case AUDIT_OBJ_TYPE: /* fallthrough */ case AUDIT_OBJ_LEV_LOW: /* fallthrough */ case AUDIT_OBJ_LEV_HIGH: /* fallthrough */ case AUDIT_WATCH: /* fallthrough */ case AUDIT_DIR: /* fallthrough */ case AUDIT_EXE: /* fallthrough */ case AUDIT_FILTERKEY: offset += rule->values[i]; break; } } if (offset > len) { return false; } return true; } bool AuditRule::Parse(const std::string& text, std::string& error) { error.clear(); auto clean_text = trim_whitespace(text); if (clean_text.empty() || clean_text[0] == '#') { return false; } auto args = split(text, ' '); if (args.empty()) { return false; } if (args[0].size() < 2 || args[0][0] != '-') { error.append("Invalid option '"); error.append(args[0]); error.append("'"); return false; } bool watch = false; char rule_opt = args[0][1]; if (rule_opt == 'w' || rule_opt == 'W') { watch = true; SetSyscallAll(); if (rule_opt == 'W') { is_delete_rule = true; } if (!parse_add_w_arg(args[1], error)) { return false; } } else if (rule_opt != 'a' && rule_opt != 'A' && rule_opt != 'd') { return false; } else { if (rule_opt == 'A') { ruleptr()->flags |= AUDIT_FILTER_PREPEND; } else if (rule_opt == 'd') { is_delete_rule = true; } if (!parse_add_a_arg(args[1], error)) { return false; } } size_t idx = 2; while(idx < args.size()) { if (args[idx].size() < 2 || args[idx][0] != '-') { error.append("Invalid option '"); error.append(args[idx]); error.append("'"); return false; } if (idx+1 >= args.size()) { error.append("Missing value for option '"); error.append(args[idx]); error.append("'"); return false; } switch (args[idx][1]) { case 'A': /* fallthrough */ case 'd': /* fallthrough */ case 'a': error.append("The '-"); error.push_back(args[idx][1]); error.append("' option is not allowed with the '-"); error.push_back(rule_opt); error.append("' option"); return false; case 'W': /* fallthrough */ case 'w': error.append("The '-"); error.push_back(args[idx][1]); error.append("' option is not allowed with the '-"); error.push_back(rule_opt); error.append("' option"); return false; case 'p': if (!watch) { error.append("The '-p' option is not allowed with the '-"); error.push_back(rule_opt); error.append("' option"); return false; } if (!parse_add_p_arg(args[idx+1], error)) { return false; } idx += 2; break; case 'k': if (!parse_add_k_arg(args[idx+1], error)) { return false; } idx += 2; break; case 'S': if (watch) { error.append("The '-S' option is not allowed with the '-"); error.push_back(rule_opt); error.append("' option"); return false; } if ((ruleptr()->flags & FILTER_MASK) == AUDIT_FILTER_TASK) { error.append("The '-S' option is not allowed with the task rules"); return false; } if (!parse_add_S_arg(args[idx+1], error)) { return false; } idx += 2; break; case 'F': if (watch) { error.append("The '-F' option is not allowed with the '-"); error.push_back(rule_opt); error.append("' option"); return false; } if (args[idx].size() > 2) { if (!parse_add_F_arg(args[idx].substr(2), error)) { return false; } idx += 1; } else { if (!parse_add_F_arg(args[idx+1], error)) { return false; } idx += 2; } break; case 'C': if (watch) { error.append("The '-C' option is not allowed with the '-"); error.push_back(rule_opt); error.append("' option"); return false; } if (!parse_add_C_arg(args[idx+1], error)) { return false; } idx += 2; break; default: error.append("Unsupported option '"); error.append(args[idx]); error.append("'"); return false; } } return true; } std::unordered_map<std::string, uint32_t> s_a_actions( { {"never", AUDIT_NEVER}, // The value "possible" while present in the kernel code will result in a deprecation error. {"always", AUDIT_ALWAYS}, } ); std::unordered_map<std::string, uint32_t> s_a_flags( { {"task", AUDIT_FILTER_TASK}, {"exit", AUDIT_FILTER_EXIT}, {"user", AUDIT_FILTER_USER}, {"exclude", AUDIT_FILTER_TYPE}, } ); bool AuditRule::parse_add_a_arg(const std::string& val, std::string& error) { if (ruleptr()->action != 0 || (ruleptr()->flags & FILTER_MASK) != 0) { error.append("Multiple '-a' not allowed"); return false; } auto parts = split(val, ','); if (parts.size() != 2) { error.append("Invalid value for option '-a': '"); error.append(val); error.append("'"); return false; } bool action_found = false; for (auto& part: parts) { auto itr = s_a_actions.find(part); if (itr != s_a_actions.end()) { ruleptr()->action = itr->second; action_found = true; } } if (!action_found) { error.append("Invalid or missing action value for option '-a': '"); error.append(val); error.append("'"); return false; } bool flags_found = false; for (auto& part: parts) { auto itr = s_a_flags.find(part); if (itr != s_a_flags.end()) { ruleptr()->flags |= itr->second; flags_found = true; } } if (!flags_found) { error.append("Invalid or missing flags value for option '-a': '"); error.append(val); error.append("'"); return false; } return true; } bool AuditRule::parse_add_w_arg(const std::string& val, std::string& error) { if (has_field(AUDIT_WATCH) || has_field(AUDIT_DIR)) { error.append("Multiple '-w' not allowed"); return false; } auto path = clean_path(val); if (!check_path(path, error)) { error = "Invalid path for -w option: " + error; return false; } ruleptr()->flags = AUDIT_FILTER_EXIT; ruleptr()->action = AUDIT_ALWAYS; if (IsDir(path)) { add_str_field(AUDIT_DIR, AUDIT_EQUAL, path); } else { add_str_field(AUDIT_WATCH, AUDIT_EQUAL, path); } return true; } bool AuditRule::parse_add_p_arg(const std::string& val, std::string& error) { uint32_t perms = 0; for (auto c: val) { switch (c) { case 'a': perms |= AUDIT_PERM_ATTR; break; case 'r': perms |= AUDIT_PERM_READ; break; case 'w': perms |= AUDIT_PERM_WRITE; break; case 'x': perms |= AUDIT_PERM_EXEC; break; default: error.append("Invalid value for option '-p': '"); error.append(val); error.append("'"); return false; } } add_field(AUDIT_PERM, AUDIT_EQUAL, perms); return true; } bool AuditRule::parse_add_S_arg(const std::string& val, std::string& error) { if (val == "all") { SetSyscallAll(); return true; } auto arch = get_arch(); if (arch == 0 ) { error.append("Missing arch: Specify an arch value (via -F) prior to specifying any -S"); return false; } auto mtype = ArchToMachine(arch); if (mtype == MachineType::UNKNOWN) { error.append("Previously specified arch (via -F) is invalid"); return false; } auto parts = split(val, ','); for (auto& part: parts) { if (part.find_first_not_of("0123456789") == std::string::npos) { auto scall = std::atoi(part.c_str()); AddSyscall(scall); } else { auto scall = SyscallNameToNumber(mtype, part); if (scall < 0) { error.append("Invalid value for option '-S': Invalid syscall name: '"); error.append(part); error.append("'"); } AddSyscall(scall); } } return true; } std::unordered_map<std::string, uint32_t> s_F_ops( { {"=", AUDIT_EQUAL}, {"!=", AUDIT_NOT_EQUAL}, {">", AUDIT_GREATER_THAN}, {">=", AUDIT_GREATER_THAN_OR_EQUAL}, {"<", AUDIT_LESS_THAN}, {"<=", AUDIT_LESS_THAN_OR_EQUAL}, {"&", AUDIT_BIT_MASK}, {"&=", AUDIT_BIT_TEST}, } ); std::unordered_map<std::string, uint32_t> s_F_ftypes( { {"socket", S_IFSOCK}, {"link", S_IFLNK}, {"file", S_IFREG}, {"block", S_IFBLK}, {"dir", S_IFDIR}, {"character", S_IFCHR}, {"fifo", S_IFIFO}, } ); bool AuditRule::parse_add_F_arg(const std::string& val, std::string& error) { auto idx = val.find_first_of("=!<>&"); if (idx == 0) { error.append("Invalid value for option '-F': Missing field name: '"); error.append(val); error.append("'"); return false; } if (idx == std::string::npos) { error.append("Invalid value for option '-F': Missing operator: '"); error.append(val); error.append("'"); return false; } auto field_name = val.substr(0, idx); auto eidx = val.find_first_not_of("=!<>&", idx); if (eidx == std::string::npos) { error.append("Invalid value for option '-F': Missing value: '"); error.append(val); error.append("'"); return false; } auto op_str = val.substr(idx, eidx-idx); auto itr = s_F_ops.find(op_str); if (itr == s_F_ops.end()) { error.append("Invalid value for option '-F': Invalid operator: '"); error.append(val); error.append("'"); return false; } uint32_t op = itr->second; auto value = val.substr(eidx); if (value.empty()) { error.append("Invalid value for option '-F': Missing value: '"); error.append(val); error.append("'"); return false; } auto field = FieldNameToId(field_name); if (field < 0) { error.append("Invalid value for option '-F': Invalid field name: '"); error.append(val); error.append("'"); return false; } switch (field) { case AUDIT_UID: case AUDIT_EUID: case AUDIT_SUID: case AUDIT_FSUID: case AUDIT_LOGINUID: case AUDIT_OBJ_UID: try { if (std::isdigit(value[0])) { uint32_t v = static_cast<uint32_t>(stoul(value, 0, 0)); add_field(field, op, v); } else if (value.size() > 1 && value[0] == '-' && std::isdigit(value[1])) { uint32_t v = static_cast<uint32_t>(stol(value, 0, 0)); add_field(field, op, v); } else { if (value == "unset") { add_field(field, op, 4294967295); } else { auto uid = UserDB::UserNameToUid(value); if (uid < 0) { error.append("Invalid value for option '-F': Unknown username: '"); error.append(val); error.append("'"); return false; } add_field(field, op, uid); } } } catch (std::exception &) { error.append("Invalid value for option '-F': Invalid numeric value: '"); error.append(val); error.append("'"); return false; } break; case AUDIT_GID: case AUDIT_EGID: case AUDIT_SGID: case AUDIT_FSGID: case AUDIT_OBJ_GID: try { if (std::isdigit(value[0])) { uint32_t v = static_cast<uint32_t>(stoul(value, 0, 0)); add_field(field, op, v); } else if (value.size() > 1 && value[0] == '-' && std::isdigit(value[1])) { uint32_t v = static_cast<uint32_t>(stol(value, 0, 0)); add_field(field, op, v); } else { if (value == "unset") { add_field(field, op, 4294967295); } else { auto gid = UserDB::GroupNameToGid(value); if (gid < 0) { error.append("Invalid value for option '-F': Unknown group name: '"); error.append(val); error.append("'"); return false; } add_field(field, op, gid); } } } catch (std::exception &) { error.append("Invalid value for option '-F': Invalid numeric value: '"); error.append(val); error.append("'"); return false; } break; case AUDIT_EXIT: if ((ruleptr()->flags & FILTER_MASK) != AUDIT_FILTER_EXIT) { error.append("Invalid value for option '-F': Cannot filter on exit field unless flags (-a option) == 'exit'"); return false; } try { if (std::isdigit(value[0])) { uint32_t v = static_cast<uint32_t>(stoul(value, 0, 0)); add_field(field, op, v); } else if (value.size() > 1 && value[0] == '-' && std::isdigit(value[1])) { uint32_t v = static_cast<uint32_t>(stol(value, 0, 0)); add_field(field, op, v); } else { auto v = NameToErrno(value); if (v == 0) { error.append("Invalid value for option '-F': Invalid errno name: '"); error.append(val); error.append("'"); return false; } add_field(field, op, v); } } catch (std::exception &) { error.append("Invalid value for option '-F': Invalid numeric value: '"); error.append(val); error.append("'"); return false; } break; case AUDIT_MSGTYPE: if ((ruleptr()->flags & FILTER_MASK) != AUDIT_FILTER_TYPE) { error.append("Invalid value for option '-F': Cannot filter on msg type unless flags (-a option) == 'exclude'"); return false; } if (std::isdigit(value[0])) { try { uint32_t v = static_cast<uint32_t>(stoul(value, 0, 0)); add_field(field, op, v); } catch (std::exception &) { error.append("Invalid value for option '-F': Invalid numeric value: '"); error.append(val); error.append("'"); return false; } } else { auto rt = RecordNameToType(value); if (rt == RecordType::UNKNOWN) { error.append("Invalid value for option '-F': Invalid record type name: '"); error.append(val); error.append("'"); return false; } add_field(field, op, static_cast<uint32_t>(rt)); } break; case AUDIT_ARCH: { auto arch = ArchNameToArch(value); if (arch == 0) { error.append("Invalid value for option '-F': Invalid arch value: '"); error.append(val); error.append("'"); } if (op != AUDIT_EQUAL && op != AUDIT_NOT_EQUAL) { error.append("Invalid op("); error.append(op_str); error.append(") for option '-F': arch field only allows '=' and '!='"); } add_field(field, op, arch); break; } case AUDIT_PERM: { uint32_t perms = 0; for (auto c: value) { switch (c) { case 'a': perms |= AUDIT_PERM_ATTR; break; case 'r': perms |= AUDIT_PERM_READ; break; case 'w': perms |= AUDIT_PERM_WRITE; break; case 'x': perms |= AUDIT_PERM_EXEC; break; default: error.append("Invalid value for option '-F': Invalid permission character: '"); error.append(val); error.append("'"); return false; } } add_field(AUDIT_PERM, op, perms); break; } case AUDIT_OBJ_USER: /* fallthrough */ case AUDIT_OBJ_ROLE: /* fallthrough */ case AUDIT_OBJ_TYPE: /* fallthrough */ case AUDIT_OBJ_LEV_LOW: /* fallthrough */ case AUDIT_OBJ_LEV_HIGH: if (ruleptr()->flags != AUDIT_FILTER_EXIT) { error = "Field '" + field_name + "' can only be used with 'exit' filter"; return false; } add_str_field(field, op, value); break; case AUDIT_WATCH: /* fallthrough */ case AUDIT_DIR: { if (ruleptr()->flags != AUDIT_FILTER_EXIT) { error = "Field '" + field_name + "' can only be used with 'exit' filter"; return false; } auto path = clean_path(value); if (!check_path(path, error)) { error = "Invalid path option: " + error; return false; } add_str_field(field, op, path); break; } case AUDIT_SUBJ_USER: /* fallthrough */ case AUDIT_SUBJ_ROLE: /* fallthrough */ case AUDIT_SUBJ_TYPE: /* fallthrough */ case AUDIT_SUBJ_SEN: /* fallthrough */ case AUDIT_SUBJ_CLR: /* fallthrough */ case AUDIT_EXE: add_str_field(field, op, value); break; case AUDIT_FILTERKEY: AddKey(value); break; case AUDIT_FILETYPE: { if (ruleptr()->flags != AUDIT_FILTER_EXIT) { error = "Field '" + field_name + "' can only be used with 'exit' filter"; return false; } auto ft = s_F_ftypes.find(value); if (ft != s_F_ftypes.end()) { add_field(field, op, ft->second); } else { error.append("Invalid value for option '-F': Invalid filetype name: '"); error.append(val); error.append("'"); return false; } break; } default: try { uint32_t v = static_cast<uint32_t>(stol(value, 0, 0)); add_field(field, op, v); } catch (std::exception&) { error.append("Invalid value for option '-F': Invalid numeric value: '"); error.append(val); error.append("'"); return false; } } return true; } std::unordered_map<uint64_t, uint32_t> s_C_fields( { {(static_cast<uint64_t>(AUDIT_UID)<<32)|AUDIT_OBJ_UID, AUDIT_COMPARE_UID_TO_OBJ_UID}, {(static_cast<uint64_t>(AUDIT_GID)<<32)|AUDIT_OBJ_GID, AUDIT_COMPARE_GID_TO_OBJ_GID}, {(static_cast<uint64_t>(AUDIT_EUID)<<32)|AUDIT_OBJ_UID, AUDIT_COMPARE_EUID_TO_OBJ_UID}, {(static_cast<uint64_t>(AUDIT_EGID)<<32)|AUDIT_OBJ_GID, AUDIT_COMPARE_EGID_TO_OBJ_GID}, {(static_cast<uint64_t>(AUDIT_LOGINUID)<<32)|AUDIT_OBJ_UID, AUDIT_COMPARE_AUID_TO_OBJ_UID}, {(static_cast<uint64_t>(AUDIT_SUID)<<32)|AUDIT_OBJ_UID, AUDIT_COMPARE_SUID_TO_OBJ_UID}, {(static_cast<uint64_t>(AUDIT_SGID)<<32)|AUDIT_OBJ_GID, AUDIT_COMPARE_SGID_TO_OBJ_GID}, {(static_cast<uint64_t>(AUDIT_FSUID)<<32)|AUDIT_OBJ_UID, AUDIT_COMPARE_FSUID_TO_OBJ_UID}, {(static_cast<uint64_t>(AUDIT_FSGID)<<32)|AUDIT_OBJ_GID, AUDIT_COMPARE_FSGID_TO_OBJ_GID}, {(static_cast<uint64_t>(AUDIT_UID)<<32)|AUDIT_LOGINUID, AUDIT_COMPARE_UID_TO_AUID}, {(static_cast<uint64_t>(AUDIT_UID)<<32)|AUDIT_EUID, AUDIT_COMPARE_UID_TO_EUID}, {(static_cast<uint64_t>(AUDIT_UID)<<32)|AUDIT_FSUID, AUDIT_COMPARE_UID_TO_FSUID}, {(static_cast<uint64_t>(AUDIT_UID)<<32)|AUDIT_SUID, AUDIT_COMPARE_UID_TO_SUID}, {(static_cast<uint64_t>(AUDIT_LOGINUID)<<32)|AUDIT_FSUID, AUDIT_COMPARE_AUID_TO_FSUID}, {(static_cast<uint64_t>(AUDIT_LOGINUID)<<32)|AUDIT_SUID, AUDIT_COMPARE_AUID_TO_SUID}, {(static_cast<uint64_t>(AUDIT_LOGINUID)<<32)|AUDIT_EUID, AUDIT_COMPARE_AUID_TO_EUID}, {(static_cast<uint64_t>(AUDIT_EUID)<<32)|AUDIT_SUID, AUDIT_COMPARE_EUID_TO_SUID}, {(static_cast<uint64_t>(AUDIT_EUID)<<32)|AUDIT_FSUID, AUDIT_COMPARE_EUID_TO_FSUID}, {(static_cast<uint64_t>(AUDIT_SUID)<<32)|AUDIT_FSUID, AUDIT_COMPARE_SUID_TO_FSUID}, {(static_cast<uint64_t>(AUDIT_GID)<<32)|AUDIT_EGID, AUDIT_COMPARE_GID_TO_EGID}, {(static_cast<uint64_t>(AUDIT_GID)<<32)|AUDIT_FSGID, AUDIT_COMPARE_GID_TO_FSGID}, {(static_cast<uint64_t>(AUDIT_GID)<<32)|AUDIT_SGID, AUDIT_COMPARE_GID_TO_SGID}, {(static_cast<uint64_t>(AUDIT_EGID)<<32)|AUDIT_FSGID, AUDIT_COMPARE_EGID_TO_FSGID}, {(static_cast<uint64_t>(AUDIT_EGID)<<32)|AUDIT_SGID, AUDIT_COMPARE_EGID_TO_SGID}, {(static_cast<uint64_t>(AUDIT_SGID)<<32)|AUDIT_FSGID, AUDIT_COMPARE_SGID_TO_FSGID}, } ); bool AuditRule::parse_add_C_arg(const std::string& val, std::string& error) { auto idx = val.find_first_of("=!<>&"); if (idx == 0) { error.append("Invalid value for option '-C': Missing field name: '"); error.append(val); error.append("'"); return false; } if (idx == std::string::npos) { error.append("Invalid value for option '-C': Missing operator: '"); error.append(val); error.append("'"); return false; } auto field_name = val.substr(0, idx); auto eidx = val.find_first_not_of("=!<>&", idx); if (eidx == std::string::npos) { error.append("Invalid value for option '-C': Missing field2: '"); error.append(val); error.append("'"); return false; } auto op_str = val.substr(idx, eidx-idx); auto itr = s_F_ops.find(op_str); if (itr == s_F_ops.end()) { error.append("Invalid value for option '-C': Invalid operator: '"); error.append(val); error.append("'"); return false; } uint32_t op = itr->second; if (op != AUDIT_EQUAL && op != AUDIT_NOT_EQUAL) { error.append("Invalid value for option '-C': Invalid operator: '"); error.append(val); error.append("'"); return false; } auto field2_name = val.substr(eidx); if (field2_name.empty()) { error.append("Invalid value for option '-C': Missing field2: '"); error.append(val); error.append("'"); return false; } auto field1 = FieldNameToId(field_name); if (field1 < 0) { error.append("Invalid value for option '-C': Invalid field name: '"); error.append(val); error.append("'"); return false; } auto field2 = FieldNameToId(field2_name); if (field2 < 0) { error.append("Invalid value for option '-C': Invalid field name: '"); error.append(val); error.append("'"); return false; } auto citr = s_C_fields.find((static_cast<uint64_t>(field1)<<32)|field2); if (citr == s_C_fields.end()) { error.append("Invalid value for option '-C': Invalid field name combination: '"); error.append(val); error.append("'"); return false; } add_field(AUDIT_FIELD_COMPARE, op, citr->second); return true; } bool AuditRule::parse_add_k_arg(const std::string& val, std::string& error) { if (val.find(KEY_SEP) != std::string::npos) { error = "Invalid character in key"; return false; } AddKey(val); return true; } std::string AuditRule::CanonicalMergeKey() const { std::string text; auto watch = IsWatch(); if (!watch) { if (is_delete_rule) { text.append("-d "); } else if (ruleptr()->flags & AUDIT_FILTER_PREPEND) { text.append("-A "); } else { text.append("-a "); } append_action(text); text.append(","); append_flag(text); for (int i = 0; i < ruleptr()->field_count; ++i) { if ((ruleptr()->fields[i] & ~AUDIT_OPERATORS) == AUDIT_ARCH) { append_field(text, i, watch); } } } for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; if (field != AUDIT_ARCH && field != AUDIT_PERM && field != AUDIT_FILTERKEY) { append_field(text, i, watch); } } return text; } std::string AuditRule::CanonicalText() const { std::string text; auto watch = IsWatch(); if (!watch) { if (is_delete_rule) { text.append("-d "); } else if (ruleptr()->flags & AUDIT_FILTER_PREPEND) { text.append("-A "); } else { text.append("-a "); } append_action(text); text.append(","); append_flag(text); for (int i = 0; i < ruleptr()->field_count; ++i) { if ((ruleptr()->fields[i] & ~AUDIT_OPERATORS) == AUDIT_ARCH) { append_field(text, i, watch); } } append_syscalls(text); } for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; if (field != AUDIT_ARCH) { append_field(text, i, watch); } } return text; } std::string AuditRule::RawText() const { std::stringstream str; str << "Flags: " << std::hex << ruleptr()->flags << std::endl; str << "Action: " << std::hex << ruleptr()->action << std::endl; str << "Syscall: " << std::endl; for (int j = 0, i = 0; i < AUDIT_BITMASK_SIZE && j < 8; ++j) { str << " "; for (int x = 0; x < 8 && i < AUDIT_BITMASK_SIZE; i++, x++) { str << " " << std::hex << ruleptr()->mask[i]; } str << std::endl; } str << "FieldCount: " << std::dec << ruleptr()->field_count << std::endl; for (int i = 0; i < ruleptr()->field_count; ++i) { str << "Field[" << i << "]: " << std::dec << ruleptr()->fields[i] << ", " << std::hex << ruleptr()->values[i] << ", " << ruleptr()->fieldflags[i] << std::endl; } str << "Buflen: " << std::dec << ruleptr()->buflen << std::endl; auto bufstr = std::string(ruleptr()->buf, ruleptr()->buflen); auto idx = bufstr.find_first_of(0x1); while (idx != std::string::npos) { bufstr.replace(idx, 1, "\\0x01"); idx = bufstr.find_first_of(0x1); } str << "Buf: " << bufstr << std::endl; return str.str(); } bool AuditRule::IsValid() const { if (!IsDataValid(_data.data(), ruleptr()->buflen+sizeof(audit_rule_data))) { return false; } for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; if (field == AUDIT_FILTERKEY && ruleptr()->values[i] == 0) { return false; } } return true; } bool AuditRule::IsWatch() const { bool has_perm = false; for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; if (field == AUDIT_PERM) { has_perm = true; } else if (field != AUDIT_WATCH && field != AUDIT_DIR && field != AUDIT_FILTERKEY) { return false; } } if (!has_perm) { return false; } auto filter = ruleptr()->flags & FILTER_MASK; if (filter != AUDIT_FILTER_USER && filter != AUDIT_FILTER_TASK && filter != AUDIT_FILTER_TYPE) { return IsSyscallAll(); } return false; } bool AuditRule::IsLoadable() const { bool is_64bit = false; bool has_interfield_compare = false; bool has_exe_field = false; bool has_sessionid_field = false; bool has_dir_field = false; bool has_path_field = false; for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; switch (field) { case AUDIT_ARCH: if (__AUDIT_ARCH_64BIT & ruleptr()->values[i]) { is_64bit = true; } break; case AUDIT_SESSIONID: has_sessionid_field = true; break; case AUDIT_FIELD_COMPARE: has_interfield_compare = true; break; case AUDIT_EXE: has_exe_field = true; break; case AUDIT_DIR: has_dir_field = true; break; case AUDIT_WATCH: has_path_field = true; } } if (!KernelInfo::Is64bit() && is_64bit) { return false; } if (!KernelInfo::HasAuditSyscall() && !IsSyscallAll()) { return false; } if (!KernelInfo::HasAuditInterfieldCompare() && has_interfield_compare) { return false; } if (!KernelInfo::HasAuditExeField() && has_exe_field) { return false; } if (!KernelInfo::HasAuditSessionIdField() && has_sessionid_field) { return false; } // The kernel audit code will refuse to load a rule if the specified dir doesn't exist. if (has_dir_field) { auto str = get_str_field(AUDIT_DIR); if (!IsDir(str)) { return false; } } // The kernel audit code will refuse to load a rule if the specified path's parent dir doesn't exist. if (has_path_field) { auto str = get_str_field(AUDIT_WATCH); if (!IsDir(Dirname(str))) { return false; } } return true; } std::unordered_set<char> AuditRule::GetPerms() const { std::unordered_set<char> perms; for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; auto value = ruleptr()->values[i]; if (field == AUDIT_PERM) { if (value & AUDIT_PERM_READ) { perms.insert('r'); } if (value & AUDIT_PERM_WRITE) { perms.insert('w'); } if (value & AUDIT_PERM_EXEC) { perms.insert('x'); } if (value & AUDIT_PERM_ATTR) { perms.insert('a'); } } } return perms; } void AuditRule::AddPerm(char perm) { for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; auto value = ruleptr()->values[i]; if (field == AUDIT_PERM) { switch (perm) { case 'a': ruleptr()->values[i] |= AUDIT_PERM_ATTR; break; case 'r': ruleptr()->values[i] |= AUDIT_PERM_READ; break; case 'w': ruleptr()->values[i] |= AUDIT_PERM_WRITE; break; case 'x': ruleptr()->values[i] |= AUDIT_PERM_EXEC; break; } } } } void AuditRule::AddPerms(const std::unordered_set<char>& perms) { for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; auto value = ruleptr()->values[i]; if (field == AUDIT_PERM) { for (auto perm: perms) { switch (perm) { case 'a': ruleptr()->values[i] |= AUDIT_PERM_ATTR; break; case 'r': ruleptr()->values[i] |= AUDIT_PERM_READ; break; case 'w': ruleptr()->values[i] |= AUDIT_PERM_WRITE; break; case 'x': ruleptr()->values[i] |= AUDIT_PERM_EXEC; break; } } } } } void AuditRule::SetPerms(const std::unordered_set<char>& perms) { for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; auto value = ruleptr()->values[i]; if (field == AUDIT_PERM) { ruleptr()->values[i] = 0; for (auto perm: perms) { switch (perm) { case 'a': ruleptr()->values[i] |= AUDIT_PERM_ATTR; break; case 'r': ruleptr()->values[i] |= AUDIT_PERM_READ; break; case 'w': ruleptr()->values[i] |= AUDIT_PERM_WRITE; break; case 'x': ruleptr()->values[i] |= AUDIT_PERM_EXEC; break; } } } } } // Will return empty set if no syscalls, or syscall ALL std::unordered_set<int> AuditRule::GetSyscalls() const { std::unordered_set<int> syscalls; for (int i = 0; i < (AUDIT_BITMASK_SIZE-1); ++i) { if (ruleptr()->mask[i] != 0) { for (int x = 0; x < 32; ++x) { int s = (i*32)+x; if (ruleptr()->mask[i] & AUDIT_BIT(s)) { syscalls.insert(s); } } } } return syscalls; } bool AuditRule::IsSyscallAll() const { for (int i = 0; i < (AUDIT_BITMASK_SIZE-1); ++i) { if (ruleptr()->mask[i] != 0xFFFFFFFF) { return false; } } return true; } void AuditRule::SetSyscallAll() { for (auto& mask : ruleptr()->mask) { mask = 0xFFFFFFFF; } } void AuditRule::AddSyscall(int syscall) { int idx = AUDIT_WORD(syscall); if (idx >= AUDIT_BITMASK_SIZE) { return; } ruleptr()->mask[idx] |= AUDIT_BIT(syscall); } void AuditRule::AddSyscalls(const std::unordered_set<int>& syscalls) { for (auto s: syscalls) { int idx = AUDIT_WORD(s); if (idx < AUDIT_BITMASK_SIZE) { ruleptr()->mask[idx] |= AUDIT_BIT(s); } } } void AuditRule::SetSyscalls(const std::unordered_set<int>& syscalls) { ::memset(ruleptr()->mask, 0, sizeof(ruleptr()->mask)); for (auto s: syscalls) { int idx = AUDIT_WORD(s); if (idx < AUDIT_BITMASK_SIZE) { ruleptr()->mask[idx] |= AUDIT_BIT(s); } } } std::unordered_set<std::string> AuditRule::GetKeys() const { std::unordered_set<std::string> keys; for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; auto value = ruleptr()->values[i]; if (field == AUDIT_FILTERKEY) { std::string key_str(&ruleptr()->buf[_value_offsets[i]], value); for (auto& key: split(key_str, KEY_SEP)) { keys.insert(key); } } } return keys; } void AuditRule::AddKey(const std::string& key) { auto keys = GetKeys(); if (keys.count(key) > 0) { return; } keys.insert(key); SetKeys(keys); } void AuditRule::AddKeys(const std::unordered_set<std::string>& keys) { auto new_keys = GetKeys(); auto ksize= new_keys.size(); new_keys.insert(keys.begin(), keys.end()); if (new_keys.size() == ksize) { return; } SetKeys(new_keys); } void AuditRule::SetKeys(const std::unordered_set<std::string>& keys) { std::string key_str; if (!keys.empty()) { std::vector<std::string> key_list; key_list.reserve(keys.size()); size_t str_len = 0; for (auto &key: keys) { str_len += key.size(); key_list.emplace_back(key); } str_len += keys.size() - 1; std::sort(key_list.begin(), key_list.end()); key_str.reserve(str_len); for (auto &key: key_list) { if (!key_str.empty()) { key_str.push_back(KEY_SEP); } key_str.append(key); } if (key_str.size() > AUDIT_MAX_KEY_LEN) { throw std::runtime_error("Max key length exceeded"); } } for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; if (field == AUDIT_FILTERKEY) { remove_field(i); break; } } if (!key_str.empty()) { add_str_field(AUDIT_FILTERKEY, AUDIT_EQUAL, key_str); } } bool AuditRule::operator==(const AuditRule& rule) const { /* * When comparing ruleptr()->mask we ignore the last element in the array. * The reason for this is because then set to "all" the last element might be 0xFFFFFFFF or 0x0000FFFF. */ return ruleptr()->field_count == rule.ruleptr()->field_count && ruleptr()->action == rule.ruleptr()->action && ruleptr()->flags == rule.ruleptr()->flags && ruleptr()->buflen == rule.ruleptr()->buflen && ::memcmp(ruleptr()->mask, rule.ruleptr()->mask, (AUDIT_BITMASK_SIZE-1)*sizeof(ruleptr()->fields[0])) == 0 && ::memcmp(ruleptr()->fields, rule.ruleptr()->fields, ruleptr()->field_count*sizeof(ruleptr()->fields[0])) == 0 && ::memcmp(ruleptr()->fieldflags, rule.ruleptr()->fieldflags, ruleptr()->field_count*sizeof(ruleptr()->fieldflags[0])) == 0 && ::memcmp(ruleptr()->values, rule.ruleptr()->values, ruleptr()->field_count*sizeof(ruleptr()->values[0])) == 0 && ::memcmp(ruleptr()->buf, rule.ruleptr()->buf, ruleptr()->buflen) == 0; } bool AuditRule::has_field(uint32_t field) const { for (int i = 0; i < ruleptr()->field_count; ++i) { int f = ruleptr()->fields[i] & ~AUDIT_OPERATORS; if (field == f) { return true; } } return false; } uint32_t AuditRule::get_arch() const { for (int i = 0; i < ruleptr()->field_count; ++i) { int field = ruleptr()->fields[i] & ~AUDIT_OPERATORS; int op = ruleptr()->fieldflags[i] & AUDIT_OPERATORS; if (field == AUDIT_ARCH && op == AUDIT_EQUAL) { return ruleptr()->values[i]; } } return 0; } int AuditRule::add_field(uint32_t field, uint32_t op, uint32_t value) { if (ruleptr()->field_count >= (AUDIT_MAX_FIELDS-1)) { throw std::runtime_error("Max field count for rule exceeded"); } int idx = ruleptr()->field_count; ruleptr()->fields[idx] = field; ruleptr()->fieldflags[idx] = op; ruleptr()->values[idx] = value; ruleptr()->field_count += 1; return idx; } int AuditRule::add_str_field(uint32_t field, uint32_t op, const std::string& value) { auto idx = add_field(field, op, static_cast<uint32_t>(value.size())); auto offset = ruleptr()->buflen; value.copy(&ruleptr()->buf[ruleptr()->buflen], value.size()); ruleptr()->buflen += value.size(); _value_offsets[idx] = offset; return idx; } void AuditRule::remove_field(int idx) { if (idx >= ruleptr()->field_count) { return; } auto len = ruleptr()->values[idx]; auto offset = _value_offsets[idx]; auto mlen = ruleptr()->buflen - len - offset; if (mlen > 0) { ::memmove(&ruleptr()->buf[offset], &ruleptr()->buf[offset+len], mlen); } else { ::memset(&ruleptr()->buf[offset], 0, len); } ruleptr()->buflen -= len; for (int i = idx+1; i < ruleptr()->field_count; ++i) { ruleptr()->fields[i-1] = ruleptr()->fields[i]; ruleptr()->fieldflags[i-1] = ruleptr()->fieldflags[i]; ruleptr()->values[i-1] = ruleptr()->values[i]; if (_value_offsets[i] != 0) { _value_offsets[i-1] = _value_offsets[i]-len; } else { _value_offsets[i-1] = 0; } } ruleptr()->fields[ruleptr()->field_count-1] = 0; ruleptr()->fieldflags[ruleptr()->field_count-1] = 0; ruleptr()->values[ruleptr()->field_count-1] = 0; _value_offsets[ruleptr()->field_count-1] = 0; ruleptr()->field_count -= 1; } std::string AuditRule::get_str_field(uint32_t field) const { for (int i = 0; i < ruleptr()->field_count; ++i) { if (field == ruleptr()->fields[i] & ~AUDIT_OPERATORS) { auto offset = _value_offsets[i]; auto len = ruleptr()->values[i]; if (len > 0 && offset+len <= ruleptr()->buflen) { return std::string(&ruleptr()->buf[offset], len); } else { return std::string(); } } } return std::string(); } void AuditRule::append_field_name(std::string& out, int field) const { out.append(FieldIdToName(field)); } void AuditRule::append_op(std::string& out, int op) const { switch (op) { case AUDIT_EQUAL: out.append("="); break; case AUDIT_NOT_EQUAL: out.append("!="); break; case AUDIT_GREATER_THAN: out.append(">"); break; case AUDIT_GREATER_THAN_OR_EQUAL: out.append(">="); break; case AUDIT_LESS_THAN: out.append("<"); break; case AUDIT_LESS_THAN_OR_EQUAL: out.append("<="); break; case AUDIT_BIT_MASK: out.append("&"); break; case AUDIT_BIT_TEST: out.append("&="); break; default: out.append("???"); break; } } void AuditRule::fill_value_offsets() { _value_offsets.fill(0); uint32_t offset = 0; for (int i = 0; i < ruleptr()->field_count; ++i) { switch (ruleptr()->fields[i] & ~AUDIT_OPERATORS) { case AUDIT_SUBJ_USER: /* fallthrough */ case AUDIT_SUBJ_ROLE: /* fallthrough */ case AUDIT_SUBJ_TYPE: /* fallthrough */ case AUDIT_SUBJ_SEN: /* fallthrough */ case AUDIT_SUBJ_CLR: /* fallthrough */ case AUDIT_OBJ_USER: /* fallthrough */ case AUDIT_OBJ_ROLE: /* fallthrough */ case AUDIT_OBJ_TYPE: /* fallthrough */ case AUDIT_OBJ_LEV_LOW: /* fallthrough */ case AUDIT_OBJ_LEV_HIGH: /* fallthrough */ case AUDIT_WATCH: /* fallthrough */ case AUDIT_DIR: /* fallthrough */ case AUDIT_EXE: /* fallthrough */ case AUDIT_FILTERKEY: _value_offsets[i] = offset; offset += ruleptr()->values[i]; break; } } } void AuditRule::append_action(std::string& out) const { switch (ruleptr()->action) { case AUDIT_NEVER: out.append("never"); break; case AUDIT_POSSIBLE: out.append("possible"); break; case AUDIT_ALWAYS: out.append("always"); break; default: out.append("unknown-action("+std::to_string(ruleptr()->action)+")"); break; } } void AuditRule::append_flag(std::string& out) const { switch (ruleptr()->flags & FILTER_MASK) { case AUDIT_FILTER_TASK: out.append("task"); break; case AUDIT_FILTER_EXIT: out.append("exit"); break; case AUDIT_FILTER_USER: out.append("user"); break; case AUDIT_FILTER_TYPE: out.append("exclude"); break; case AUDIT_FILTER_FS: out.append("path"); break; default: out.append("unknown-flag("+std::to_string(ruleptr()->flags)+")"); break; } } /* */ void AuditRule::append_field(std::string& out, int idx, bool is_watch) const { int field = ruleptr()->fields[idx] & ~AUDIT_OPERATORS; int op = ruleptr()->fieldflags[idx] & AUDIT_OPERATORS; auto value = ruleptr()->values[idx]; switch(field) { case AUDIT_ARCH: out.append(" -F "); append_field_name(out, field); append_op(out, op); if (__AUDIT_ARCH_64BIT & value) { out.append("b64"); } else { out.append("b32"); } break; case AUDIT_MSGTYPE: out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append(RecordTypeToName(static_cast<RecordType>(value))); break; case AUDIT_SUBJ_USER: /* fallthrough */ case AUDIT_SUBJ_ROLE: /* fallthrough */ case AUDIT_SUBJ_TYPE: /* fallthrough */ case AUDIT_SUBJ_SEN: /* fallthrough */ case AUDIT_SUBJ_CLR: /* fallthrough */ case AUDIT_OBJ_USER: /* fallthrough */ case AUDIT_OBJ_ROLE: /* fallthrough */ case AUDIT_OBJ_TYPE: /* fallthrough */ case AUDIT_OBJ_LEV_LOW: /* fallthrough */ case AUDIT_OBJ_LEV_HIGH: out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append(std::string(&ruleptr()->buf[_value_offsets[idx]], value)); break; case AUDIT_INODE: out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append(std::to_string(value)); break; case AUDIT_EXIT: out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append(std::to_string(static_cast<int32_t>(value))); break; case AUDIT_WATCH: if (is_watch) { if (is_delete_rule) { out.append("-W "); } else { out.append("-w "); } } else { out.append(" -F "); append_field_name(out, field); append_op(out, op); } out.append(std::string(&ruleptr()->buf[_value_offsets[idx]], value)); break; case AUDIT_PERM: if (is_watch) { out.append(" -p "); } else { out.append(" -F "); append_field_name(out, field); append_op(out, op); } if (value & AUDIT_PERM_READ) { out.append("r"); } if (value & AUDIT_PERM_WRITE) { out.append("w"); } if (value & AUDIT_PERM_EXEC) { out.append("x"); } if (value & AUDIT_PERM_ATTR) { out.append("a"); } break; case AUDIT_DIR: if (is_watch) { if (is_delete_rule) { out.append("-W "); } else { out.append("-w "); } } else { out.append(" -F "); append_field_name(out, field); append_op(out, op); } out.append(std::string(&ruleptr()->buf[_value_offsets[idx]], value)); break; case AUDIT_FIELD_COMPARE: out.append(" -C "); switch (value) { case AUDIT_COMPARE_UID_TO_OBJ_UID: out.append("uid"); append_op(out, op); out.append("obj_uid"); break; case AUDIT_COMPARE_GID_TO_OBJ_GID: out.append("gid"); append_op(out, op); out.append("obj_gid"); break; case AUDIT_COMPARE_EUID_TO_OBJ_UID: out.append("euid"); append_op(out, op); out.append("obj_uid"); break; case AUDIT_COMPARE_EGID_TO_OBJ_GID: out.append("egid"); append_op(out, op); out.append("obj_gid"); break; case AUDIT_COMPARE_AUID_TO_OBJ_UID: out.append("auid"); append_op(out, op); out.append("obj_uid"); break; case AUDIT_COMPARE_SUID_TO_OBJ_UID: out.append("suid"); append_op(out, op); out.append("obj_uid"); break; case AUDIT_COMPARE_SGID_TO_OBJ_GID: out.append("sgid"); append_op(out, op); out.append("obj_gid"); break; case AUDIT_COMPARE_FSUID_TO_OBJ_UID: out.append("fsuid"); append_op(out, op); out.append("obj_uid"); break; case AUDIT_COMPARE_FSGID_TO_OBJ_GID: out.append("fsgid"); append_op(out, op); out.append("obj_gid"); break; case AUDIT_COMPARE_UID_TO_AUID: out.append("uid"); append_op(out, op); out.append("auid"); break; case AUDIT_COMPARE_UID_TO_EUID: out.append("uid"); append_op(out, op); out.append("euid"); break; case AUDIT_COMPARE_UID_TO_FSUID: out.append("uid"); append_op(out, op); out.append("fsuid"); break; case AUDIT_COMPARE_UID_TO_SUID: out.append("uid"); append_op(out, op); out.append("suid"); break; case AUDIT_COMPARE_AUID_TO_FSUID: out.append("auid"); append_op(out, op); out.append("fsuid"); break; case AUDIT_COMPARE_AUID_TO_SUID: out.append("auid"); append_op(out, op); out.append("suid"); break; case AUDIT_COMPARE_AUID_TO_EUID: out.append("auid"); append_op(out, op); out.append("euid"); break; case AUDIT_COMPARE_EUID_TO_SUID: out.append("euid"); append_op(out, op); out.append("suid"); break; case AUDIT_COMPARE_EUID_TO_FSUID: out.append("euid"); append_op(out, op); out.append("fsuid"); break; case AUDIT_COMPARE_SUID_TO_FSUID: out.append("suid"); append_op(out, op); out.append("fsuid"); break; case AUDIT_COMPARE_GID_TO_EGID: out.append("gid"); append_op(out, op); out.append("egid"); break; case AUDIT_COMPARE_GID_TO_FSGID: out.append("gid"); append_op(out, op); out.append("fsgid"); break; case AUDIT_COMPARE_GID_TO_SGID: out.append("gid"); append_op(out, op); out.append("sgid"); break; case AUDIT_COMPARE_EGID_TO_FSGID: out.append("egid"); append_op(out, op); out.append("fsgid"); break; case AUDIT_COMPARE_EGID_TO_SGID: out.append("egid"); append_op(out, op); out.append("sgid"); break; case AUDIT_COMPARE_SGID_TO_FSGID: out.append("sgid"); append_op(out, op); out.append("fsgid"); break; } break; case AUDIT_EXE: out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append(std::string(&ruleptr()->buf[_value_offsets[idx]], value)); break; case AUDIT_ARG0: /* fallthrough */ case AUDIT_ARG1: /* fallthrough */ case AUDIT_ARG2: /* fallthrough */ case AUDIT_ARG3: { char val[32]; snprintf(val, sizeof(val), "%X", value); out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append("0x"); out.append(val); break; } case AUDIT_FILTERKEY: { std::string keys_str(&ruleptr()->buf[_value_offsets[idx]], value); auto keys = split(keys_str, KEY_SEP); for (auto& key: keys) { if (is_watch) { out.append(" -k "); } else { out.append(" -F key="); } out.append(key); } break; } default: out.append(" -F "); append_field_name(out, field); append_op(out, op); out.append(std::to_string(static_cast<int32_t>(value))); break; } } void AuditRule::append_syscalls(std::string& out) const { MachineType mach = DetectMachine(); for (int i = 0; i < AUDIT_MAX_FIELDS; ++i) { if ((ruleptr()->fields[i] & ~AUDIT_OPERATORS) == AUDIT_ARCH && (ruleptr()->fieldflags[i] & AUDIT_OPERATORS) == AUDIT_EQUAL) { mach = ArchToMachine(ruleptr()->values[i]); } } bool has_syscall = false; if (IsSyscallAll()) { out.append(" -S all"); return; } else { for (int i = 0; i < AUDIT_BITMASK_SIZE; ++i) { if (ruleptr()->mask[i] != 0) { has_syscall = true; break; } } } if (has_syscall) { out.append(" -S "); bool first = true; for (int i = 0; i < AUDIT_BITMASK_SIZE; ++i) { if (ruleptr()->mask[i] != 0) { for (int x = 0; x < 32; ++x) { int s = (i*32)+x; if (ruleptr()->mask[i] & AUDIT_BIT(s)) { if (!first) { out.append(","); } auto name = SyscallToName(mach, s); if (starts_with(name, "unknown-syscall")) { out.append(std::to_string(s)); } else { out.append(name); } first = false; } } } } } } void ReplaceSection(std::vector<std::string>& lines, const std::vector<std::string>& replacement, const std::string& start_marker, const std::string& end_marker) { auto start = std::find(lines.begin(), lines.end(), start_marker); auto end = std::find(lines.begin(), lines.end(), end_marker); if (start != lines.end() && end == lines.end()) { throw std::runtime_error("Missing end marker"); } if (start == lines.end() && end != lines.end()) { throw std::runtime_error("Missing start marker"); } if (start != lines.end() && end != lines.end() && start > end) { throw std::runtime_error("Start and end markers are inverted"); } if (start == lines.end() && end == lines.end()) { start = lines.end(); } else { ++end; start = lines.erase(start, end); } if (replacement.empty()) { return; } start = lines.insert(start, start_marker); ++start; start = lines.insert(start, replacement.begin(), replacement.end()); start += replacement.size(); lines.insert(start, end_marker); } void RemoveSection(std::vector<std::string>& lines, const std::string& start_marker, const std::string& end_marker) { auto start = std::find(lines.begin(), lines.end(), start_marker); auto end = std::find(lines.begin(), lines.end(), end_marker); if (start != lines.end() && end == lines.end()) { throw std::runtime_error("Missing end marker"); } if (start == lines.end() && end != lines.end()) { throw std::runtime_error("Missing start marker"); } if (start == lines.end() && end == lines.end()) { return; } if (start > end) { throw std::runtime_error("Start and end markers are inverted"); } ++end; lines.erase(start, end); } std::vector<AuditRule> ParseRules(const std::vector<std::string>& lines, std::vector<std::string>* errors) { std::vector<AuditRule> rules; for (int i = 0; i < lines.size(); ++i) { AuditRule rule; std::string error; if (rule.Parse(lines[i], error)) { rules.emplace_back(rule); } else if (!error.empty()) { if (errors != nullptr) { errors->emplace_back("Failed to parse line " + std::to_string(i + 1) + ": " + error); } else { throw std::runtime_error("Failed to parse line " + std::to_string(i + 1) + ": " + error); } } } return rules; } template<typename T> T diff_set(T a, T b) { T ret; for (auto& e: b) { if (a.find(e) == a.end()) { ret.emplace(e); } } return ret; } // Merge perms, syscalls, and keys from srule into drule void merge_rule(AuditRule& drule, const AuditRule& srule) { if (drule.IsWatch()) { auto diff = diff_set(drule.GetPerms(), srule.GetPerms()); if (!diff.empty()) { drule.AddPerms(diff); } } else { if (srule.IsSyscallAll()) { drule.SetSyscallAll(); } else { auto diff = diff_set(drule.GetSyscalls(), srule.GetSyscalls()); if (!diff.empty()) { drule.AddSyscalls(diff); } } } auto diff = diff_set(drule.GetKeys(), srule.GetKeys()); if (!diff.empty()) { drule.AddKeys(diff); } } // Assumes that drule and srule have the same CanonicalMergeKey() value // Returns true if srule is a strict subset (perms or syscalls) of drule bool is_subset(const AuditRule& drule, const AuditRule& srule) { if (drule.IsWatch()) { auto diff = diff_set(drule.GetPerms(), srule.GetPerms()); return diff.empty(); } else { if (drule.IsSyscallAll()) { return true; } else { auto diff = diff_set(drule.GetSyscalls(), srule.GetSyscalls()); return diff.empty(); } } } // Assumes that drule and srule have the same CanonicalMergeKey() value // Returns rule that has perms and syscalls found in srule that where not in drule. // Returned rule will have same CanonicalMergeKey() and keys as srule. AuditRule diff_rule(const AuditRule& drule, const AuditRule& srule) { AuditRule rule = drule; if (drule.IsWatch()) { auto diff = diff_set(drule.GetPerms(), srule.GetPerms()); rule.SetPerms(diff); } else { auto diff = diff_set(drule.GetSyscalls(), srule.GetSyscalls()); rule.SetSyscalls(diff); } rule.SetKeys(srule.GetKeys()); return rule; } std::vector<AuditRule> MergeRules(const std::vector<AuditRule>& rules1) { std::vector<AuditRule> rules; std::unordered_map<std::string, size_t> indexes; for (auto& rule: rules1) { auto key = rule.CanonicalMergeKey(); auto itr = indexes.find(key); if (itr == indexes.end()) { rules.emplace_back(rule); indexes.emplace(key, rules.size()-1); } else { auto& r = rules[itr->second]; merge_rule(r, rule); } } return rules; } std::vector<AuditRule> MergeRules(const std::vector<AuditRule>& rules1, const std::vector<AuditRule>& rules2) { std::vector<AuditRule> rules; std::unordered_map<std::string, size_t> indexes; for (auto& rule: rules1) { auto key = rule.CanonicalMergeKey(); auto itr = indexes.find(key); if (itr == indexes.end()) { rules.emplace_back(rule); indexes.emplace(key, rules.size()-1); } else { auto& r = rules[itr->second]; merge_rule(r, rule); } } for (auto& rule: rules2) { auto key = rule.CanonicalMergeKey(); auto itr = indexes.find(key); if (itr == indexes.end()) { rules.emplace_back(rule); indexes.emplace(key, rules.size()-1); } else { auto& r = rules[itr->second]; merge_rule(r, rule); } } return rules; } // Return set of rules that when added to actual, at least represents the desired // If rule in actual has a key matching match_key, and that rule matches the canonical(-F) of a desired but not the perm/syscall // Then the returned rules will include new rule plus delete rule // Assumes desired rules are already "merged" std::vector<AuditRule> DiffRules(const std::vector<AuditRule>& actual, const std::vector<AuditRule>& desired, const std::string& match_key) { std::vector<AuditRule> rules; std::unordered_map<std::string, size_t> ridxs; std::unordered_map<std::string, size_t> aidxs; for (int i = 0; i < actual.size(); ++i) { aidxs.emplace(actual[i].CanonicalMergeKey(), i); } for(auto& drule: desired) { auto aitr = aidxs.find(drule.CanonicalMergeKey()); if (aitr == aidxs.end()) { rules.emplace_back(drule); ridxs.emplace(drule.CanonicalMergeKey(), rules.size()-1); } else { auto& arule = actual[aitr->second]; if (!is_subset(arule, drule)) { auto diff = diff_rule(arule, drule); rules.emplace_back(diff); ridxs.emplace(diff.CanonicalMergeKey(), rules.size()-1); } } } return rules; } std::vector<AuditRule> ReadAuditRulesFromDir(const std::string& dir, std::vector<std::string>* errors) { std::vector<std::string> files; std::vector<AuditRule> rules; files = GetDirList(dir); for(auto& file: files) { if (ends_with(file, ".rules")) { auto lines = ReadFile(dir + "/" + file); rules = MergeRules(rules, ParseRules(lines, errors)); } } return rules; } // Read rules from auditd rules.d dir std::vector<AuditRule> ReadAuditdRulesDir(bool exclude_auoms, std::vector<std::string>* errors) { std::vector<std::string> files; std::vector<AuditRule> rules; files = GetDirList(AUDITD_RULES_DIR); for(auto& file: files) { if (ends_with(file, ".rules")) { auto lines = ReadFile(std::string(AUDITD_RULES_DIR) + "/" + file); std::vector<std::string> file_errors; if (exclude_auoms) { auto in_rules = ParseRules(lines, &file_errors); std::vector<AuditRule> out_rules; out_rules.reserve(in_rules.size()); // Only include non-auoms rules for (auto &rule: in_rules) { auto keys = rule.GetKeys(); if (keys.count(AUOMS_RULE_KEY) == 0) { out_rules.emplace_back(rule); } } rules = MergeRules(rules, out_rules); } else { rules = MergeRules(rules, ParseRules(lines, &file_errors)); } if (errors != nullptr) { for (auto &err : file_errors) { errors->emplace_back("Encountered parse error in '" + std::string(AUDITD_RULES_DIR) + "/" + file + "': " + err); } } else { std::stringstream ss; ss << "Encountered parse errors in '" << std::string(AUDITD_RULES_DIR) << "/" << file << "': " << std::endl; for (auto &err : file_errors) { ss << " " << err << std::endl; } throw std::runtime_error(ss.str()); } } } return rules; } // Adds auoms's desired rules to auoms rules file in auditd rule.d dir void WriteAuomsRuleToAuditDir(const std::vector<AuditRule>& rules) { if (rules.empty()) { unlink(AUOMS_AUDITD_RULES_FILE); } else { std::vector<std::string> rule_lines; for (auto &rule: rules) { rule_lines.emplace_back(rule.CanonicalText()); } WriteFile(AUOMS_AUDITD_RULES_FILE, rule_lines); } } // Adds auoms's desired rules to auditd rules file void WriteAuomsRulesToAuditFile(const std::vector<AuditRule>& rules) { auto lines = ReadFile(AUDITD_RULES_FILE); if (rules.empty()) { RemoveSection(lines, AUOMS_AUDITD_RULES_FILE_START_MARKER, AUOMS_AUDITD_RULES_FILE_END_MARKER); } else { std::vector<std::string> rule_lines; for (auto &rule: rules) { rule_lines.emplace_back(rule.CanonicalText()); } ReplaceSection(lines, rule_lines, AUOMS_AUDITD_RULES_FILE_START_MARKER, AUOMS_AUDITD_RULES_FILE_END_MARKER); } WriteFile(AUDITD_RULES_FILE, lines); } bool HasAuditdRulesFiles() { return PathExists(AUDITD_RULES_FILE); } std::vector<AuditRule> ReadActualAuditdRules(bool exclude_auoms, std::vector<std::string>* errors) { if (!PathExists(AUDITD_RULES_FILE)) { return std::vector<AuditRule>(); } auto lines = ReadFile(AUDITD_RULES_FILE); // If the audit.rules file was at any time in the past generated with augenrules // assume it is still in use if (PathExists(AUGENRULES_BIN) && lines.size() > 0 && starts_with(lines[0], AUGENRULES_HEADER)) { return ReadAuditdRulesDir(exclude_auoms, errors); } else { std::vector<AuditRule> rules; std::vector<std::string> file_errors; if (exclude_auoms) { // Remove the auoms rules section if present. RemoveSection(lines, AUOMS_AUDITD_RULES_FILE_START_MARKER, AUOMS_AUDITD_RULES_FILE_END_MARKER); auto in_rules = ParseRules(lines, &file_errors); std::vector<AuditRule> out_rules; out_rules.reserve(in_rules.size()); // Only include non-auoms rules for (auto &rule: in_rules) { auto keys = rule.GetKeys(); if (keys.count(AUOMS_RULE_KEY) == 0) { out_rules.emplace_back(rule); } } rules = MergeRules({}, out_rules); } else { rules = MergeRules({}, ParseRules(lines, &file_errors)); } if (errors != nullptr) { for (auto &err : file_errors) { errors->emplace_back("Encountered parse error in '" + std::string(AUDITD_RULES_FILE) + "': " + err); } } else { std::stringstream ss; ss << "Encountered parse errors in '" << std::string(AUDITD_RULES_FILE) << "': " << std::endl; for (auto &err : file_errors) { ss << " " << err << std::endl; } throw std::runtime_error(ss.str()); } return rules; } } bool WriteAuditdRules(const std::vector<AuditRule>& rules) { auto lines = ReadFile(AUDITD_RULES_FILE); if (PathExists(AUGENRULES_BIN) && !lines.empty() && starts_with(lines[0], AUGENRULES_HEADER)) { WriteAuomsRuleToAuditDir(rules); return true; } else { WriteAuomsRulesToAuditFile(rules); // If rules dir exists, also write rules to it, in case system owner switches to using augenrules if (PathExists(AUDITD_RULES_DIR)) { WriteAuomsRuleToAuditDir(rules); } } return false; } // Remove auoms's desired rules to auditd config // Returns true if augenrules needs to be run bool RemoveAuomsRulesAuditdFiles() { std::vector<std::string> errors; bool has_auoms_rules = false; auto rules = ReadActualAuditdRules(false, &errors); for (auto &rule: rules) { auto keys = rule.GetKeys(); if (keys.count(AUOMS_RULE_KEY) > 0) { has_auoms_rules = true; break; } } if (has_auoms_rules) { return WriteAuditdRules({}); } return false; }
33.832519
464
0.504747
[ "vector" ]
349fa317b29cee36b90468081f0e99e9af7c8a26
1,106
cpp
C++
src/lib/storage/AbstractIndex.cpp
EvilMcJerkface/hyrise-v1
d97fa0df5b9e2b9aaa78865c010e93173404086d
[ "MIT" ]
7
2017-11-13T11:02:59.000Z
2022-02-05T11:49:35.000Z
src/lib/storage/AbstractIndex.cpp
EvilMcJerkface/hyrise-v1
d97fa0df5b9e2b9aaa78865c010e93173404086d
[ "MIT" ]
null
null
null
src/lib/storage/AbstractIndex.cpp
EvilMcJerkface/hyrise-v1
d97fa0df5b9e2b9aaa78865c010e93173404086d
[ "MIT" ]
6
2017-10-19T13:34:08.000Z
2020-11-30T13:14:47.000Z
// Copyright (c) 2012 Hasso-Plattner-Institut fuer Softwaresystemtechnik GmbH. All rights reserved. #include <storage/AbstractIndex.h> namespace hyrise { namespace storage { AbstractIndex::AbstractIndex() {}; AbstractIndex::AbstractIndex(std::string id) : _id(id) {} AbstractIndex::~AbstractIndex() {} std::string AbstractIndex::getId() { return _id; } std::shared_ptr<AbstractIndex> AbstractIndex::recreateIndex(const c_atable_ptr_t& in, field_t column) { throw std::runtime_error("The index did not implement the recreateIndex method!"); } std::shared_ptr<AbstractIndex> AbstractIndex::recreateIndexMergeDict(size_t column, std::shared_ptr<Store> store, std::shared_ptr<AbstractDictionary>& newDictReturn, std::vector<value_id_t>& x, std::vector<value_id_t>& Vd) { return nullptr; } } } // namespace hyrise::storage
39.5
120
0.576854
[ "vector" ]
34bc5636da46a8af1e70324fb10d1bb077d67827
2,728
cpp
C++
mplugins/cameras_mplugin/src/cameras/flow/RaspiCam.cpp
mico-corp/mico
45febf13da8c919eea77af9fa3b91afeb324f81b
[ "MIT" ]
3
2020-02-08T19:47:14.000Z
2022-03-14T14:13:29.000Z
mplugins/cameras_mplugin/src/cameras/flow/RaspiCam.cpp
mico-corp/mico
45febf13da8c919eea77af9fa3b91afeb324f81b
[ "MIT" ]
10
2020-01-29T21:27:12.000Z
2022-03-22T17:03:02.000Z
mplugins/cameras_mplugin/src/cameras/flow/RaspiCam.cpp
mico-corp/mico
45febf13da8c919eea77af9fa3b91afeb324f81b
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------------------------------------------------- // Cameras wrapper MICO plugin //--------------------------------------------------------------------------------------------------------------------- // Copyright 2020 Pablo Ramon Soria (a.k.a. Bardo91) pabramsor@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. //--------------------------------------------------------------------------------------------------------------------- #ifdef MICO_IS_RASPBIAN #include <mico/cameras/flow/RaspiCam.h> #include <flow/Outpipe.h> namespace mico{ namespace cameras { RaspiCam::RaspiCam() { createPipe<cv::Mat>("Color"); } bool RaspiCam::configure(std::vector<flow::ConfigParameterDef> _params) { if (isRunningLoop()) // Cant configure if already running. return false; return camera_.open(); } std::vector<flow::ConfigParameterDef> RaspiCam::parameters() { return { {} }; } void RaspiCam::loopCallback() { while (isRunningLoop()) { if (auto pipe = getPipe("Color"); pipe->registrations() != 0) { cv::Mat image; if(camera_.grab()) { camera_.retrieve(image); pipe->flush(image); } } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } } #endif
43.301587
119
0.519062
[ "vector" ]
34bdef10ab74702e6285c9a618ac7bc0f181f4c4
2,802
cpp
C++
src/PureGravComp.cpp
ndehio/mc_franka
230fda2c0f872ccd9cd387159b46ca769930519b
[ "BSD-2-Clause" ]
null
null
null
src/PureGravComp.cpp
ndehio/mc_franka
230fda2c0f872ccd9cd387159b46ca769930519b
[ "BSD-2-Clause" ]
null
null
null
src/PureGravComp.cpp
ndehio/mc_franka
230fda2c0f872ccd9cd387159b46ca769930519b
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <array> #include <atomic> #include <cmath> #include <functional> #include <iostream> #include <iterator> #include <mutex> #include <thread> #include <Eigen/Core> #include <Eigen/Eigen> #include <franka/duration.h> #include <franka/exception.h> #include <franka/model.h> #include <franka/rate_limiting.h> #include <franka/robot.h> int main(int argc, char** argv) { // Check whether the required arguments were passed. if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <robot-hostname>" << std::endl; return -1; } try { franka::Robot robot(argv[1]); robot.setJointImpedance({{3000, 3000, 3000, 2500, 2500, 2000, 2000}}); //values taken from https://github.com/frankaemika/libfranka/blob/master/examples/examples_common.cpp#L18 robot.setCartesianImpedance({{3000, 3000, 3000, 300, 300, 300}}); //values taken from https://github.com/frankaemika/libfranka/blob/master/examples/examples_common.cpp#L19 //TODO: be careful with this mode! robot.setCollisionBehavior( {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}}, {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}}, {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}}, {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}}, {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}}, {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}}, {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}}, {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}}); franka::Model model = robot.loadModel(); // Define callback for the joint torque control loop. std::function<franka::Torques(const franka::RobotState&, franka::Duration)> impedance_control_callback = [&model]( const franka::RobotState& state, franka::Duration /*period*/) -> franka::Torques { const std::array<double, 7> coriolis = model.coriolis(state); // Compute torque command std::array<double, 7> tau_d_calculated; for (size_t i = 0; i < 7; i++) { tau_d_calculated[i] = 0.0; //coriolis[i]; } // The following line is only necessary for printing the rate limited torque. As we activated // rate limiting for the control loop (activated by default), the torque would anyway be // adjusted! std::array<double, 7> tau_d_rate_limited = franka::limitRate(franka::kMaxTorqueRate, tau_d_calculated, state.tau_J_d); // Send torque command. return tau_d_rate_limited; }; // Start real-time control loop. robot.control(impedance_control_callback); } catch (const franka::Exception& ex) { std::cerr << ex.what() << std::endl; } return 0; }
38.916667
180
0.652034
[ "model" ]
34ce1b371f1492d80dd787e27de453a38cc8b591
13,329
hpp
C++
libtifwang/TiffFile.hpp
Imagine-Programming/tiffconvert
1eba05f3f876ac669d28ab9309326376bef61ef1
[ "MIT" ]
null
null
null
libtifwang/TiffFile.hpp
Imagine-Programming/tiffconvert
1eba05f3f876ac669d28ab9309326376bef61ef1
[ "MIT" ]
3
2021-02-15T08:10:59.000Z
2021-03-13T10:52:47.000Z
libtifwang/TiffFile.hpp
Imagine-Programming/tiffconvert
1eba05f3f876ac669d28ab9309326376bef61ef1
[ "MIT" ]
null
null
null
#pragma once #include "pch.h" #ifndef tiff_file_h #define tiff_file_h namespace TiffWang { namespace Tiff { constexpr const char* IntelEndian = "II"; // Start bytes of Tiff files, little endian. constexpr const char* MotorolaEndian = "MM"; // Start bytes of Tiff files, big endian. constexpr uint16_t Magic = 42; // Magic number in Tiff header. /// <summary> /// A struct allowing for defining how to read integers (and floating point numbers) dynamically. This is /// used to read both little endian and big endian streams. /// </summary> struct TiffNumericReader { std::function<int16_t()> Int16; std::function<uint16_t()> Uint16; std::function<int32_t()> Int32; std::function<uint32_t()> Uint32; std::function<int64_t()> Int64; std::function<uint64_t()> Uint64; std::function<float()> Float; std::function<double()> Double; std::function<int16_t()> Int16Le; std::function<uint16_t()> Uint16Le; std::function<int32_t()> Int32Le; std::function<uint32_t()> Uint32Le; std::function<int64_t()> Int64Le; std::function<uint64_t()> Uint64Le; std::function<float()> FloatLe; std::function<double()> DoubleLe; }; #pragma pack( push, 1 ) /// <summary> /// The Tiff file header /// </summary> struct TiffHeader { char ByteOrder[2]; // Should be either II or MM. uint16_t Magic; // 42. uint32_t OffsetFirstIfd; // Offset from beginning of stream to first IFD. }; /// <summary> /// A single tag in an Image File Directory /// </summary> struct TiffIfdEntry { TiffTagId TagId; // The identification of this tag. TiffTagType TagType; // The type of this tag. uint32_t ValueCount; // The number of values referenced by this tag (in bytes, that is sizeof(TagType) * ValueCount). uint32_t ValueOffset; // The offset (from the beginning of the stream) to the first value. bool IsWangTag; // True when this tag refers to an eiStream/Wang tag. }; #pragma pack( pop ) /// <summary> /// The dimensions and resolution of an IFD (Tiff page). /// </summary> struct TiffDimensions { double ResolutionX = 0; // Horizontal resolution (i.e. 300 dpi). double ResolutionY = 0; // Vertical resolution (i.e. 300 dpi). uint32_t Height = 0; // The height, in pixels. uint32_t Width = 0; // The width, in pixels. /// <summary> /// The resolution unit describes the unit of the <see cref="ResolutionX"/> and <see cref="ResolutionY"/> members. /// </summary> TiffResolutionUnit ResolutionUnit = TiffResolutionUnit::NoAbsoluteMeasurement; }; /// <summary> /// The TiffFile class is capable of handling a Tiff file on binary level, so not on graphical level. It does not decode /// the image, it merely parses the structure of the file and enumerates all the tags. With this information, a developer /// can process the tags however they seem fit. /// </summary> class __EXPORTED_API TiffFile { /// <summary> /// <see cref="WangAnnotationReader"/> is allowed to access all private members of <see cref="TiffFile"/>. /// </summary> friend class WangAnnotationReader; using TiffIfdList = std::vector<std::vector<TiffIfdEntry>>; // A list of image file directories, which are lists of tags, i.e. [1] is the IFD of page 2. using TiffDimensionList = std::vector<TiffDimensions>; // A list of IFD dimensions, i.e. [1] is the dimensions of page 2. using TiffStringList = std::vector<std::string>; // A simple alias for a vector of strings. private: #pragma warning ( push ) #pragma warning ( disable: 4251 ) /* "needs to have dll-interface to be used by clients of class" - members are not public and have no friends outside the DLL */ mutable std::ifstream m_Stream; size_t m_StreamSize; TiffNumericReader m_IntegerReader; TiffHeader m_Header; TiffIfdList m_PageIfdCollection; TiffDimensionList m_Dimensions; TiffStringList m_Software; TiffStringList m_DateTime; TiffStringList m_Artist; #pragma warning ( pop ) public: /// <summary> /// Construct a new TiffFile instance from ascii filepath. /// </summary> /// <param name="filepath">The Tiff-file to parse.</param> TiffFile(const std::string& filepath); /// <summary> /// Construct a new TiffFile instance from unicode filepath. /// </summary> /// <param name="filepath">The Tiff-file to parse.</param> TiffFile(const std::wstring& filepath); private: /// <summary> /// Initialize the opened file stream, read and process the file header. /// </summary> void Init(); public: TiffFile(const TiffFile&) = delete; TiffFile& operator=(const TiffFile&) = delete; TiffFile(TiffFile&&) = delete; TiffFile& operator=(TiffFile&&) = delete; /// <summary> /// Process all the Image File Directories. /// </summary> void ReadIfdCollection(); /// <summary> /// Get the total number of Image File Directories. /// </summary> /// <returns>The number of directories (or pages).</returns> size_t GetPageCount() const noexcept; /// <summary> /// Get the total number of tags in a specific IFD (page). /// </summary> /// <param name="pageIndex">The IFD (page) index.</param> /// <returns>The number of tags in this IFD.</returns> /// <exception cref="std::out_of_range">When indices are out of range.</exception> size_t GetPageIfdCount(size_t pageIndex) const; /// <summary> /// Get the IFD tag at a certain page index and IFD tag index. /// </summary> /// <param name="pageIndex">The IFD (page) index.</param> /// <param name="ifdIndex">The tag index.</param> /// <returns>A const reference to the tag entry.</returns> /// <exception cref="std::out_of_range">When indices are out of range.</exception> const TiffIfdEntry& GetPageIfd(size_t pageIndex, size_t ifdIndex) const; /// <summary> /// Get the dimensions for a specific IFD (page). /// </summary> /// <param name="pageIndex">The IFD (page) index.</param> /// <returns>A const reference to the dimensions and resolution instance.</returns> /// <exception cref="std::out_of_range">When indices are out of range.</exception> const TiffDimensions& GetDimensions(size_t pageIndex) const; /// <summary> /// Get the name of the software that wrote a specific IFD (page). /// </summary> /// <param name="pageIndex">The IFD (page) index.</param> /// <returns>The software name or an empty string if unavailable.</returns> /// <exception cref="std::out_of_range">When indices are out of range.</exception> const std::string& GetSoftware(size_t pageIndex) const; /// <summary> /// Get the formatted creation date and time or a specific IFD (page). /// </summary> /// <param name="pageIndex">The IFD (page) index.</param> /// <returns>The formatted timestamp or an empty string if unavailable.</returns> /// <exception cref="std::out_of_range">When indices are out of range.</exception> const std::string& GetDateTime(size_t pageIndex) const; /// <summary> /// Get the artist name or a specific IFD (page). /// </summary> /// <param name="pageIndex">The IFD (page) index.</param> /// <returns>The artist name or an empty string if unavailable.</returns> /// <exception cref="std::out_of_range">When indices are out of range.</exception> const std::string& GetArtist(size_t pageIndex) const; private: /// <summary> /// Correct the order of IFD collections based on page index tags, if any. If one of /// the IFDs (pages) does not contain a page index tag, the order of reading is maintained. /// </summary> void CorrectIfdOrder(); /// <summary> /// Determines how many bytes there are left in the stream to read. /// </summary> /// <returns>Number of bytes left</returns> size_t SizeLeft() const; /// <summary> /// Throw an exception if there is not enough data left to read. /// </summary> /// <param name="required">The number of bytes required in the stream.</param> /// <exception cref="std::runtime_error">When required &lt; SizeLeft().</exception> void AssertSizeLeft(size_t required) const; /// <summary> /// Throw an exception if a certain offset in a stream does not exist. /// </summary> /// <param name="offset">The offset to test</param> /// <exception cref="std::runtime_error">When the offset is out of bounds.</exception> void AssertOffset(size_t offset) const; /// <summary> /// Throw an exception if the IFD (page) index is out of range. /// </summary> /// <param name="pageIndex">The index to check for.</param> /// <exception cref="std::out_of_range">When index is out of bounds.</exception> void AssertPageIndex(size_t pageIndex) const; /// <summary> /// Throw an exception if either the IFD (page) index or if the IFD Tag index is out of range. /// </summary> /// <param name="pageIndex">The page index to check for.</param> /// <param name="ifdIndex">The tag index to check for.</param> /// <exception cref="std::out_of_range">When either index is out of bounds.</exception> void AssertPageIfdIndex(size_t pageIndex, size_t ifdIndex) const; /// <summary> /// Read a struct or class value from the stream. /// </summary> /// <param name="value">A reference to the value to read to.</param> /// <typeparam name="The type of struct or class to read."></typeparam> /// <exception cref="::std::runtime_error">When insufficient data is available, an exception is thrown.</exception> template < typename TValue, std::enable_if_t<std::is_class_v<TValue>, int> = 0 > void Read(TValue& value); /// <summary> /// Read an integral or floating point value from the stream. /// </summary> /// <typeparam name="TValue">The type of integral or floating point value to read.</typeparam> /// <returns>The read value.</returns> /// <exception cref="::std::runtime_error">When insufficient data is available, an exception is thrown.</exception> template <typename TValue, std::enable_if_t< std::conjunction< std::disjunction<std::is_integral<TValue>, std::is_floating_point<TValue>>, std::negation<std::is_pointer<TValue>>, std::negation<std::is_reference<TValue>> >::value, int > = 0 > TValue Read(); /// <summary> /// Read all the associated tag data from a BYTE tag to a buffer. /// </summary> /// <param name="entry">The TiffIfdEntry to read, which should have BYTE as TagType.</param> /// <param name="buffer">The output buffer, which should be large enough to hold all of <see cref="TiffIfdEntry::ValueCount"/>.</param> /// <param name="size">The size of the output buffer.</param> /// <exception cref="::std::runtime_error">When insufficient data is available, the output buffer is too small or the type != BYTE an exception is thrown.</exception> void Read(const TiffIfdEntry& entry, uint8_t* buffer, size_t size) const; /// <summary> /// Read all the associated tag data from a BYTE tag to a buffer /// </summary> /// <param name="entry">The TiffIfdEntry to read, which should have BYTE as TagType.</param> /// <param name="result">The output buffer</param> /// <exception cref="::std::runtime_error">When insufficient data is available or the type != BYTE an exception is thrown.</exception> void Read(const TiffIfdEntry& entry, std::vector<uint8_t>& result) const; /// <summary> /// Read one or more TiffTagType::SHORT values /// </summary> /// <param name="entry">The TiffIfdEntry to read.</param> /// <returns>A vector of read unsigned shorts.</returns> /// <exception cref="::std::runtime_error">When insufficient data is available, an exception is thrown.</exception> std::vector<uint16_t> ReadUnsignedShortArray(const TiffIfdEntry& entry); /// <summary> /// Read a rational number (two TiffTagType::LONG values) and produce a rational number, /// by dividing the numerator by the denominator. /// </summary> /// <param name="entry">The TiffIfdEntry to read.</param> /// <returns>A double floating point value represented by the 2 read LONG values.</returns> /// <exception cref="::std::runtime_error">When insufficient data is available, an exception is thrown.</exception> double ReadRational(const TiffIfdEntry& entry); /// <summary> /// Read a NUL-terminated Ascii-string, ignoring the NUL character. /// </summary> /// <param name="entry">The TiffIfdEntry to read.</param> /// <returns>The resulting string, or an empty string when its length was 0.</returns> /// <exception cref="::std::runtime_error">When insufficient data is available, an exception is thrown.</exception> std::string ReadAsciiString(const TiffIfdEntry& entry); }; } } #endif
42.858521
171
0.652037
[ "vector" ]
34d0987fc3ff6edab38c6dc08b3de48cf2f23f07
150,962
cpp
C++
source/grains.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/grains.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/grains.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ /*grain main routine to converge grains thermal solution */ #include "cddefines.h" #include "atmdat.h" #include "atmdat_adfa.h" #include "rfield.h" #include "hmi.h" #include "trace.h" #include "conv.h" #include "ionbal.h" #include "thermal.h" #include "phycon.h" #include "doppvel.h" #include "heavy.h" #include "ipoint.h" #include "elementnames.h" #include "grainvar.h" #include "grains.h" #include "iso.h" #include "mole.h" #include "dense.h" #include "vectorize.h" #include "parser.h" /* the next three defines are for debugging purposes only, uncomment to activate */ /* #define WD_TEST2 1 */ /* #define IGNORE_GRAIN_ION_COLLISIONS 1 */ /* #define IGNORE_THERMIONIC 1 */ /* no parentheses around PTR needed since it needs to be an lvalue */ #define FREE_CHECK(PTR) { ASSERT( PTR != NULL ); free( PTR ); PTR = NULL; } #define FREE_SAFE(PTR) { if( PTR != NULL ) free( PTR ); PTR = NULL; } static const long MAGIC_AUGER_DATA = 20060126L; static const bool INCL_TUNNEL = true; static const bool NO_TUNNEL = false; /*================================================================================*/ /* these are used for setting up grain emissivities in InitEmissivities() */ /* NTOP is number of bins for temps between GRAIN_TMID and GRAIN_TMAX */ static const long NTOP = NDEMS/5; /*================================================================================*/ /* these are used when iterating the grain charge in GrainCharge() */ static const double TOLER = CONSERV_TOL/10.; static const long BRACKET_MAX = 50L; /* >>chng 06 feb 07, increased CT_LOOP_MAX (10 -> 25), T_LOOP_MAX (30 -> 50), pah.in, PvH */ /* maximum number of tries to converge charge/temperature in GrainChargeTemp() */ static const long CT_LOOP_MAX = 25L; /* maximum number of tries to converge grain temperature in GrainChargeTemp() */ static const long T_LOOP_MAX = 50L; /* these will become the new tolerance levels used throughout the code */ static double HEAT_TOLER = DBL_MAX; static double HEAT_TOLER_BIN = DBL_MAX; static double CHRG_TOLER = DBL_MAX; /* static double CHRG_TOLER_BIN = DBL_MAX; */ /*================================================================================*/ /* miscellaneous grain physics */ /* a_0 thru a_2 constants for calculating IP_V and EA, in cm */ static const double AC0 = 3.e-9; static const double AC1G = 4.e-8; static const double AC2G = 7.e-8; /* constants needed to calculate energy distribution of secondary electrons */ static const double ETILDE = 2.*SQRT2/EVRYD; /* sqrt(8) eV */ static const double INV_ETILDE = 1./ETILDE; /* constant for thermionic emissions, 7.501e20 e/cm^2/s/K^2 */ static const double THERMCONST = PI4*ELECTRON_MASS*POW2(BOLTZMANN)/POW3(HPLANCK); /* sticking probabilities */ static const double STICK_ELEC = 0.5; static const double STICK_ION = 1.0; /** evaluate e^2/a, the potential of one electron */ inline double one_elec(long nd) { return ELEM_CHARGE/EVRYD/gv.bin[nd].Capacity; } /** convert grain potential in Ryd to charge in electrons */ inline double pot2chrg(double x, long nd) { return x/one_elec(nd) - 1.; } /** convert grain charge in electrons into potential in Ryd */ inline double chrg2pot(double x, long nd) { return (x+1.)*one_elec(nd); } /** mean pathlength travelled by electrons inside the grain, in cm (Eq. 11 of WDB06) */ inline double elec_esc_length(double e, // energy of electron in Ryd long nd) { // calculate escape length in cm if( e <= gv.bin[nd].le_thres ) return 1.e-7; else return 3.e-6*gv.bin[nd].eec*powpq(e*EVRYD*1.e-3,3,2); } /* read data for electron energy spectrum of Auger electrons */ STATIC void ReadAugerData(); /* initialize the Auger data for grain bin nd between index ipBegin <= i < ipEnd */ STATIC void InitBinAugerData(size_t,long,long); /* initialize grain emissivities */ STATIC void InitEmissivities(); /* PlanckIntegral compute total radiative cooling due to large grains */ STATIC double PlanckIntegral(double,size_t,long); /* invalidate charge dependent data from previous iteration */ STATIC void NewChargeData(long); /* GrnStdDpth returns the grain abundance as a function of depth into cloud */ STATIC double GrnStdDpth(long); /* iterate grain charge and temperature */ STATIC void GrainChargeTemp(); /* GrainCharge compute grains charge */ STATIC void GrainCharge(size_t,/*@out@*/double*); /* grain electron recombination rates for single charge state */ STATIC double GrainElecRecomb1(size_t,long,/*@out@*/double*,/*@out@*/double*); /* grain electron emission rates for single charge state */ STATIC double GrainElecEmis1(size_t,long,/*@out@*/double*,/*@out@*/double*,/*@out@*/double*,/*@out@*/double*); /* correction factors for grain charge screening (including image potential * to correct for polarization of the grain as charged particle approaches). */ STATIC void GrainScreen(long,size_t,long,double*,double*); /* helper function for GrainScreen */ STATIC double ThetaNu(double); /* update items that depend on grain potential */ STATIC void UpdatePot(size_t,long,long,/*@out@*/double[],/*@out@*/double[]); /* calculate charge state populations */ STATIC void GetFracPop(size_t,long,/*@in@*/double[],/*@in@*/double[],/*@out@*/long*); /* this routine updates all quantities that depend only on grain charge and radius */ STATIC void UpdatePot1(size_t,long,long,long); /* this routine updates all quantities that depend on grain charge, radius and temperature */ STATIC void UpdatePot2(size_t,long); /* Helper function to calculate primary and secondary yields and the average electron energy at infinity */ STATIC void Yfunc(long,long,const realnum[],const realnum[],const realnum[],double,const double[],const double[], /*@out@*/realnum[],/*@out@*/realnum[],/*@out@*/realnum[],/*@out@*/realnum[],long,long); STATIC void Yfunc(long,long,const realnum[],const realnum[],double,double,double, /*@out@*/realnum[],/*@out@*/realnum[],/*@out@*/realnum[],/*@out@*/realnum[],long,long); /* This calculates the y0 function for band electrons (Sect. 4.1.3/4.1.4 of WDB06) */ STATIC void y0b(size_t,long,/*@out@*/realnum[],long,long); /* This calculates the y0 function for band electrons (Eq. 16 of WD01) */ STATIC void y0b01(size_t,long,/*@out@*/realnum[],long,long); /* This calculates the y0 function for primary/secondary and Auger electrons (Eq. 9 of WDB06) */ STATIC double y0psa(size_t,long,long,double); /* This calculates the y1 function for primary/secondary and Auger electrons (Eq. 6 of WDB06) */ STATIC double y1psa(size_t,long,double); /* This calculates the y2 function for primary and Auger electrons (Eq. 8 of WDB06) */ inline void y2pa(double,const double[],long,/*@out@*/realnum[],/*@out@*/realnum[],long,long); /* This calculates the y2 function for secondary electrons (Eq. 20-21 of WDB06) */ inline void y2s(double,const double[],long,const realnum[],/*@out@*/realnum[],/*@out@*/realnum[],long,long); /* determine charge Z0 ion recombines to upon impact on grain */ STATIC void UpdateRecomZ0(size_t,long); /* helper routine for UpdatePot */ STATIC void GetPotValues(size_t,long,/*@out@*/double*,/*@out@*/double*,/*@out@*/double*, /*@out@*/double*,/*@out@*/double*,/*@out@*/double*,bool); /* given grain nd in charge state nz, and incoming ion (nelem,ion), * detemine outgoing ion (nelem,Z0) and chemical energy ChEn released * ChemEn is net contribution of ion recombination to grain heating */ STATIC void GrainIonColl(size_t,long,long,long,const double[],const double[],/*@out@*/long*, /*@out@*/realnum*,/*@out@*/realnum*); /* initialize ion recombination rates on grain species nd */ STATIC void GrainChrgTransferRates(long); /* this routine updates all grain quantities that depend on radius, except gv.dstab and gv.dstsc */ STATIC void GrainUpdateRadius1(); /* this routine adds all the grain opacities in gv.dstab and gv.dstsc */ STATIC void GrainUpdateRadius2(); /* GrainTemperature computes grains temperature, and gas cooling */ STATIC void GrainTemperature(size_t,/*@out@*/realnum*,/*@out@*/double*,/*@out@*/double*, /*@out@*/double*); /* helper routine for initializing quantities related to the photo-electric effect */ STATIC void PE_init(size_t,long,long,/*@out@*/double*,/*@out@*/double*,/*@out@*/double*, /*@out@*/double*,/*@out@*/double*,/*@out@*/double*,/*@out@*/double*); /* GrainCollHeating computes grains collisional heating cooling */ STATIC void GrainCollHeating(size_t,/*@out@*/realnum*,/*@out@*/realnum*); /* GrnVryDpth user supplied function for the grain abundance as a function of depth into cloud */ STATIC double GrnVryDpth(size_t); /* this routine is called by IterStart(), so anything that needs to be reset before each * iteration starts should be put here; typically variables that are integrated over radius */ void GrainStartIter() { DEBUG_ENTRY( "GrainStartIter()" ); if( gv.lgDustOn() && gv.lgGrainPhysicsOn ) { gv.lgNegGrnDrg = false; gv.TotalDustHeat = 0.; gv.GrnElecDonateMax = 0.; gv.GrnElecHoldMax = 0.; gv.dphmax = 0.f; gv.dclmax = 0.f; for( size_t nd=0; nd < gv.bin.size(); nd++ ) { gv.bin[nd].ZloSave = gv.bin[nd].chrg(0).DustZ; gv.bin[nd].qtmin = ( gv.bin[nd].qtmin_zone1 > 0. ) ? gv.bin[nd].qtmin_zone1 : DBL_MAX; gv.bin[nd].avdust = 0.; gv.bin[nd].avdpot = 0.; gv.bin[nd].avdft = 0.; gv.bin[nd].avDGRatio = 0.; gv.bin[nd].TeGrainMax = -1.f; gv.bin[nd].lgEverQHeat = false; gv.bin[nd].QHeatFailures = 0L; gv.bin[nd].lgQHTooWide = false; gv.bin[nd].lgPAHsInIonizedRegion = false; gv.bin[nd].nChrgOrg = gv.bin[nd].nChrg; } } return; } /* this routine is called by IterRestart(), so anything that needs to be * reset or saved after an iteration is finished should be put here */ void GrainRestartIter() { DEBUG_ENTRY( "GrainRestartIter()" ); if( gv.lgDustOn() && gv.lgGrainPhysicsOn ) { for( size_t nd=0; nd < gv.bin.size(); nd++ ) { gv.bin[nd].lgIterStart = true; gv.bin[nd].nChrg = gv.bin[nd].nChrgOrg; } } return; } /* this routine is called by ParseSet() */ void SetNChrgStates(long nChrg) { DEBUG_ENTRY( "SetNChrgStates()" ); ASSERT( nChrg >= 2 && nChrg <= NCHU ); gv.nChrgRequested = nChrg; return; } /*GrainsInit, called one time by opacitycreateall at initialization of calculation, * called after commands have been parsed, * not after every iteration or every model */ void GrainsInit() { long int i, nelem; unsigned int ns; DEBUG_ENTRY( "GrainsInit()" ); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " GrainsInit called.\n" ); } gv.dstab.resize( rfield.nflux_with_check ); gv.dstsc.resize( rfield.nflux_with_check ); gv.GrainEmission.resize( rfield.nflux_with_check ); gv.GraphiteEmission.resize( rfield.nflux_with_check ); gv.SilicateEmission.resize( rfield.nflux_with_check ); /* >>chng 02 jan 15, initialize to zero in case grains are not used, needed in IonIron(), PvH */ for( nelem=0; nelem < LIMELM; nelem++ ) { gv.elmSumAbund[nelem] = 0.f; } for( i=0; i < rfield.nflux_with_check; i++ ) { gv.dstab[i] = 0.; gv.dstsc[i] = 0.; /* >>chng 01 sep 12, moved next three initializations from GrainZero(), PvH */ gv.GrainEmission[i] = 0.; gv.SilicateEmission[i] = 0.; gv.GraphiteEmission[i] = 0.; } if( !gv.lgDustOn() ) { /* grains are not on, set all heating/cooling agents to zero */ gv.GrainHeatInc = 0.; gv.GrainHeatDif = 0.; gv.GrainHeatLya = 0.; gv.GrainHeatCollSum = 0.; gv.GrainHeatSum = 0.; gv.GasCoolColl = 0.; thermal.setHeating(0,13,0.); thermal.setHeating(0,14,0.); thermal.setHeating(0,25,0.); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " GrainsInit exits.\n" ); } return; } #ifdef WD_TEST2 gv.lgWD01 = true; #endif HEAT_TOLER = conv.HeatCoolRelErrorAllowed / 3.; HEAT_TOLER_BIN = HEAT_TOLER / sqrt((double)gv.bin.size()); CHRG_TOLER = conv.EdenErrorAllowed / 3.; /* CHRG_TOLER_BIN = CHRG_TOLER / sqrt(gv.bin.size()); */ ReadAugerData(); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { double help,atoms,p_rad,ThresInf,ThresInfVal,Emin,d[5]; long low1,low2,low3,lowm; /* sanity checks */ ASSERT( gv.bin[nd].nChrg >= 2 && gv.bin[nd].nChrg <= NCHU ); if( gv.bin[nd].DustWorkFcn < rfield.emm() || gv.bin[nd].DustWorkFcn > rfield.egamry() ) { fprintf( ioQQQ, " Grain work function for %s has insane value: %.4e\n", gv.bin[nd].chDstLab,gv.bin[nd].DustWorkFcn ); cdEXIT(EXIT_FAILURE); } /* this is QHEAT ALL command */ if( gv.lgQHeatAll ) { gv.bin[nd].lgQHeat = true; } /* this is NO GRAIN QHEAT command, always takes precedence */ if( !gv.lgQHeatOn ) { gv.bin[nd].lgQHeat = false; } /* >>chng 04 jun 01, disable quantum heating when constant grain temperature is used, PvH */ if( thermal.ConstGrainTemp > 0. ) { gv.bin[nd].lgQHeat = false; } if (ENABLE_QUANTUM_HEATING) { gv.bin[nd].lgQHTooWide = false; gv.bin[nd].qtmin = DBL_MAX; } gv.bin[nd].lgIterStart = true; if( gv.bin[nd].nDustFunc>DF_STANDARD || gv.bin[nd].matType == MAT_PAH || gv.bin[nd].matType == MAT_PAH2 ) gv.lgAnyDustVary = true; /* grain abundance may depend on radius, * invalidate for now; GrainUpdateRadius1() will set correct value */ gv.bin[nd].dstAbund = -FLT_MAX; gv.bin[nd].GrnDpth = 1.f; gv.bin[nd].qtmin_zone1 = -1.; /* this is threshold in Ryd above which to use X-ray prescription for electron escape length */ gv.bin[nd].le_thres = gv.lgWD01 ? FLT_MAX : (realnum)(powpq(pow((double)gv.bin[nd].dustp[0],0.85)/30.,2,3)*1.e3/EVRYD); /* >>chng 00 jun 19, this value is absolute lower limit for the grain * potential, electrons cannot be bound for lower values..., PvH */ zmin_type zcase = gv.which_zmin[gv.bin[nd].matType]; switch( zcase ) { case ZMIN_CAR: // this is Eq. 23a + 24 of WD01 help = gv.bin[nd].AvRadius*1.e7; help = ceil(-(1.2*POW2(help)+3.9*help+0.2)/1.44); break; case ZMIN_SIL: // this is Eq. 23b + 24 of WD01 help = gv.bin[nd].AvRadius*1.e7; help = ceil(-(0.7*POW2(help)+2.5*help+0.8)/1.44); break; default: fprintf( ioQQQ, " GrainsInit detected unknown Zmin type: %d\n" , zcase ); cdEXIT(EXIT_FAILURE); } /* this is to assure that gv.bin[nd].LowestZg > LONG_MIN */ ASSERT( help > (double)(LONG_MIN+1) ); low1 = nint(help); /* >>chng 01 apr 20, iterate to get LowestZg such that the exponent in the thermionic * rate never becomes positive; the value can be derived by equating ThresInf >= 0; * the new expression for Emin (see GetPotValues) cannot be inverted analytically, * hence it is necessary to iterate for LowestZg. this also automatically assures that * the expressions for ThresInf and LowestZg are consistent with each other, PvH */ low2 = low1; GetPotValues(nd,low2,&ThresInf,&d[0],&d[1],&d[2],&d[3],&d[4],INCL_TUNNEL); if( ThresInf < 0. ) { low3 = 0; /* do a bisection search for the lowest charge such that * ThresInf >= 0, the end result will eventually be in low3 */ while( low3-low2 > 1 ) { lowm = (low2+low3)/2; GetPotValues(nd,lowm,&ThresInf,&d[0],&d[1],&d[2],&d[3],&d[4],INCL_TUNNEL); if( ThresInf < 0. ) low2 = lowm; else low3 = lowm; } low2 = low3; } /* the first term implements the minimum charge due to autoionization * the second term assures that the exponent in the thermionic rate never * becomes positive; the expression was derived by equating ThresInf >= 0 */ gv.bin[nd].LowestZg = MAX2(low1,low2); gv.bin[nd].ZloSave = LONG_MIN; ASSERT( gv.bin[nd].sd.size() == 0 ); ns = 0; gv.bin[nd].sd.emplace_back( ShellData() ); /* this is data for valence band */ gv.bin[nd].sd[ns].nelem = -1; gv.bin[nd].sd[ns].ns = -1; gv.bin[nd].sd[ns].ionPot = gv.bin[nd].DustWorkFcn; /* now add data for inner shell photoionization */ for( nelem=ipLITHIUM; nelem < LIMELM && !gv.lgWD01; nelem++ ) { if( gv.bin[nd].elmAbund[nelem] > 0. ) { if( gv.AugerData[nelem].nSubShell == 0 ) { fprintf( ioQQQ, " Grain Auger data are missing for element %s\n", elementnames.chElementName[nelem] ); fprintf( ioQQQ, " Please include the NO GRAIN X-RAY TREATMENT command " "to disable the Auger treatment in grains.\n" ); cdEXIT(EXIT_FAILURE); } for( unsigned int j=0; j < gv.AugerData[nelem].nSubShell; j++ ) { ++ns; gv.bin[nd].sd.emplace_back( ShellData() ); gv.bin[nd].sd[ns].nelem = nelem; gv.bin[nd].sd[ns].ns = j; gv.bin[nd].sd[ns].ionPot = gv.AugerData[nelem].IonThres[j]; } } } GetPotValues(nd,gv.bin[nd].LowestZg,&d[0],&ThresInfVal,&d[1],&d[2],&d[3],&Emin,INCL_TUNNEL); for( ns=0; ns < gv.bin[nd].sd.size(); ns++ ) { long ipLo; double Ethres = ( ns == 0 ) ? ThresInfVal : gv.bin[nd].sd[ns].ionPot; ShellData *sptr = &gv.bin[nd].sd[ns]; sptr->ipLo = rfield.ithreshC( Ethres ); ipLo = sptr->ipLo; // allow room for adjustment of rfield.nPositive later on long len = rfield.nflux_with_check - ipLo; sptr->p.reserve( len ); sptr->p.alloc( ipLo, rfield.nPositive ); sptr->y01.reserve( len ); sptr->y01.alloc( ipLo, rfield.nPositive ); /* there are no Auger electrons from the band structure */ if( ns > 0 ) { sptr->nData = gv.AugerData[sptr->nelem].nData[sptr->ns]; sptr->AvNr.resize( sptr->nData ); sptr->Ener.resize( sptr->nData ); sptr->y01A.resize( sptr->nData ); for( long n=0; n < sptr->nData; n++ ) { sptr->AvNr[n] = gv.AugerData[sptr->nelem].AvNumber[sptr->ns][n]; sptr->Ener[n] = gv.AugerData[sptr->nelem].Energy[sptr->ns][n]; sptr->y01A[n].reserve( len ); sptr->y01A[n].alloc( ipLo, rfield.nPositive ); } } } gv.bin[nd].y0b06.resize( rfield.nflux_with_check ); InitBinAugerData( nd, 0, rfield.nPositive ); gv.bin[nd].nfill = rfield.nPositive; /* >>chng 00 jul 13, new sticking probability for electrons */ /* the second term is chance that electron passes through grain, * 1-p_rad is chance that electron is ejected before grain settles * see discussion in * >>refer grain physics Weingartner & Draine, 2001, ApJS, 134, 263 */ /** \todo xray - StickElec depends on Te ???? use elec_esc_length(1.5*kTe,nd) ???? */ gv.bin[nd].StickElecPos = STICK_ELEC*(1. - exp(-gv.bin[nd].AvRadius/elec_esc_length(0.,nd))); atoms = gv.bin[nd].AvVol*gv.bin[nd].dustp[0]/ATOMIC_MASS_UNIT/gv.bin[nd].atomWeight; p_rad = 1./(1.+exp(20.-atoms)); gv.bin[nd].StickElecNeg = gv.bin[nd].StickElecPos*p_rad; /* >>chng 02 feb 15, these quantities depend on radius and are normally set * in GrainUpdateRadius1(), however, it is necessary to initialize them here * as well so that they are valid the first time hmole is called. */ gv.bin[nd].GrnDpth = (realnum)GrnStdDpth(nd); gv.bin[nd].dstAbund = (realnum)(gv.bin[nd].dstfactor*gv.GrainMetal*gv.bin[nd].GrnDpth); ASSERT( gv.bin[nd].dstAbund > 0.f ); /* grain unit conversion, <unit>/H (default depl) -> <unit>/cm^3 (actual depl) */ gv.bin[nd].cnv_H_pCM3 = dense.gas_phase[ipHYDROGEN]*gv.bin[nd].dstAbund; gv.bin[nd].cnv_CM3_pH = 1./gv.bin[nd].cnv_H_pCM3; /* grain unit conversion, <unit>/cm^3 (actual depl) -> <unit>/grain */ gv.bin[nd].cnv_CM3_pGR = gv.bin[nd].cnv_H_pGR/gv.bin[nd].cnv_H_pCM3; gv.bin[nd].cnv_GR_pCM3 = 1./gv.bin[nd].cnv_CM3_pGR; } /* >>chng 02 dec 19, these quantities depend on radius and are normally set * in GrainUpdateRadius1(), however, it is necessary to initialize them here * as well so that they are valid for the initial printout in Cloudy, PvH */ /* calculate the summed grain abundances, these are valid at the inner radius; * these numbers depend on radius and are updated in GrainUpdateRadius1() */ for( nelem=0; nelem < LIMELM; nelem++ ) { gv.elmSumAbund[nelem] = 0.f; } for( size_t nd=0; nd < gv.bin.size(); nd++ ) { for( nelem=0; nelem < LIMELM; nelem++ ) { gv.elmSumAbund[nelem] += gv.bin[nd].elmAbund[nelem]*(realnum)gv.bin[nd].cnv_H_pCM3; } } gv.nzone = -1; gv.GrnRecomTe = -1.; /* >>chng 01 nov 21, total grain opacities depend on charge and therefore on radius, * invalidate for now; GrainUpdateRadius2() will set correct values */ for( i=0; i < rfield.nflux_with_check; i++ ) { /* these are total absorption and scattering cross sections, * the latter should contain the asymmetry factor (1-g) */ gv.dstab[i] = -DBL_MAX; gv.dstsc[i] = -DBL_MAX; } InitEmissivities(); InitEnthalpy(); if( trace.lgDustBug && trace.lgTrace ) { fprintf( ioQQQ, " There are %ld grain types turned on.\n", (unsigned long)gv.bin.size() ); fprintf( ioQQQ, " grain depletion factors, dstfactor*GrainMetal=" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, "%10.2e", gv.bin[nd].dstfactor*gv.GrainMetal ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " nChrg =" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %ld", gv.bin[nd].nChrg ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " lowest charge (e) =" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %ld", gv.bin[nd].LowestZg ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " nDustFunc flag for user requested custom depth dependence:" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, "%2i", gv.bin[nd].nDustFunc ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " Quantum heating flag:" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, "%2c", TorF(gv.bin[nd].lgQHeat) ); } fprintf( ioQQQ, "\n" ); /* >>chng 01 nov 21, removed total abs and sct cross sections, they are invalid */ fprintf( ioQQQ, " NU(Ryd), Abs cross sec per proton\n" ); fprintf( ioQQQ, " Ryd " ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %-12.12s", gv.bin[nd].chDstLab ); } fprintf( ioQQQ, "\n" ); for( i=0; i < rfield.nflux_with_check; i += 40 ) { fprintf( ioQQQ, "%10.2e", rfield.anu(i) ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %10.2e ", gv.bin[nd].dstab1[i] ); } fprintf( ioQQQ, "\n" ); } fprintf( ioQQQ, " NU(Ryd), Sct cross sec per proton\n" ); fprintf( ioQQQ, " Ryd " ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %-12.12s", gv.bin[nd].chDstLab ); } fprintf( ioQQQ, "\n" ); for( i=0; i < rfield.nflux_with_check; i += 40 ) { fprintf( ioQQQ, "%10.2e", rfield.anu(i) ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %10.2e ", gv.bin[nd].pure_sc1[i] ); } fprintf( ioQQQ, "\n" ); } fprintf( ioQQQ, " NU(Ryd), Q abs\n" ); fprintf( ioQQQ, " Ryd " ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %-12.12s", gv.bin[nd].chDstLab ); } fprintf( ioQQQ, "\n" ); for( i=0; i < rfield.nflux_with_check; i += 40 ) { fprintf( ioQQQ, "%10.2e", rfield.anu(i) ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %10.2e ", gv.bin[nd].dstab1[i]*4./gv.bin[nd].IntArea ); } fprintf( ioQQQ, "\n" ); } fprintf( ioQQQ, " NU(Ryd), Q sct\n" ); fprintf( ioQQQ, " Ryd " ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %-12.12s", gv.bin[nd].chDstLab ); } fprintf( ioQQQ, "\n" ); for( i=0; i < rfield.nflux_with_check; i += 40 ) { fprintf( ioQQQ, "%10.2e", rfield.anu(i) ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %10.2e ", gv.bin[nd].pure_sc1[i]*4./gv.bin[nd].IntArea ); } fprintf( ioQQQ, "\n" ); } fprintf( ioQQQ, " NU(Ryd), asymmetry factor\n" ); fprintf( ioQQQ, " Ryd " ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %-12.12s", gv.bin[nd].chDstLab ); } fprintf( ioQQQ, "\n" ); for( i=0; i < rfield.nflux_with_check; i += 40 ) { fprintf( ioQQQ, "%10.2e", rfield.anu(i) ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %10.2e ", gv.bin[nd].asym[i] ); } fprintf( ioQQQ, "\n" ); } fprintf( ioQQQ, " GrainsInit exits.\n" ); } return; } /* read data for electron energy spectrum of Auger electrons */ STATIC void ReadAugerData() { DEBUG_ENTRY( "ReadAugerData()" ); DataParser d("auger_spectrum.dat", ES_NONE); d.getline(); d.checkMagic(MAGIC_AUGER_DATA); while( true ) { d.getline(); long nelem; d.getToken(nelem); if( nelem < 0 ) break; ASSERT( nelem < LIMELM ); AEInfo *ptr = &gv.AugerData[nelem]; d.getline(); d.getToken(ptr->nSubShell); ASSERT( ptr->nSubShell > 0 ); ptr->nData.resize( ptr->nSubShell ); ptr->IonThres.resize( ptr->nSubShell ); ptr->Energy.resize( ptr->nSubShell ); ptr->AvNumber.resize( ptr->nSubShell ); for( unsigned int ns=0; ns < ptr->nSubShell; ns++ ) { unsigned int ss; d.getline(); d.getToken(ss); ASSERT( ns == ss ); d.getline(); d.getToken(ptr->IonThres[ns]); ptr->IonThres[ns] /= EVRYD; d.getline(); d.getToken(ptr->nData[ns]); ASSERT( ptr->nData[ns] > 0 ); ptr->Energy[ns].resize( ptr->nData[ns] ); ptr->AvNumber[ns].resize( ptr->nData[ns] ); for( unsigned int n=0; n < ptr->nData[ns]; n++ ) { d.getline(); d.getToken(ptr->Energy[ns][n]); d.getToken(ptr->AvNumber[ns][n]); ptr->Energy[ns][n] /= EVRYD; ASSERT( ptr->Energy[ns][n] < ptr->IonThres[ns] ); } } } } /** initialize the Auger data for grain bin nd between index ipBegin <= i < ipEnd */ STATIC void InitBinAugerData(size_t nd, long ipBegin, long ipEnd) { DEBUG_ENTRY( "InitBinAugerData()" ); long i, ipLo, nelem; unsigned int ns; flex_arr<realnum> temp( ipBegin, ipEnd ); temp.zero(); /* this converts gv.bin[nd].elmAbund[nelem] to particle density inside the grain */ double norm = gv.bin[nd].cnv_H_pGR/gv.bin[nd].AvVol; /* this loop calculates the probability that photoionization occurs in a given shell */ for( ns=0; ns < gv.bin[nd].sd.size(); ns++ ) { ipLo = max( gv.bin[nd].sd[ns].ipLo, ipBegin ); gv.bin[nd].sd[ns].p.realloc( ipEnd ); /** \todo xray - Compton recoil still needs to be added here */ for( i=ipLo; i < ipEnd; i++ ) { long nel,nsh; double phot_ev,cs; phot_ev = rfield.anu(i)*EVRYD; if( ns == 0 ) { /* this is the valence band, defined as the sum of any * subshell not treated explicitly as an inner shell below */ gv.bin[nd].sd[ns].p[i] = 0.; for( nelem=ipHYDROGEN; nelem < LIMELM && !gv.lgWD01; nelem++ ) { if( gv.bin[nd].elmAbund[nelem] == 0. ) continue; long nshmax = Heavy.nsShells[nelem][0]; for( nsh = gv.AugerData[nelem].nSubShell; nsh < nshmax; nsh++ ) { nel = nelem+1; cs = t_ADfA::Inst().phfit(nelem+1,nel,nsh+1,phot_ev); gv.bin[nd].sd[ns].p[i] += (realnum)(norm*gv.bin[nd].elmAbund[nelem]*cs*1e-18); } } temp[i] += gv.bin[nd].sd[ns].p[i]; } else { /* this is photoionization from inner shells */ nelem = gv.bin[nd].sd[ns].nelem; nel = nelem+1; nsh = gv.bin[nd].sd[ns].ns; cs = t_ADfA::Inst().phfit(nelem+1,nel,nsh+1,phot_ev); gv.bin[nd].sd[ns].p[i] = (realnum)(norm*gv.bin[nd].elmAbund[nelem]*cs*1e-18); temp[i] += gv.bin[nd].sd[ns].p[i]; } } } for( i=ipBegin; i < ipEnd && !gv.lgWD01; i++ ) { /* this is Eq. 10 of WDB06 */ if( rfield.anu(i) > 20./EVRYD ) gv.bin[nd].inv_att_len[i] = temp[i]; } for( ns=0; ns < gv.bin[nd].sd.size(); ns++ ) { ipLo = max( gv.bin[nd].sd[ns].ipLo, ipBegin ); /* renormalize so that sum of probabilities is 1 */ for( i=ipLo; i < ipEnd; i++ ) { if( temp[i] > 0. ) gv.bin[nd].sd[ns].p[i] /= temp[i]; else gv.bin[nd].sd[ns].p[i] = ( ns == 0 ) ? 1.f : 0.f; } } temp.clear(); for( ns=0; ns < gv.bin[nd].sd.size(); ns++ ) { long n; ShellData *sptr = &gv.bin[nd].sd[ns]; ipLo = max( sptr->ipLo, ipBegin ); /* initialize the yield for primary electrons */ sptr->y01.realloc( ipEnd ); for( i=ipLo; i < ipEnd; i++ ) { double elec_en,yzero,yone; elec_en = MAX2(rfield.anu(i) - sptr->ionPot,0.); yzero = y0psa( nd, ns, i, elec_en ); /* this is size-dependent geometrical yield enhancement * defined in Weingartner & Draine, 2001; modified in WDB06 */ yone = y1psa( nd, i, elec_en ); if( ns == 0 ) { gv.bin[nd].y0b06[i] = (realnum)yzero; sptr->y01[i] = (realnum)yone; } else { sptr->y01[i] = (realnum)(yzero*yone); } } /* there are no Auger electrons from the band structure */ if( ns > 0 ) { /* initialize the yield for Auger electrons */ for( n=0; n < sptr->nData; n++ ) { sptr->y01A[n].realloc( ipEnd ); for( i=ipLo; i < ipEnd; i++ ) { double yzero = sptr->AvNr[n] * y0psa( nd, ns, i, sptr->Ener[n] ); /* this is size-dependent geometrical yield enhancement * defined in Weingartner & Draine, 2001; modified in WDB06 */ double yone = y1psa( nd, i, sptr->Ener[n] ); sptr->y01A[n][i] = (realnum)(yzero*yone); } } } } } STATIC void InitEmissivities() { double fac, fac2, tdust; long int i; DEBUG_ENTRY( "InitEmissivities()" ); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " InitEmissivities starts\n" ); fprintf( ioQQQ, " ND Tdust Emis BB Check 4pi*a^2*<Q>\n" ); } ASSERT( NTOP >= 2 && NDEMS > 2*NTOP ); fac = exp(log(GRAIN_TMID/GRAIN_TMIN)/(double)(NDEMS-NTOP)); tdust = GRAIN_TMIN; for( i=0; i < NDEMS-NTOP; i++ ) { gv.dsttmp[i] = log(tdust); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { gv.bin[nd].dstems[i] = log(PlanckIntegral(tdust,nd,i)); } tdust *= fac; } /* temperatures above GRAIN_TMID are unrealistic -> make grid gradually coarser */ fac2 = exp(log(GRAIN_TMAX/GRAIN_TMID/powi(fac,NTOP-1))/(double)((NTOP-1)*NTOP/2)); for( i=NDEMS-NTOP; i < NDEMS; i++ ) { gv.dsttmp[i] = log(tdust); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { gv.bin[nd].dstems[i] = log(PlanckIntegral(tdust,nd,i)); } fac *= fac2; tdust *= fac; } #ifndef NDEBUG /* sanity checks */ double mul = 1.; ASSERT( fabs(gv.dsttmp[0] - log(GRAIN_TMIN)) < 10.*mul*DBL_EPSILON ); mul = sqrt((double)(NDEMS-NTOP)); ASSERT( fabs(gv.dsttmp[NDEMS-NTOP] - log(GRAIN_TMID)) < 10.*mul*DBL_EPSILON ); mul = (double)NTOP + sqrt((double)NDEMS); ASSERT( fabs(gv.dsttmp[NDEMS-1] - log(GRAIN_TMAX)) < 10.*mul*DBL_EPSILON ); #endif /* now find slopes form spline fit */ for( size_t nd=0; nd < gv.bin.size(); nd++ ) { /* set up coefficients for spline */ spline(gv.bin[nd].dstems,gv.dsttmp,NDEMS,2e31,2e31,gv.bin[nd].dstslp); spline(gv.dsttmp,gv.bin[nd].dstems,NDEMS,2e31,2e31,gv.bin[nd].dstslp2); } # if 0 /* test the dstems interpolation */ nd = nint(fudge(0)); ASSERT( nd >= 0 && nd < gv.bin.size() ); for( i=0; i < 2000; i++ ) { double x,y,z; z = exp10(-40. + (double)i/50.); splint(gv.bin[nd].dstems,gv.dsttmp,gv.bin[nd].dstslp,NDEMS,log(z),&y); if( exp(y) > GRAIN_TMIN && exp(y) < GRAIN_TMAX ) { x = PlanckIntegral(exp(y),nd,3); printf(" input %.6e temp %.6e output %.6e rel. diff. %.6e\n",z,exp(y),x,(x-z)/z); } } cdEXIT(EXIT_SUCCESS); # endif return; } /* PlanckIntegral compute total radiative cooling due to grains */ STATIC double PlanckIntegral(double tdust, size_t nd, long int ip) { DEBUG_ENTRY( "PlanckIntegral()" ); /****************************************************************** * * >>>chng 99 mar 12, this sub rewritten following Peter van Hoof * comments. Original coding was in single precision, and for * very low temperature the exponential was set to zero. As * a result Q was far too large for grain temperatures below 10K * ******************************************************************/ /* Boltzmann factors for Planck integration */ double TDustRyg = TE1RYD/tdust; double x = 0.999*log(DBL_MAX); long mini = 0, maxi = rfield.nflux_with_check; avx_ptr<double> arg(rfield.nflux_with_check), expval(rfield.nflux_with_check); for( long i=0; i < rfield.nflux_with_check; i++ ) { /* this is hnu/kT for grain at this temp and photon energy */ arg[i] = TDustRyg*rfield.anu(i); if( arg[i] < 0.9999e-5 ) ++mini; if( arg[i] > x+0.0001 ) { maxi = i; break; } } vexp( arg.ptr0(), expval.ptr0(), mini, maxi ); double integral1 = 0.; /* integral(Planck) */ double integral2 = 0.; /* integral(Planck*abs_cs) */ for( long i=0; i < maxi; i++ ) { double ExpM1; /* want the number exp(hnu/kT) - 1, two expansions */ if( arg[i] < 1.e-5 ) { /* for small arg expand exp(hnu/kT) - 1 to second order */ ExpM1 = arg[i]*(1. + arg[i]/2.); } else { /* for large arg, evaluate the full expansion */ ExpM1 = expval[i] - 1.; } double Planck1 = PI4*2.*HPLANCK/POW2(SPEEDLIGHT)*POW2(FR1RYD)*POW2(FR1RYD)* rfield.anu3(i)/ExpM1*rfield.widflx(i); double Planck2 = Planck1*gv.bin[nd].dstab1[i]; /* add integral over RJ tail, maybe useful for extreme low temps */ if( i == 0 ) { integral1 = Planck1/rfield.widflx(0)*rfield.anu(0)/3.; integral2 = Planck2/rfield.widflx(0)*rfield.anu(0)/5.; } /* if we are in the Wien tail - exit */ if( Planck1/integral1 < DBL_EPSILON && Planck2/integral2 < DBL_EPSILON ) break; integral1 += Planck1; integral2 += Planck2; } /* this is an option to print out every few steps, when 'trace grains' is set */ if( trace.lgDustBug && trace.lgTrace && ip%10 == 0 ) { fprintf( ioQQQ, " %4ld %11.4e %11.4e %11.4e %11.4e\n", (unsigned long)nd, tdust, integral2, integral1/4./5.67051e-5/powi(tdust,4), integral2*4./integral1 ); } ASSERT( integral2 > 0. ); return integral2; } /* invalidate charge dependent data from previous iteration */ STATIC void NewChargeData(long nd) { long nz; DEBUG_ENTRY( "NewChargeData()" ); for( nz=0; nz < NCHS; nz++ ) { gv.bin[nd].chrg(nz).RSum1 = -DBL_MAX; gv.bin[nd].chrg(nz).RSum2 = -DBL_MAX; gv.bin[nd].chrg(nz).ESum1a = -DBL_MAX; gv.bin[nd].chrg(nz).ESum1b = -DBL_MAX; gv.bin[nd].chrg(nz).ESum2 = -DBL_MAX; gv.bin[nd].chrg(nz).hots1 = -DBL_MAX; gv.bin[nd].chrg(nz).bolflux1 = -DBL_MAX; gv.bin[nd].chrg(nz).pe1 = -DBL_MAX; /** \todo 2 should any of the following 3 statements be removed? */ gv.bin[nd].chrg(nz).ThermRate = -DBL_MAX; gv.bin[nd].chrg(nz).GrainHeat = -DBL_MAX; gv.bin[nd].chrg(nz).HeatingRate2 = -DBL_MAX; } if( !fp_equal(phycon.te,gv.GrnRecomTe) ) { for( nz=0; nz < NCHS; nz++ ) { memset( gv.bin[nd].chrg(nz).eta, 0, (LIMELM+2)*sizeof(double) ); memset( gv.bin[nd].chrg(nz).xi, 0, (LIMELM+2)*sizeof(double) ); } } if( nzone != gv.nzone ) { for( nz=0; nz < NCHS; nz++ ) { gv.bin[nd].chrg(nz).hcon1 = -DBL_MAX; } } return; } /* GrnStdDpth sets the standard behavior of the grain abundance as a function * of depth into cloud - user-define code should go in GrnVryDpth */ STATIC double GrnStdDpth(long int nd) { double GrnStdDpth_v; DEBUG_ENTRY( "GrnStdDpth()" ); /* NB NB - this routine defines the standard depth dependence of the grain abundance, * to implement user-defined behavior of the abundance (invoked with the "function" * keyword on the command line), modify the routine GrnVryDpth at the end of this file, * DO NOT MODIFY THIS ROUTINE */ if( gv.bin[nd].nDustFunc == DF_STANDARD ) { if( gv.bin[nd].matType == MAT_PAH || gv.bin[nd].matType == MAT_PAH2 ) { /* default behavior for PAH's */ if( gv.chPAH_abundance == "H" ) { /* the scale factor is the hydrogen atomic fraction, small when gas is ionized * or molecular and unity when atomic. This function is observed for PAHs * across the Orion Bar, the PAHs are strong near the ionization front and * weak in the ionized and molecular gas */ /* >>chng 04 sep 28, propto atomic fraction */ GrnStdDpth_v = dense.xIonDense[ipHYDROGEN][0]/dense.gas_phase[ipHYDROGEN]; } else if( gv.chPAH_abundance == "H,H2" ) { /* the scale factor is the total of the hydrogen atomic and molecular fractions, * small when gas is ionized and unity when atomic or molecular. This function is * observed for PAHs across the Orion Bar, the PAHs are strong near the ionization * front and weak in the ionized and molecular gas */ /* >>chng 04 sep 28, propto atomic fraction */ GrnStdDpth_v = (dense.xIonDense[ipHYDROGEN][0]+2*hmi.H2_total)/dense.gas_phase[ipHYDROGEN]; } else if( gv.chPAH_abundance == "CON" ) { /* constant abundance - unphysical, used only for testing */ GrnStdDpth_v = 1.; } else { fprintf(ioQQQ,"Invalid argument to SET PAH: %s\n",gv.chPAH_abundance.c_str()); TotalInsanity(); } } else { /* default behavior for all other types of grains */ GrnStdDpth_v = 1.; } } else if( gv.bin[nd].nDustFunc == DF_USER_FUNCTION ) { GrnStdDpth_v = GrnVryDpth(nd); } else if( gv.bin[nd].nDustFunc == DF_SUBLIMATION ) { // abundance depends on temperature relative to sublimation // "grain function sublimation" command GrnStdDpth_v = sexp( pow3( gv.bin[nd].tedust / gv.bin[nd].Tsublimat ) ); } else { TotalInsanity(); } GrnStdDpth_v = max(1.e-10,GrnStdDpth_v); return GrnStdDpth_v; } /* this is the main routine that drives the grain physics */ void GrainDrive() { DEBUG_ENTRY( "GrainDrive()" ); /* gv.lgGrainPhysicsOn set false with no grain physics command */ if( gv.lgDustOn() && gv.lgGrainPhysicsOn ) { static double tesave = -1.; static long int nzonesave = -1; /* option to only reevaluate grain physics if something has changed. * gv.lgReevaluate is set false with keyword no reevaluate on grains command * option to force constant reevaluation of grain physics - * by default is true * usually reevaluate grains at all times, but NO REEVALUATE will * save some time but may affect stability */ if( gv.lgReevaluate || conv.lgSearch || nzonesave != nzone || /* need to reevaluate the grains when temp changes since */ ! fp_equal( phycon.te, tesave ) || /* >>chng 03 dec 30, check that electrons locked in grains are not important, * if they are, then reevaluate */ fabs(gv.TotalEden)/dense.eden > conv.EdenErrorAllowed/5. || /* >>chng 04 aug 06, always reevaluate when thermal effects of grains are important, * first is collisional energy exchange with gas, second is grain photoionization */ (fabs( gv.GasCoolColl ) + fabs( thermal.heating(0,13) ))/SDIV(thermal.ctot)>0.1 ) { nzonesave = nzone; tesave = phycon.te; if( trace.nTrConvg >= 5 ) { fprintf( ioQQQ, " grain5 calling GrainChargeTemp\n"); } /* find dust charge and temperature - this must be called at least once per zone * since grain abundances, set here, may change with depth */ GrainChargeTemp(); /* >>chng 04 jan 31, moved call to GrainDrift to ConvPresTempEdenIoniz(), PvH */ } } else if( gv.lgDustOn() && !gv.lgGrainPhysicsOn ) { /* very minimalistic treatment of grains; only extinction of continuum is considered * however, the absorbed energy is not reradiated, so this creates thermal imbalance! */ if( gv.nCalledGrainDrive == 0 ) { long nelem, ion, ion_to; /* when not doing grain physics still want some exported quantities * to be reasonable, grain temperature used for H2 formation */ gv.GasHeatPhotoEl = 0.; for( size_t nd=0; nd < gv.bin.size(); nd++ ) { long nz; /* this disables warnings about PAHs in the ionized region */ gv.bin[nd].lgPAHsInIonizedRegion = false; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { gv.bin[nd].chrg(nz).DustZ = nz; gv.bin[nd].chrg(nz).FracPop = ( nz == 0 ) ? 1. : 0.; gv.bin[nd].chrg(nz).nfill = 0; gv.bin[nd].chrg(nz).tedust = 100.f; } gv.bin[nd].AveDustZ = 0.; gv.bin[nd].dstpot = chrg2pot(0.,nd); gv.bin[nd].tedust = 100.f; gv.bin[nd].TeGrainMax = 100.; /* set all heating/cooling agents to zero */ gv.bin[nd].BolFlux = 0.; gv.bin[nd].GrainCoolTherm = 0.; gv.bin[nd].GasHeatPhotoEl = 0.; gv.bin[nd].GrainHeat = 0.; gv.bin[nd].GrainHeatColl = 0.; gv.bin[nd].ChemEn = 0.; gv.bin[nd].ChemEnH2 = 0.; gv.bin[nd].thermionic = 0.; gv.bin[nd].lgUseQHeat = false; gv.bin[nd].lgEverQHeat = false; gv.bin[nd].QHeatFailures = 0; gv.bin[nd].DustDftVel = 0.; gv.bin[nd].avdust = gv.bin[nd].tedust; gv.bin[nd].avdft = 0.f; gv.bin[nd].avdpot = (realnum)(gv.bin[nd].dstpot*EVRYD); gv.bin[nd].avDGRatio = -1.f; /* >>chng 06 jul 21, add this here as well as in GrainTemperature so that can * get fake heating when grain physics is turned off */ if( 0 && gv.lgBakesPAH_heat ) { /* this is a dirty hack to get BT94 PE heating rate * for PAH's included, for Lorentz Center 2004 PDR meeting, PvH */ /*>>>refer PAH heating Bakes, E.L.O., & Tielens, A.G.G.M. 1994, ApJ, 427, 822 */ /* >>chng 05 aug 12, change from +=, which added additional heating to what exists already, * to simply = to set the heat, this equation gives total heating */ gv.bin[nd].GasHeatPhotoEl = 1.e-24*hmi.UV_Cont_rel2_Habing_TH85_depth* dense.gas_phase[ipHYDROGEN]*(4.87e-2/(1.0+4e-3*pow((hmi.UV_Cont_rel2_Habing_TH85_depth* sqrt(phycon.te)/dense.eden),0.73)) + 3.65e-2*pow(phycon.te/1.e4,0.7)/ (1.+2.e-4*(hmi.UV_Cont_rel2_Habing_TH85_depth*sqrt(phycon.te)/dense.eden)))/gv.bin.size() * gv.GrainHeatScaleFactor; gv.GasHeatPhotoEl += gv.bin[nd].GasHeatPhotoEl; } } gv.TotalEden = 0.; gv.GrnElecDonateMax = 0.f; gv.GrnElecHoldMax = 0.f; for( nelem=0; nelem < LIMELM; nelem++ ) { for( ion=0; ion <= nelem+1; ion++ ) { for( ion_to=0; ion_to <= nelem+1; ion_to++ ) { gv.GrainChTrRate[nelem][ion][ion_to] = 0.f; } } } /* set all heating/cooling agents to zero */ gv.GrainHeatInc = 0.; gv.GrainHeatDif = 0.; gv.GrainHeatLya = 0.; gv.GrainHeatCollSum = 0.; gv.GrainHeatSum = 0.; gv.GrainHeatChem = 0.; gv.GasCoolColl = 0.; gv.TotalDustHeat = 0.f; gv.dphmax = 0.f; gv.dclmax = 0.f; thermal.setHeating(0,13,0.); thermal.setHeating(0,14,0.); thermal.setHeating(0,25,0.); } if( gv.nCalledGrainDrive == 0 || gv.lgAnyDustVary ) { GrainUpdateRadius1(); GrainUpdateRadius2(); } } ++gv.nCalledGrainDrive; return; } /* iterate grain charge and temperature */ STATIC void GrainChargeTemp() { long int i, ion, ion_to, nelem, nz; realnum dccool = FLT_MAX; double delta, GasHeatNet, hcon = DBL_MAX, hla = DBL_MAX, hots = DBL_MAX, oldtemp, oldTotalEden, ratio, ThermRatio; static long int oldZone = -1; static double oldTe = -DBL_MAX, oldHeat = -DBL_MAX; DEBUG_ENTRY( "GrainChargeTemp()" ); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, "\n GrainChargeTemp called lgSearch%2c\n\n", TorF(conv.lgSearch) ); } oldTotalEden = gv.TotalEden; /* these will sum heating agents over grain populations */ gv.GrainHeatInc = 0.; gv.GrainHeatDif = 0.; gv.GrainHeatLya = 0.; gv.GrainHeatCollSum = 0.; gv.GrainHeatSum = 0.; gv.GrainHeatChem = 0.; gv.GasCoolColl = 0.; gv.GasHeatPhotoEl = 0.; gv.GasHeatTherm = 0.; gv.TotalEden = 0.; for( nelem=0; nelem < LIMELM; nelem++ ) { for( ion=0; ion <= nelem+1; ion++ ) { for( ion_to=0; ion_to <= nelem+1; ion_to++ ) { gv.GrainChTrRate[nelem][ion][ion_to] = 0.f; } } } /* this sets dstAbund and conversion factors, but not gv.dstab and gv.dstsc! */ GrainUpdateRadius1(); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { double one; double ChTdBracketLo = 0., ChTdBracketHi = -DBL_MAX; long relax = ( conv.lgSearch ) ? 3 : 1; /* >>chng 02 nov 11, added test for the presence of PAHs in the ionized region, PvH */ if( gv.bin[nd].matType == MAT_PAH || gv.bin[nd].matType == MAT_PAH2 ) { if( dense.xIonDense[ipHYDROGEN][1]/dense.gas_phase[ipHYDROGEN] > 0.50 ) { gv.bin[nd].lgPAHsInIonizedRegion = true; } } /* >>chng 01 sep 13, dynamically allocate backup store, remove ncell dependence, PvH */ /* allocate data inside loop to avoid accidental spillover to next iteration */ /* >>chng 04 jan 18, no longer delete and reallocate data inside loop to speed up the code, PvH */ NewChargeData(nd); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " >>GrainChargeTemp starting grain %s\n", gv.bin[nd].chDstLab ); } delta = 2.*TOLER; /* >>chng 01 nov 29, relax max no. of iterations during initial search */ for( i=0; i < relax*CT_LOOP_MAX && delta > TOLER; ++i ) { string which; long j; double TdBracketLo = 0., TdBracketHi = -DBL_MAX; double ThresEst = 0.; oldtemp = gv.bin[nd].tedust; /* solve for charge using previous estimate for grain temp * grain temp only influences thermionic emissions * Thermratio is fraction thermionic emissions contribute * to the total electron loss rate of the grain */ GrainCharge(nd,&ThermRatio); ASSERT( gv.bin[nd].GrainHeat > 0. ); ASSERT( gv.bin[nd].tedust >= GRAIN_TMIN && gv.bin[nd].tedust <= GRAIN_TMAX ); /* >>chng 04 may 31, in conditions where collisions become an important * heating/cooling source (e.g. gas that is predominantly heated by cosmic * rays), the heating rate depends strongly on the assumed dust temperature. * hence it is necessary to iterate for the dust temperature. PvH */ gv.bin[nd].lgTdustConverged = false; for( j=0; j < relax*T_LOOP_MAX; ++j ) { double oldTemp2 = gv.bin[nd].tedust; double oldHeat2 = gv.bin[nd].GrainHeat; double oldCool = gv.bin[nd].GrainGasCool; /* now solve grain temp using new value for grain potential */ GrainTemperature(nd,&dccool,&hcon,&hots,&hla); gv.bin[nd].GrainGasCool = dccool; if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " >>loop %ld BracketLo %.6e BracketHi %.6e", j, TdBracketLo, TdBracketHi ); } /* this test assures that convergence can only happen if GrainHeat > 0 * and therefore the value of tedust is guaranteed to be valid as well */ /* >>chng 04 aug 05, test that gas cooling is converged as well, * in deep PDRs gas cooling depends critically on grain temperature, PvH */ if( fabs(gv.bin[nd].GrainHeat-oldHeat2) < HEAT_TOLER*gv.bin[nd].GrainHeat && fabs(gv.bin[nd].GrainGasCool-oldCool) < HEAT_TOLER_BIN*thermal.ctot ) { gv.bin[nd].lgTdustConverged = true; if( trace.lgTrace && trace.lgDustBug ) fprintf( ioQQQ, " converged\n" ); break; } /* update the bracket for the solution */ if( gv.bin[nd].tedust < oldTemp2 ) TdBracketHi = oldTemp2; else TdBracketLo = oldTemp2; /* GrainTemperature yields a new estimate for tedust, and initially * that estimate will be used. In most zones this will converge quickly. * However, sometimes the solution will oscillate and converge very * slowly. So, as soon as j >= 2 and the bracket is set up, we will * force convergence by using a bisection search within the bracket */ /** \todo 2 this algorithm might be more efficient with Brent */ /* this test assures that TdBracketHi is initialized */ if( TdBracketHi > TdBracketLo ) { /* if j >= 2, the solution is converging too slowly * so force convergence by doing a bisection search */ if( ( j >= 2 && TdBracketLo > 0. ) || gv.bin[nd].tedust <= TdBracketLo || gv.bin[nd].tedust >= TdBracketHi ) { gv.bin[nd].tedust = (realnum)(0.5*(TdBracketLo + TdBracketHi)); if( trace.lgTrace && trace.lgDustBug ) fprintf( ioQQQ, " bisection\n" ); } else { if( trace.lgTrace && trace.lgDustBug ) fprintf( ioQQQ, " iteration\n" ); } } else { if( trace.lgTrace && trace.lgDustBug ) fprintf( ioQQQ, " iteration\n" ); } ASSERT( gv.bin[nd].tedust >= GRAIN_TMIN && gv.bin[nd].tedust <= GRAIN_TMAX ); } if( gv.bin[nd].lgTdustConverged ) { /* update the bracket for the solution */ if( gv.bin[nd].tedust < oldtemp ) ChTdBracketHi = oldtemp; else ChTdBracketLo = oldtemp; } else { bool lgBoundErr; double y, x = log(gv.bin[nd].tedust); /* make sure GrainHeat is consistent with value of tedust */ splint_safe(gv.dsttmp,gv.bin[nd].dstems,gv.bin[nd].dstslp2,NDEMS,x,&y,&lgBoundErr); gv.bin[nd].GrainHeat = exp(y)*gv.bin[nd].cnv_H_pCM3; fprintf( ioQQQ," PROBLEM temperature of grain species %s (Tg=%.3eK) not converged\n", gv.bin[nd].chDstLab , gv.bin[nd].tedust ); ConvFail("grai",""); } ASSERT( gv.bin[nd].GrainHeat > 0. ); ASSERT( gv.bin[nd].tedust >= GRAIN_TMIN && gv.bin[nd].tedust <= GRAIN_TMAX ); /* delta estimates relative change in electron emission rate * due to the update in the grain temperature, if it is small * we won't bother to iterate (which is usually the case) * the formula assumes that thermionic emission is the only * process that depends on grain temperature */ /** \todo 2 should collisional heating/cooling be included here? */ ratio = gv.bin[nd].tedust/oldtemp; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { ThresEst += gv.bin[nd].chrg(nz).FracPop*gv.bin[nd].chrg(nz).ThresInf; } delta = ThresEst*TE1RYD/gv.bin[nd].tedust*(ratio - 1.); /** \todo 2 use something like log(ThermRatio) + log(delta) ???? */ delta = ( delta < 0.9*log(DBL_MAX) ) ? ThermRatio*fabs(POW2(ratio)*exp(delta)-1.) : DBL_MAX; /* >>chng 06 feb 07, bracket grain temperature to force convergence when oscillating, PvH */ if( delta > TOLER ) { if( trace.lgTrace && trace.lgDustBug ) which = "iteration"; /* The loop above yields a new estimate for tedust, and initially that * estimate will be used. In most zones this will converge very quickly. * However, sometimes the solution will oscillate and converge very * slowly. So, as soon as i >= 2 and the bracket is set up, we will * force convergence by using a bisection search within the bracket */ /** \todo 2 this algorithm might be more efficient with Brent */ /* this test assures that ChTdBracketHi is initialized */ if( ChTdBracketHi > ChTdBracketLo ) { /* if i >= 2, the solution is converging too slowly * so force convergence by doing a bisection search */ if( ( i >= 2 && ChTdBracketLo > 0. ) || gv.bin[nd].tedust <= ChTdBracketLo || gv.bin[nd].tedust >= ChTdBracketHi ) { gv.bin[nd].tedust = (realnum)(0.5*(ChTdBracketLo + ChTdBracketHi)); if( trace.lgTrace && trace.lgDustBug ) which = "bisection"; } } } if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " >>GrainChargeTemp finds delta=%.4e, ", delta ); fprintf( ioQQQ, " old/new temp=%.5e %.5e, ", oldtemp, gv.bin[nd].tedust ); if( delta > TOLER ) fprintf( ioQQQ, "doing another %s\n", which.c_str() ); else fprintf( ioQQQ, "converged\n" ); } } if( delta > TOLER ) { fprintf( ioQQQ, " PROBLEM charge/temperature not converged for %s zone %.2f\n", gv.bin[nd].chDstLab , fnzone ); ConvFail("grai",""); } /* add in ion recombination rates on this grain species */ /* ionbal.lgGrainIonRecom is 1 by default, set to 0 with * no grain neutralization command */ if( ionbal.lgGrainIonRecom ) GrainChrgTransferRates(nd); /* >>chng 04 jan 31, moved call to UpdateRadius2 outside loop, PvH */ /* following used to keep track of heating agents in printout * no physics done with GrainHeatInc * dust heating by incident continuum, and elec friction before ejection */ gv.GrainHeatInc += hcon; /* remember total heating by diffuse fields, for printout (includes Lya) */ gv.GrainHeatDif += hots; /* GrainHeatLya - total heating by LA in this zone, erg cm-3 s-1, only here * for eventual printout, hots is total ots line heating */ gv.GrainHeatLya += hla; /* this will be total collisional heating, for printing in lines */ gv.GrainHeatCollSum += gv.bin[nd].GrainHeatColl; /* GrainHeatSum is total heating of all grain types in this zone, * will be carried by total cooling, only used in lines to print tot heat * printed as entry "GraT 0 " */ gv.GrainHeatSum += gv.bin[nd].GrainHeat; /* net amount of chemical energy donated by recombining ions and molecule formation */ gv.GrainHeatChem += gv.bin[nd].ChemEn + gv.bin[nd].ChemEnH2; /* dccool is gas cooling due to collisions with grains - negative if net heating * zero if NO GRAIN GAS COLLISIONAL EXCHANGE command included */ gv.GasCoolColl += dccool; gv.GasHeatPhotoEl += gv.bin[nd].GasHeatPhotoEl; gv.GasHeatTherm += gv.bin[nd].thermionic; /* this is grain charge in e/cm^3, positive number means grain supplied free electrons */ /* >>chng 01 mar 24, changed DustZ+1 to DustZ, PvH */ one = 0.; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { one += gv.bin[nd].chrg(nz).FracPop*(double)gv.bin[nd].chrg(nz).DustZ* gv.bin[nd].cnv_GR_pCM3; } /* electron density contributed by grains, cm-3 */ gv.TotalEden += one; { /*@-redef@*/ enum {DEBUG_LOC=false}; /*@+redef@*/ if( DEBUG_LOC ) { fprintf(ioQQQ," DEBUG grn chr nz\t%.2f\teden\t%.3e\tnd\t%li", fnzone, dense.eden, (unsigned long)nd); fprintf(ioQQQ,"\tne\t%.2e\tAveDustZ\t%.2e\t%.2e\t%.2e\t%.2e", one, gv.bin[nd].AveDustZ, gv.bin[nd].chrg(0).FracPop,(double)gv.bin[nd].chrg(0).DustZ, gv.bin[nd].cnv_GR_pCM3); fprintf(ioQQQ,"\n"); } } if( trace.lgTrace && trace.lgDustBug ) { fprintf(ioQQQ," %s Pot %.5e Thermal %.5e GasCoolColl %.5e" , gv.bin[nd].chDstLab, gv.bin[nd].dstpot, gv.bin[nd].GrainHeat, dccool ); fprintf(ioQQQ," GasPEHeat %.5e GasThermHeat %.5e ChemHeat %.5e\n\n" , gv.bin[nd].GasHeatPhotoEl, gv.bin[nd].thermionic, gv.bin[nd].ChemEn ); } } /* >>chng 04 aug 06, added test of convergence of the net gas heating/cooling, PvH */ GasHeatNet = gv.GasHeatPhotoEl + gv.GasHeatTherm - gv.GasCoolColl; if( !fp_equal(phycon.te,gv.GrnRecomTe) ) { oldZone = gv.nzone; oldTe = gv.GrnRecomTe; oldHeat = gv.GasHeatNet; } /* >>chng 04 aug 07, added estimate for heating derivative, PvH */ if( nzone == oldZone && !fp_equal(phycon.te,oldTe) ) { gv.dHeatdT = (GasHeatNet-oldHeat)/(phycon.te-oldTe); } /* >>chng 04 sep 15, add test for convergence of gv.TotalEden, PvH */ if( nzone != gv.nzone || !fp_equal(phycon.te,gv.GrnRecomTe) || fabs(gv.GasHeatNet-GasHeatNet) > HEAT_TOLER*thermal.ctot || fabs(gv.TotalEden-oldTotalEden) > CHRG_TOLER*dense.eden ) { /* >>chng 04 aug 07, add test whether eden on grain converged */ /* flag that change in eden was too large */ /*conv.lgConvEden = false;*/ if( fabs(gv.TotalEden-oldTotalEden) > CHRG_TOLER*dense.eden ) { conv.setConvIonizFail( "grn eden chg" , oldTotalEden, gv.TotalEden); } else if( fabs(gv.GasHeatNet-GasHeatNet) > HEAT_TOLER*thermal.ctot ) { conv.setConvIonizFail( "grn het chg" , gv.GasHeatNet, GasHeatNet); } else if( !fp_equal(phycon.te,gv.GrnRecomTe) ) { conv.setConvIonizFail( "grn ter chg" , gv.GrnRecomTe, phycon.te); } else if( nzone != gv.nzone ) { conv.setConvIonizFail( "grn zon chg" , gv.nzone, nzone ); } else TotalInsanity(); } /* printf( "DEBUG GasHeatNet %.6e -> %.6e TotalEden %e -> %e conv.lgConvIoniz %c\n", gv.GasHeatNet, GasHeatNet, gv.TotalEden, oldTotalEden, TorF(conv.lgConvIoniz) ); */ /* printf( "DEBUG %.2f %e %e\n", fnzone, phycon.te, dense.eden ); */ /* update total grain opacities in gv.dstab and gv.dstsc, * they depend on grain charge and may depend on depth * also add in the photo-dissociation cs in gv.dstab */ GrainUpdateRadius2(); gv.nzone = nzone; gv.GrnRecomTe = phycon.te; gv.GasHeatNet = GasHeatNet; #ifdef WD_TEST2 printf("wd test: proton fraction %.5e Total DustZ %.6f heating/cooling rate %.5e %.5e\n", dense.xIonDense[ipHYDROGEN][1]/dense.gas_phase[ipHYDROGEN], gv.bin[0]->AveDustZ,gv.GasHeatPhotoEl/dense.gas_phase[ipHYDROGEN]/fudge(0), gv.GasCoolColl/dense.gas_phase[ipHYDROGEN]/fudge(0)); #endif if( trace.lgTrace ) { /*@-redef@*/ enum {DEBUG_LOC=false}; /*@+redef@*/ if( DEBUG_LOC ) { fprintf( ioQQQ, " %.2f Grain surface charge transfer rates\n", fnzone ); for( nelem=0; nelem < LIMELM; nelem++ ) { if( dense.lgElmtOn[nelem] ) { printf( " %s:", elementnames.chElementSym[nelem] ); for( ion=dense.IonLow[nelem]; ion <= dense.IonHigh[nelem]; ++ion ) { for( ion_to=0; ion_to <= nelem+1; ion_to++ ) { if( gv.GrainChTrRate[nelem][ion][ion_to] > 0.f ) { printf( " %ld->%ld %.2e", ion, ion_to, gv.GrainChTrRate[nelem][ion][ion_to] ); } } } printf( "\n" ); } } } fprintf( ioQQQ, " %.2f Grain contribution to electron density %.2e\n", fnzone , gv.TotalEden ); fprintf( ioQQQ, " Grain electons: " ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { double sum = 0.; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { sum += gv.bin[nd].chrg(nz).FracPop*(double)gv.bin[nd].chrg(nz).DustZ* gv.bin[nd].cnv_GR_pCM3; } fprintf( ioQQQ, " %.2e", sum ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " Grain potentials:" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %.2e", gv.bin[nd].dstpot ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " Grain temperatures:" ); for( size_t nd=0; nd < gv.bin.size(); nd++ ) { fprintf( ioQQQ, " %.2e", gv.bin[nd].tedust ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " GrainCollCool: %.6e\n", gv.GasCoolColl ); } /*if( nzone > 900) fprintf(ioQQQ,"DEBUG cool\t%.2f\t%e\t%e\t%e\n", fnzone, phycon.te , dense.eden, gv.GasCoolColl );*/ return; } STATIC void GrainCharge(size_t nd, /*@out@*/double *ThermRatio) /* ratio of thermionic to total rate */ { bool lgBigError; long backup, i, loopMax, newZlo, nz, power, stride, stride0, Zlo; double crate, csum1, csum1a, csum1b, csum2, csum3, netloss0 = -DBL_MAX, netloss1 = -DBL_MAX, rate_up[NCHU], rate_dn[NCHU], step; DEBUG_ENTRY( "GrainCharge()" ); /* find dust charge */ if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " Charge loop, search %c,", TorF(conv.lgSearch) ); } ASSERT( nd < gv.bin.size() ); for( nz=0; nz < NCHS; nz++ ) { gv.bin[nd].chrg(nz).FracPop = -DBL_MAX; } /* this algorithm determines the value of Zlo and the charge state populations * in the n-charge state model as described in: * * >>refer grain physics van Hoof P.A.M., Weingartner J.C., et al., 2004, MNRAS, 350, 1330 * * the algorithm first uses the n charge states to bracket the solution by * separating the charge states with a stride that is an integral power of * n-1, e.g. like this for an n == 4 calculation: * * +gain +gain -gain -gain * | | | | * -8 1 10 19 * * for each of the charge states the total electron emission and recombination * rates are calculated. the solution is considered properly bracketed if the * sign of the net gain rate (emission-recombination) is different for the first * and the last of the n charge states. then the algorithm searches for two * adjacent charge states where the net gain rate changes sign and divides * that space into n-1 equal parts, like here * * net gain + + + - * | | | | * Zg 1 4 7 10 * * note that the first and the last charge state can be retained from the * previous iteration and do not need to be recalculated (UpdatePot as well * as GrainElecEmis1 and GrainElecRecomb1 have mechanisms for re-using * previously calculated data, so GrainCharge doesn't need to worry about * this). The dividing algorithm is repeated until the stride equals 1, like * here * * net gain +--- * |||| * Zg 7 10 * * finally, the bracket may need to be shifted in order for the criterion * J1 x J2 <= 0 to be fulfilled (see the paper quoted above for a detailed * explanation). in the example here one shift might be necessary: * * net gain ++-- * |||| * Zg 6 9 * * for n == 2, the algorithm would have to be slightly different. In order * to avoid complicating the code, we force the code to use n == 3 in the * first two steps of the process, reverting back to n == 2 upon the last * step. this should not produce any noticeable additional CPU overhead */ backup = gv.bin[nd].nChrg; gv.bin[nd].nChrg = MAX2(gv.bin[nd].nChrg,3); stride0 = gv.bin[nd].nChrg-1; /* set up initial bracket for grain charge, will be checked below */ if( gv.bin[nd].lgIterStart ) { if( iteration == 1 ) { // this is the very first time the grain charge is determined // so here we try to get a rough first estimate of the charge long ilo = rfield.ipointC(0.9); long ihi = rfield.nflux; // determine average photon energy above 0.9 Ryd to ionize grain double sum1, sum2 = reduce_ab_a( get_ptr(rfield.flux[0]), rfield.anuptr(), ilo, ihi, &sum1 ); double anuav = safe_div( sum2, sum1, 0. ); if( anuav > 1. ) { // this is a hard radiation field -> assume grains are positively charged Zlo = 0; step = max(pot2chrg(anuav/2.,nd),1.); } else { // this is likely a PDR model -> assume grains are somewhat negative step = max(pot2chrg(0.2,nd),1.); Zlo = -long(nint(step/4.)); } power = (int)(log(step)/log((double)stride0)); power = MAX2(power,0); double xxx = powi((double)stride0,power); stride = nint(xxx); } else { // use the initial solution from the previous iteration stride = 1; Zlo = gv.bin[nd].ZloSave; } } else { /* the previous solution is the best choice here */ stride = 1; Zlo = gv.bin[nd].chrg(0).DustZ; } Zlo = max(Zlo,gv.bin[nd].LowestZg); UpdatePot( nd, Zlo, stride, rate_up, rate_dn ); /* check if the grain charge is correctly bracketed */ for( i=0; i < BRACKET_MAX; i++ ) { netloss0 = rate_up[0] - rate_dn[0]; netloss1 = rate_up[gv.bin[nd].nChrg-1] - rate_dn[gv.bin[nd].nChrg-1]; if( netloss0*netloss1 <= 0. ) break; if( netloss1 > 0. ) Zlo += (gv.bin[nd].nChrg-1)*stride; if( i > 0 ) stride *= stride0; if( netloss1 < 0. ) Zlo -= (gv.bin[nd].nChrg-1)*stride; Zlo = MAX2(Zlo,gv.bin[nd].LowestZg); UpdatePot( nd, Zlo, stride, rate_up, rate_dn ); } if( netloss0*netloss1 > 0. ) { fprintf( ioQQQ, " insanity: could not bracket grain charge for %s\n", gv.bin[nd].chDstLab ); ShowMe(); cdEXIT(EXIT_FAILURE); } /* home in on the charge */ while( stride > 1 ) { stride /= stride0; netloss0 = rate_up[0] - rate_dn[0]; for( nz=0; nz < gv.bin[nd].nChrg-1; nz++ ) { netloss1 = rate_up[nz+1] - rate_dn[nz+1]; if( netloss0*netloss1 <= 0. ) { Zlo = gv.bin[nd].chrg(nz).DustZ; break; } netloss0 = netloss1; } UpdatePot( nd, Zlo, stride, rate_up, rate_dn ); } ASSERT( netloss0*netloss1 <= 0. ); gv.bin[nd].nChrg = backup; /* >>chng 04 feb 15, relax upper limit on initial search when nChrg is much too large, PvH */ loopMax = ( gv.bin[nd].lgIterStart ) ? 4*gv.bin[nd].nChrg : 2*gv.bin[nd].nChrg; lgBigError = true; for( i=0; i < loopMax; i++ ) { GetFracPop( nd, Zlo, rate_up, rate_dn, &newZlo ); if( newZlo == Zlo ) { lgBigError = false; break; } Zlo = newZlo; UpdatePot( nd, Zlo, 1, rate_up, rate_dn ); } if( lgBigError ) { fprintf( ioQQQ, " insanity: could not converge grain charge for %s\n", gv.bin[nd].chDstLab ); ShowMe(); cdEXIT(EXIT_FAILURE); } gv.bin[nd].AveDustZ = 0.; crate = csum3 = 0.; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { double d[4]; gv.bin[nd].AveDustZ += gv.bin[nd].chrg(nz).FracPop*gv.bin[nd].chrg(nz).DustZ; crate += gv.bin[nd].chrg(nz).FracPop*GrainElecEmis1(nd,nz,&d[0],&d[1],&d[2],&d[3]); csum3 += gv.bin[nd].chrg(nz).FracPop*d[3]; } gv.bin[nd].dstpot = chrg2pot(gv.bin[nd].AveDustZ,nd); *ThermRatio = ( crate > 0. ) ? csum3/crate : 0.; ASSERT( *ThermRatio >= 0. ); gv.bin[nd].lgIterStart = false; if( trace.lgTrace && trace.lgDustBug ) { double d[4]; fprintf( ioQQQ, "\n" ); crate = csum1a = csum1b = csum2 = csum3 = 0.; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { crate += gv.bin[nd].chrg(nz).FracPop* GrainElecEmis1(nd,nz,&d[0],&d[1],&d[2],&d[3]); csum1a += gv.bin[nd].chrg(nz).FracPop*d[0]; csum1b += gv.bin[nd].chrg(nz).FracPop*d[1]; csum2 += gv.bin[nd].chrg(nz).FracPop*d[2]; csum3 += gv.bin[nd].chrg(nz).FracPop*d[3]; } fprintf( ioQQQ, " ElecEm rate1a=%.4e, rate1b=%.4e, ", csum1a, csum1b ); fprintf( ioQQQ, "rate2=%.4e, rate3=%.4e, sum=%.4e\n", csum2, csum3, crate ); if( crate > 0. ) { fprintf( ioQQQ, " rate1a/sum=%.4e, rate1b/sum=%.4e, ", csum1a/crate, csum1b/crate ); fprintf( ioQQQ, "rate2/sum=%.4e, rate3/sum=%.4e\n", csum2/crate, csum3/crate ); } crate = csum1 = csum2 = 0.; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { crate += gv.bin[nd].chrg(nz).FracPop*GrainElecRecomb1(nd,nz,&d[0],&d[1]); csum1 += gv.bin[nd].chrg(nz).FracPop*d[0]; csum2 += gv.bin[nd].chrg(nz).FracPop*d[1]; } fprintf( ioQQQ, " ElecRc rate1=%.4e, rate2=%.4e, sum=%.4e\n", csum1, csum2, crate ); if( crate > 0. ) { fprintf( ioQQQ, " rate1/sum=%.4e, rate2/sum=%.4e\n", csum1/crate, csum2/crate ); } fprintf( ioQQQ, " Charging rates:" ); for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { fprintf( ioQQQ, " Zg %ld up %.4e dn %.4e", gv.bin[nd].chrg(nz).DustZ, rate_up[nz], rate_dn[nz] ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " FracPop: fnzone %.2f nd %ld AveZg %.5e", fnzone, (unsigned long)nd, gv.bin[nd].AveDustZ ); for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { fprintf( ioQQQ, " Zg %ld %.5f", Zlo+nz, gv.bin[nd].chrg(nz).FracPop ); } fprintf( ioQQQ, "\n" ); fprintf( ioQQQ, " >Grain potential:%12.12s %.6fV", gv.bin[nd].chDstLab, gv.bin[nd].dstpot*EVRYD ); for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { fprintf( ioQQQ, " Thres[%ld]: %.4f V ThresVal[%ld]: %.4f V", gv.bin[nd].chrg(nz).DustZ, gv.bin[nd].chrg(nz).ThresInf*EVRYD, gv.bin[nd].chrg(nz).DustZ, gv.bin[nd].chrg(nz).ThresInfVal*EVRYD ); } fprintf( ioQQQ, "\n" ); } return; } /* grain electron recombination rates for single charge state */ STATIC double GrainElecRecomb1(size_t nd, long nz, /*@out@*/ double *sum1, /*@out@*/ double *sum2) { long ion, nelem; double eta, rate, Stick, ve, xi; DEBUG_ENTRY( "GrainElecRecomb1()" ); ASSERT( nd < gv.bin.size() ); ASSERT( nz >= 0 && nz < gv.bin[nd].nChrg ); /* >>chng 01 may 31, try to find cached results first */ /* >>chng 04 feb 11, moved cached data to ChargeBin, PvH */ if( gv.bin[nd].chrg(nz).RSum1 >= 0. ) { *sum1 = gv.bin[nd].chrg(nz).RSum1; *sum2 = gv.bin[nd].chrg(nz).RSum2; rate = *sum1 + *sum2; return rate; } /* -1 makes psi correct for impact by electrons */ ion = -1; /* VE is mean (not RMS) electron velocity */ /*ve = TePowers.sqrte*6.2124e5;*/ ve = sqrt(8.*BOLTZMANN/PI/ELECTRON_MASS*phycon.te); Stick = ( gv.bin[nd].chrg(nz).DustZ <= -1 ) ? gv.bin[nd].StickElecNeg : gv.bin[nd].StickElecPos; /* >>chng 00 jul 19, replace classical results with results including image potential * to correct for polarization of the grain as charged particle approaches. */ GrainScreen(ion,nd,nz,&eta,&xi); /* this is grain surface recomb rate for electrons */ *sum1 = ( gv.bin[nd].chrg(nz).DustZ > gv.bin[nd].LowestZg ) ? Stick*dense.eden*ve*eta : 0.; /* >>chng 00 jul 13, add in gain rate from atoms and ions, PvH */ *sum2 = 0.; #ifndef IGNORE_GRAIN_ION_COLLISIONS for( ion=0; ion <= LIMELM; ion++ ) { double CollisionRateAll = 0.; for( nelem=MAX2(ion-1,0); nelem < LIMELM; nelem++ ) { if( dense.lgElmtOn[nelem] && dense.xIonDense[nelem][ion] > 0. && gv.bin[nd].chrg(nz).RecomZ0[nelem][ion] > ion ) { /* this is rate with which charged ion strikes grain */ CollisionRateAll += STICK_ION*dense.xIonDense[nelem][ion]* GetAveVelocity( dense.AtomicWeight[nelem] )* (double)(gv.bin[nd].chrg(nz).RecomZ0[nelem][ion]-ion); } } if( CollisionRateAll > 0. ) { /* >>chng 00 jul 19, replace classical results with results * including image potential to correct for polarization * of the grain as charged particle approaches. */ GrainScreen(ion,nd,nz,&eta,&xi); *sum2 += CollisionRateAll*eta; } } #endif rate = *sum1 + *sum2; /* >>chng 01 may 31, store results so that they may be used agian */ gv.bin[nd].chrg(nz).RSum1 = *sum1; gv.bin[nd].chrg(nz).RSum2 = *sum2; ASSERT( *sum1 >= 0. && *sum2 >= 0. ); return rate; } /* grain electron emission rates for single charge state */ STATIC double GrainElecEmis1(size_t nd, long nz, /*@out@*/ double *sum1a, /*@out@*/ double *sum1b, /*@out@*/ double *sum2, /*@out@*/ double *sum3) { DEBUG_ENTRY( "GrainElecEmis1()" ); ASSERT( nd < gv.bin.size() ); ASSERT( nz >= 0 && nz < gv.bin[nd].nChrg ); /* >>chng 01 may 31, try to find cached results first */ /* >>chng 04 feb 11, moved cached data to ChargeBin, PvH */ if( gv.bin[nd].chrg(nz).ESum1a >= 0. ) { *sum1a = gv.bin[nd].chrg(nz).ESum1a; *sum1b = gv.bin[nd].chrg(nz).ESum1b; *sum2 = gv.bin[nd].chrg(nz).ESum2; /* don't cache thermionic rates as they depend on grain temp */ *sum3 = 4.*gv.bin[nd].chrg(nz).ThermRate; return *sum1a + *sum1b + *sum2 + *sum3; } /* this is the loss rate due to photo-electric effect (includes Auger and secondary electrons) */ /* >>chng 01 dec 18, added code for modeling secondary electron emissions, PvH */ /* this code does a crude correction for the Auger effect in grains, * it is roughly valid for neutral and negative grains, but overestimates * the effect for positively charged grains. Many of the Auger electrons have * rather low energies and will not make it out of the potential well for * high grain potentials typical of AGN conditions, see Table 4.1 & 4.2 of * >>refer grain physics Dwek E. & Smith R.K., 1996, ApJ, 459, 686 */ /* >>chng 06 jan 31, this code has been completely rewritten following * >>refer grain physics Weingartner J.C., Draine B.T, Barr D.K., 2006, ApJ, 645, 1188 */ ChargeBin& gptr = gv.bin[nd].chrg(nz); long ipLo = gptr.ipThresInfVal; long ipHi = rfield.nPositive; # ifdef WD_TEST2 *sum1a = reduce_abc( get_ptr(gv.bin[nd].dstab1), get_ptr(rfield.flux[0]), gptr.yhat.ptr0(), ipLo, ipHi ); # else *sum1a = reduce_abc( get_ptr(gv.bin[nd].dstab1), get_ptr(rfield.SummedCon), gptr.yhat.ptr0(), ipLo, ipHi ); # endif /* normalize to rates per cm^2 of projected grain area */ *sum1a /= gv.bin[nd].IntArea/4.; *sum1b = 0.; if( gptr.DustZ <= -1 ) { ipLo = gptr.ipThresInf; /* >>chng 00 jul 17, use description of Weingartner & Draine, 2001 */ # ifdef WD_TEST2 *sum1b = reduce_ab( gptr.cs_pdt.ptr0(), get_ptr(rfield.flux[0]), ipLo, ipHi ); # else *sum1b = reduce_ab( gptr.cs_pdt.ptr0(), get_ptr(rfield.SummedCon), ipLo, ipHi ); # endif *sum1b /= gv.bin[nd].IntArea/4.; } /* >>chng 00 jun 19, add in loss rate due to recombinations with ions, PvH */ *sum2 = 0.; # ifndef IGNORE_GRAIN_ION_COLLISIONS for( long ion=0; ion <= LIMELM; ion++ ) { double CollisionRateAll = 0.; for( long nelem=MAX2(ion-1,0); nelem < LIMELM; nelem++ ) { if( dense.lgElmtOn[nelem] && dense.xIonDense[nelem][ion] > 0. && ion > gptr.RecomZ0[nelem][ion] ) { /* this is rate with which charged ion strikes grain */ CollisionRateAll += dense.xIonDense[nelem][ion]* GetAveVelocity( dense.AtomicWeight[nelem] )* (double)(ion-gptr.RecomZ0[nelem][ion]); } } CollisionRateAll *= STICK_ION; if( CollisionRateAll > 0. ) { /* >>chng 00 jul 19, replace classical results with results * including image potential to correct for polarization * of the grain as charged particle approaches. */ double eta, xi; GrainScreen(ion,nd,nz,&eta,&xi); *sum2 += CollisionRateAll*eta; } } # endif /* >>chng 01 may 30, moved calculation of ThermRate to UpdatePot */ /* >>chng 01 jan 19, multiply by 4 since thermionic emissions scale with total grain * surface area while the above two processes scale with projected grain surface area, PvH */ *sum3 = 4.*gv.bin[nd].chrg(nz).ThermRate; /** \todo - add ionizations due to cosmic rays */ /* >>chng 01 may 31, store results so that they may be used agian */ gptr.ESum1a = *sum1a; gptr.ESum1b = *sum1b; gptr.ESum2 = *sum2; ASSERT( *sum1a >= 0. && *sum1b >= 0. && *sum2 >= 0. && *sum3 >= 0. ); return *sum1a + *sum1b + *sum2 + *sum3; } /* correction factors for grain charge screening (including image potential * to correct for polarization of the grain as charged particle approaches). */ STATIC void GrainScreen(long ion, size_t nd, long nz, /*@out@*/ double *eta, /*@out@*/ double *xi) { DEBUG_ENTRY( "GrainScreen()" ); /* >>chng 04 jan 31, start caching eta, xi results, PvH */ /* add 1 to allow for electron charge ion = -1 */ long ind = ion+1; ASSERT( ind >= 0 && ind < LIMELM+2 ); if( gv.bin[nd].chrg(nz).eta[ind] > 0. ) { *eta = gv.bin[nd].chrg(nz).eta[ind]; *xi = gv.bin[nd].chrg(nz).xi[ind]; return; } /* >>refer grain physics Draine & Sutin, 1987, ApJ, 320, 803 * eta = J-tilde (eq. 3.3 thru 3.5), xi = Lambda-tilde/2. (eq. 3.8 thru 3.10) */ if( ion == 0 ) { *eta = 1.; *xi = 1.; } else { /* >>chng 01 jan 03, assume that grain charge is distributed in two states just below and * above the average charge, instead of the delta function we assume elsewhere. by averaging * over the distribution we smooth out the discontinuities of the the Draine & Sutin expressions * around nu == 0. they were the cause of temperature instabilities in globule.in. PvH */ /* >>chng 01 may 07, revert back to single charge state since only integral charge states are * fed into this routine now, making the two-charge state approximation obsolete, PvH */ double nu = (double)gv.bin[nd].chrg(nz).DustZ/(double)ion; double tau = gv.bin[nd].Capacity*BOLTZMANN*phycon.te*1.e-7/POW2((double)ion*ELEM_CHARGE); if( nu < 0. ) { *eta = (1. - nu/tau)*(1. + sqrt(2./(tau - 2.*nu))); *xi = (1. - nu/(2.*tau))*(1. + 1./sqrt(tau - nu)); } else if( nu == 0. ) { *eta = 1. + sqrt(PI/(2.*tau)); *xi = 1. + 0.75*sqrt(PI/(2.*tau)); } else { double theta_nu = ThetaNu(nu); /* >>>chng 00 jul 27, avoid passing functions to macro so set to local temp var */ double xxx = 1. + 1./sqrt(4.*tau+3.*nu); *eta = POW2(xxx)*exp(-theta_nu/tau); # ifdef WD_TEST2 *xi = (1. + nu/(2.*tau))*(1. + 1./sqrt(3./(2.*tau)+3.*nu))*exp(-theta_nu/tau); # else /* >>chng 01 jan 24, use new expression for xi which only contains the excess * energy above the potential barrier of the incoming particle (accurate to * 2% or better), and then add in potential barrier separately, PvH */ xxx = 0.25*powpq(nu/tau,3,4)/(powpq(nu/tau,3,4) + powpq((25.+3.*nu)/5.,3,4)) + (1. + 0.75*sqrt(PI/(2.*tau)))/(1. + sqrt(PI/(2.*tau))); *xi = (MIN2(xxx,1.) + theta_nu/(2.*tau))*(*eta); # endif } ASSERT( *eta >= 0. && *xi >= 0. ); } gv.bin[nd].chrg(nz).eta[ind] = *eta; gv.bin[nd].chrg(nz).xi[ind] = *xi; return; } STATIC double ThetaNu(double nu) { DEBUG_ENTRY( "ThetaNu()" ); double theta_nu; if( nu > 0. ) { double xxx; const double REL_TOLER = 10.*DBL_EPSILON; /* >>chng 01 jan 24, get first estimate for xi_nu and iteratively refine, PvH */ double xi_nu = 1. + 1./sqrt(3.*nu); double xi_nu2 = POW2(xi_nu); do { double old = xi_nu; /* >>chng 04 feb 01, use Newton-Raphson to speed up convergence, PvH */ /* xi_nu = sqrt(1.+sqrt((2.*POW2(xi_nu)-1.)/(nu*xi_nu))); */ double fnu = 2.*xi_nu2 - 1. - nu*xi_nu*POW2(xi_nu2 - 1.); double dfdxi = 4.*xi_nu - nu*((5.*xi_nu2 - 6.)*xi_nu2 + 1.); xi_nu -= fnu/dfdxi; xi_nu2 = POW2(xi_nu); xxx = fabs(old-xi_nu); } while( xxx > REL_TOLER*xi_nu ); theta_nu = nu/xi_nu - 1./(2.*xi_nu2*(xi_nu2-1.)); } else { theta_nu = 0.; } return theta_nu; } /* update items that depend on grain potential */ STATIC void UpdatePot(size_t nd, long Zlo, long stride, /*@out@*/ double rate_up[], /* rate_up[NCHU] */ /*@out@*/ double rate_dn[]) /* rate_dn[NCHU] */ { DEBUG_ENTRY( "UpdatePot()" ); ASSERT( nd < gv.bin.size() ); ASSERT( Zlo >= gv.bin[nd].LowestZg ); ASSERT( stride >= 1 ); /* >>chng 00 jul 17, use description of Weingartner & Draine, 2001 */ /* >>chng 01 mar 21, assume that grain charge is distributed in two states just below and * above the average charge. */ /* >>chng 01 may 07, this routine now completely supports the hybrid grain * charge model, and the average charge state is not used anywhere anymore, PvH */ /* >>chng 01 may 30, reorganize code such that all relevant data can be copied * when a valid set of data is available from a previous call, this saves CPU time, PvH */ /* >>chng 04 jan 17, reorganized code to use pointers to the charge bins, PvH */ if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " %ld/%ld", Zlo, stride ); } if( gv.bin[nd].nfill < rfield.nPositive ) { InitBinAugerData( nd, gv.bin[nd].nfill, rfield.nPositive ); gv.bin[nd].nfill = rfield.nPositive; } for( long nz=0; nz < gv.bin[nd].nChrg; nz++ ) { long Zg = Zlo + nz*stride; /* check if charge state is already present */ long ind = NCHS-1; for( long zz=0; zz < NCHS-1; zz++ ) { if( gv.bin[nd].chrg(zz).DustZ == Zg ) { ind = zz; break; } } /* in the code below the old charge bins are shifted to the back in order to assure * that the most recently used ones are upfront; they are more likely to be reused */ long ptr = gv.bin[nd].ichrg[ind]; /* make room to swap in charge state */ for( long zz=ind-1; zz >= nz; zz-- ) gv.bin[nd].ichrg[zz+1] = gv.bin[nd].ichrg[zz]; gv.bin[nd].ichrg[nz] = ptr; if( gv.bin[nd].chrg(nz).DustZ != Zg ) UpdatePot1(nd,nz,Zg,0); else if( gv.bin[nd].chrg(nz).nfill < rfield.nPositive ) UpdatePot1(nd,nz,Zg,gv.bin[nd].chrg(nz).nfill); UpdatePot2(nd,nz); double d[4]; rate_up[nz] = GrainElecEmis1(nd,nz,&d[0],&d[1],&d[2],&d[3]); rate_dn[nz] = GrainElecRecomb1(nd,nz,&d[0],&d[1]); /* sanity checks */ ASSERT( gv.bin[nd].chrg(nz).DustZ == Zg ); ASSERT( gv.bin[nd].chrg(nz).nfill >= rfield.nPositive ); ASSERT( rate_up[nz] >= 0. && rate_dn[nz] >= 0. ); } /* determine highest energy to be considered by quantum heating routines. * since the Boltzmann distribution is resolved, the upper limit has to be * high enough that a negligible amount of energy is in the omitted tail */ /* >>chng 03 jan 26, moved this code from GrainChargeTemp to UpdatePot * since the new code depends on grain potential, HTT91.in, PvH */ double BoltzFac = (-log(CONSERV_TOL) + 8.)*BOLTZMANN/EN1RYD; double HighEnergy = 0.; for( long nz=0; nz < gv.bin[nd].nChrg; nz++ ) { /* >>chng 04 jan 21, changed phycon.te -> MAX2(phycon.te,gv.bin[nd].tedust), PvH */ HighEnergy = MAX2(HighEnergy, MAX2(gv.bin[nd].chrg(nz).ThresInfInc,0.) + BoltzFac*MAX2(phycon.te,gv.bin[nd].tedust)); } HighEnergy = min(HighEnergy,rfield.anu(rfield.nflux)); gv.bin[nd].qnflux2 = ipoint(HighEnergy); gv.bin[nd].qnflux = max(rfield.nPositive,gv.bin[nd].qnflux2); gv.bin[nd].qnflux = min(gv.bin[nd].qnflux,rfield.nflux); return; } /* calculate charge state populations */ STATIC void GetFracPop(size_t nd, long Zlo, /*@in@*/ double rate_up[], /* rate_up[NCHU] */ /*@in@*/ double rate_dn[], /* rate_dn[NCHU] */ /*@out@*/ long *newZlo) { DEBUG_ENTRY( "GetFracPop()" ); ASSERT( nd < gv.bin.size() ); ASSERT( Zlo >= gv.bin[nd].LowestZg ); bool lgRedo; double netloss[2], pop[2][NCHU-1]; /* solve level populations for levels 0..nChrg-2 (i == 0) and * levels 1..nChrg-1 (i == 1), and determine net electron loss rate * for each of those subsystems. Next we demand that * netloss[1] <= 0 <= netloss[0] * and determine FracPop by linearly adding the subsystems such that * 0 == frac*netloss[0] + (1-frac)*netloss[1] * this assures that all charge state populations are positive */ do { for( long i=0; i < 2; i++ ) { double sum = pop[i][0] = 1.; long nlim = gv.bin[nd].nChrg-1; for( long j=1; j < nlim; j++ ) { long nz = i + j; if( rate_dn[nz] > 10.*rate_up[nz-1]/sqrt(DBL_MAX) ) { pop[i][j] = pop[i][j-1]*rate_up[nz-1]/rate_dn[nz]; sum += pop[i][j]; } else { for( long k=0; k < j; k++ ) { pop[i][k] = 0.; } pop[i][j] = 1.; sum = pop[i][j]; } /* guard against overflow */ if( pop[i][j] > sqrt(DBL_MAX) ) { for( long k=0; k <= j; k++ ) { pop[i][k] /= DBL_MAX/10.; } sum /= DBL_MAX/10.; } } netloss[i] = 0.; for( long j=0; j < nlim; j++ ) { long nz = i + j; pop[i][j] /= sum; netloss[i] += pop[i][j]*(rate_up[nz] - rate_dn[nz]); } } /* ascertain that the choice of Zlo was correct, this is to ensure positive * level populations and continuous emission and recombination rates */ if( netloss[0]*netloss[1] > 0. ) *newZlo = ( netloss[1] > 0. ) ? Zlo + 1 : Zlo - 1; else *newZlo = Zlo; /* >>chng 04 feb 15, add protection for roundoff error when nChrg is much too large; * netloss[0/1] can be almost zero, but may have arbitrary sign due to roundoff error; * this can lead to a spurious lowering of Zlo below LowestZg, orion_pdr10.in, * since newZlo cannot be lowered, lower nChrg instead and recalculate, PvH */ /* >>chng 04 feb 15, also lower nChrg if population of highest charge state is marginal */ if( gv.bin[nd].nChrg > 2 && ( *newZlo < gv.bin[nd].LowestZg || ( *newZlo == Zlo && pop[1][gv.bin[nd].nChrg-2] < DBL_EPSILON ) ) ) { gv.bin[nd].nChrg--; lgRedo = true; } else { lgRedo = false; } # if 0 printf( " fnzone %.2f nd %ld Zlo %ld newZlo %ld netloss %.4e %.4e nChrg %ld lgRedo %d\n", fnzone, nd, Zlo, *newZlo, netloss[0], netloss[1], gv.bin[nd].nChrg, lgRedo ); # endif } while( lgRedo ); if( *newZlo < gv.bin[nd].LowestZg ) { fprintf( ioQQQ, " could not converge charge state populations for %s\n", gv.bin[nd].chDstLab ); ShowMe(); cdEXIT(EXIT_FAILURE); } if( *newZlo == Zlo ) { /* frac1 == 1-frac0, but calculating it like this avoids cancellation errors */ double frac0 = netloss[1]/(netloss[1]-netloss[0]); double frac1 = -netloss[0]/(netloss[1]-netloss[0]); gv.bin[nd].chrg(0).FracPop = frac0*pop[0][0]; gv.bin[nd].chrg(gv.bin[nd].nChrg-1).FracPop = frac1*pop[1][gv.bin[nd].nChrg-2]; for( long nz=1; nz < gv.bin[nd].nChrg-1; nz++ ) { gv.bin[nd].chrg(nz).FracPop = frac0*pop[0][nz] + frac1*pop[1][nz-1]; } # ifndef NDEBUG double test1 = 0., test2 = 0., test3 = 0.; for( long nz=0; nz < gv.bin[nd].nChrg; nz++ ) { ASSERT( gv.bin[nd].chrg(nz).FracPop >= 0. ); test1 += gv.bin[nd].chrg(nz).FracPop; test2 += gv.bin[nd].chrg(nz).FracPop*rate_up[nz]; test3 += gv.bin[nd].chrg(nz).FracPop*(rate_up[nz]-rate_dn[nz]); } double x1 = fabs(test1-1.); double x2 = fabs( safe_div(test3, test2, 0.) ); ASSERT( MAX2(x1,x2) < 10.*sqrt((double)gv.bin[nd].nChrg)*DBL_EPSILON ); # endif } return; } /* this routine updates all quantities that depend only on grain charge and radius * * NB NB - All global data in grain.c and grainvar.h that are charge dependent should * be calculated here or in UpdatePot2 (except gv.bin[nd].chrg(nz).FracPop * which is special). * * NB NB - the code assumes that the data calculated here remain valid throughout * the model, i.e. do NOT depend on grain temperature, etc. */ STATIC void UpdatePot1(size_t nd, long nz, long Zg, long ipStart) { DEBUG_ENTRY( "UpdatePot1()" ); /* constants in the expression for the photodetachment cross section * taken from * >>refer grain physics Weingartner & Draine, ApJS, 2001, 134, 263 */ const double INV_DELTA_E = EVRYD/3.; const double CS_PDT = 1.2e-17; /* >>chng 04 jan 23, replaced rfield.nflux with rfield.nflux_with_check so * that data remains valid throughout the model, PvH */ /* >>chng 04 jan 26, start using ipStart to solve the validity problem * ipStart == 0 means that a full initialization needs to be done * ipStart > 0 means that rfield.nflux was updated and yhat(_primary), ehat, * cs_pdt, fac1, and fac2 need to be reallocated, PvH */ if( ipStart == 0 ) { gv.bin[nd].chrg(nz).DustZ = Zg; /* invalidate eta and xi storage */ memset( gv.bin[nd].chrg(nz).eta, 0, (LIMELM+2)*sizeof(double) ); memset( gv.bin[nd].chrg(nz).xi, 0, (LIMELM+2)*sizeof(double) ); GetPotValues(nd,Zg,&gv.bin[nd].chrg(nz).ThresInf,&gv.bin[nd].chrg(nz).ThresInfVal, &gv.bin[nd].chrg(nz).ThresSurf,&gv.bin[nd].chrg(nz).ThresSurfVal, &gv.bin[nd].chrg(nz).PotSurf,&gv.bin[nd].chrg(nz).Emin,INCL_TUNNEL); /* >>chng 01 may 09, do not use tunneling corrections for incoming electrons */ /* >>chng 01 nov 25, add gv.bin[nd].chrg(nz).ThresInfInc, PvH */ double d[2]; GetPotValues(nd,Zg-1,&gv.bin[nd].chrg(nz).ThresInfInc,&d[0],&gv.bin[nd].chrg(nz).ThresSurfInc, &d[1],&gv.bin[nd].chrg(nz).PotSurfInc,&gv.bin[nd].chrg(nz).EminInc,NO_TUNNEL); gv.bin[nd].chrg(nz).ipThresInfVal = rfield.ithreshC( gv.bin[nd].chrg(nz).ThresInfVal ); } ASSERT( gv.bin[nd].chrg(nz).DustZ == Zg ); long ipLo = gv.bin[nd].chrg(nz).ipThresInfVal; /* remember how far the yhat(_primary), ehat, cs_pdt, fac1, and fac2 arrays were filled in */ gv.bin[nd].chrg(nz).nfill = rfield.nPositive; long nfill = gv.bin[nd].chrg(nz).nfill; /* >>chng 04 feb 07, only allocate arrays from ipLo to nfill to save memory, PvH */ long len = rfield.nflux_with_check - ipLo; if( ipStart == 0 ) { gv.bin[nd].chrg(nz).yhat.reserve( len ); gv.bin[nd].chrg(nz).yhat_primary.reserve( len ); gv.bin[nd].chrg(nz).ehat.reserve( len ); gv.bin[nd].chrg(nz).yhat.alloc( ipLo, nfill ); gv.bin[nd].chrg(nz).yhat_primary.alloc( ipLo, nfill ); gv.bin[nd].chrg(nz).ehat.alloc( ipLo, nfill ); } else { gv.bin[nd].chrg(nz).yhat.realloc( nfill ); gv.bin[nd].chrg(nz).yhat_primary.realloc( nfill ); gv.bin[nd].chrg(nz).ehat.realloc( nfill ); } double GrainPot = chrg2pot(Zg,nd); const double *anu = rfield.anuptr(); if( nfill > ipLo ) { double DustWorkFcn = gv.bin[nd].DustWorkFcn; double Elo = -gv.bin[nd].chrg(nz).PotSurf; double ThresInfVal = gv.bin[nd].chrg(nz).ThresInfVal; double Emin = gv.bin[nd].chrg(nz).Emin; double Wcorr = ThresInfVal + Emin - GrainPot; /** \todo xray - secondaries from incident electrons still need to be added in */ /** \todo xray - primary, secondary, auger electrons need to be added into suprathermals */ ShellData *sptr = &gv.bin[nd].sd[0]; ASSERT( sptr->ipLo <= ipLo ); long ipBegin = max(ipLo,ipStart); avx_ptr<realnum> yzero(ipBegin, nfill); y0b(nd, nz, yzero.ptr0(), ipBegin, nfill); /* calculate yield for band structure */ avx_ptr<double> Ehi(ipBegin, nfill), Ehi_band(ipBegin, nfill), Eel(ipBegin, nfill); for( long i=ipBegin; i < nfill; i++ ) { Ehi[i] = anu[i] - ThresInfVal - Emin; Ehi_band[i] = Ehi[i]; Eel[i] = anu[i] - DustWorkFcn; } avx_ptr<realnum> yp(ipBegin, nfill), ya(ipBegin, nfill), ys(ipBegin, nfill), eyp(ipBegin, nfill), eya(ipBegin, nfill), eys(ipBegin, nfill), Yp1(ipBegin, nfill), Ys1(ipBegin, nfill), Ehp(ipBegin, nfill), Ehs(ipBegin, nfill); Yfunc(nd, nz, yzero.ptr0(), sptr->y01.ptr0(), sptr->p.ptr0(), Elo, Ehi.ptr0(), Eel.ptr0(), Yp1.ptr0(), Ys1.ptr0(), Ehp.ptr0(), Ehs.ptr0(), ipBegin, nfill); if( nfill > ipBegin ) { memset( ya.data(), 0, size_t((nfill-ipBegin)*sizeof(ya[ipBegin])) ); memset( eya.data(), 0, size_t((nfill-ipBegin)*sizeof(eya[ipBegin])) ); } // write this as two separate loops so that they get vectorized for( long i=ipBegin; i < nfill; i++ ) { yp[i] = Yp1[i]; eyp[i] = Yp1[i]*Ehp[i]; } for( long i=ipBegin; i < nfill; i++ ) { ys[i] = Ys1[i]; eys[i] = Ys1[i]*Ehs[i]; } /* add in yields for inner shell ionization */ unsigned int nsmax = gv.bin[nd].sd.size(); for( unsigned int ns=1; ns < nsmax; ns++ ) { sptr = &gv.bin[nd].sd[ns]; long ipBeginShell = max(ipBegin, sptr->ipLo); double ionPot = sptr->ionPot; for( long i=ipBeginShell; i < nfill; i++ ) { Ehi[i] = Ehi_band[i] + Wcorr - ionPot; Eel[i] = anu[i] - ionPot; } Yfunc(nd, nz, sptr->y01.ptr0(), NULL, sptr->p.ptr0(), Elo, Ehi.ptr0(), Eel.ptr0(), Yp1.ptr0(), Ys1.ptr0(), Ehp.ptr0(), Ehs.ptr0(), ipBeginShell, nfill); // write this as two separate loops so that they get vectorized for( long i=ipBeginShell; i < nfill; i++ ) { yp[i] += Yp1[i]; eyp[i] += Yp1[i]*Ehp[i]; } for( long i=ipBeginShell; i < nfill; i++ ) { ys[i] += Ys1[i]; eys[i] += Ys1[i]*Ehs[i]; } /* add in Auger yields */ long nmax = sptr->nData; for( long n=0; n < nmax; n++ ) { avx_ptr<realnum> max(ipBeginShell, nfill); double AvNr = sptr->AvNr[n]; double Ener = sptr->Ener[n]; double Ehic = Ener - GrainPot; double Eelc = Ener; for( long i=ipBeginShell; i < nfill; i++ ) max[i] = AvNr*sptr->p[i]; Yfunc(nd, nz, sptr->y01A[n].ptr0(), max.ptr0(), Elo, Ehic, Eelc, Yp1.ptr0(), Ys1.ptr0(), Ehp.ptr0(), Ehs.ptr0(), ipBeginShell, nfill); // write this as two separate loops so that they get vectorized for( long i=ipBeginShell; i < nfill; i++ ) { ya[i] += Yp1[i]; eya[i] += Yp1[i]*Ehp[i]; } for( long i=ipBeginShell; i < nfill; i++ ) { ys[i] += Ys1[i]; eys[i] += Ys1[i]*Ehs[i]; } } } /* add up primary, Auger, and secondary yields */ for( long i=ipBegin; i < nfill; i++ ) { gv.bin[nd].chrg(nz).yhat[i] = yp[i] + ya[i] + ys[i]; gv.bin[nd].chrg(nz).yhat_primary[i] = min(yp[i],1.f); // if gv.bin[nd].chrg(nz).ThresInfVal and rfield.anu(ipLo) are extremely // close, gv.bin[nd].chrg(nz).yhat[i] and ehat[i] can underflow to zero gv.bin[nd].chrg(nz).ehat[i] = ( gv.bin[nd].chrg(nz).yhat[i] > 0.f ) ? (eyp[i] + eya[i] + eys[i])/gv.bin[nd].chrg(nz).yhat[i] : 0.f; ASSERT( yp[i] <= 1.00001f ); ASSERT( gv.bin[nd].chrg(nz).ehat[i] >= 0.f ); } } if( ipStart == 0 ) { /* >>chng 01 jan 08, ThresInf[nz] and ThresInfVal[nz] may become zero in * initial stages of grain potential search, PvH */ /* >>chng 01 oct 10, use bisection search to find ipThresInf, ipThresInfVal. On C scale now */ gv.bin[nd].chrg(nz).ipThresInf = rfield.ithreshC( gv.bin[nd].chrg(nz).ThresInf ); } ipLo = gv.bin[nd].chrg(nz).ipThresInf; len = rfield.nflux_with_check - ipLo; if( Zg <= -1 ) { /* >>chng 04 feb 07, only allocate arrays from ipLo to nfill to save memory, PvH */ if( ipStart == 0 ) { gv.bin[nd].chrg(nz).cs_pdt.reserve( len ); gv.bin[nd].chrg(nz).cs_pdt.alloc( ipLo, rfield.nflux ); double c1 = -CS_PDT*(double)Zg; double ThresInf = gv.bin[nd].chrg(nz).ThresInf; double cnv_GR_pH = gv.bin[nd].cnv_GR_pH; for( long i=ipLo; i < rfield.nflux; i++ ) { double x = (anu[i] - ThresInf)*INV_DELTA_E; double cs = c1*x/POW2(1.+(1./3.)*POW2(x)); /* this cross section must be at default depletion for consistency * with dstab1, hence no factor dstAbund should be applied here */ gv.bin[nd].chrg(nz).cs_pdt[i] = MAX2(cs,0.)*cnv_GR_pH; } } } /* >>chng 04 feb 07, added fac1, fac2 to optimize loop for photoelectric heating, PvH */ if( ipStart == 0 ) { gv.bin[nd].chrg(nz).fac1.reserve( len ); gv.bin[nd].chrg(nz).fac2.reserve( len ); gv.bin[nd].chrg(nz).fac1.alloc( ipLo, nfill ); gv.bin[nd].chrg(nz).fac2.alloc( ipLo, nfill ); } else { gv.bin[nd].chrg(nz).fac1.realloc( nfill ); gv.bin[nd].chrg(nz).fac2.realloc( nfill ); } if( nfill > ipLo ) { for( long i=max(ipLo,ipStart); i < nfill; i++ ) { double cs1,cs2,cs_tot,cool1,cool2,ehat1,ehat2; /* >>chng 04 jan 25, created separate routine PE_init, PvH */ PE_init(nd,nz,i,&cs1,&cs2,&cs_tot,&cool1,&cool2,&ehat1,&ehat2); gv.bin[nd].chrg(nz).fac1[i] = cs_tot*anu[i]-cs1*cool1-cs2*cool2; gv.bin[nd].chrg(nz).fac2[i] = cs1*ehat1 + cs2*ehat2; ASSERT( gv.bin[nd].chrg(nz).fac1[i] >= 0. && gv.bin[nd].chrg(nz).fac2[i] >= 0. ); } } if( ipStart == 0 ) { /* >>chng 00 jul 05, determine ionization stage Z0 the ion recombines to */ /* >>chng 04 jan 20, use all stages here so that result remains valid throughout the model */ UpdateRecomZ0(nd,nz); } /* invalidate the remaining fields */ gv.bin[nd].chrg(nz).FracPop = -DBL_MAX; gv.bin[nd].chrg(nz).RSum1 = -DBL_MAX; gv.bin[nd].chrg(nz).RSum2 = -DBL_MAX; gv.bin[nd].chrg(nz).ESum1a = -DBL_MAX; gv.bin[nd].chrg(nz).ESum1b = -DBL_MAX; gv.bin[nd].chrg(nz).ESum2 = -DBL_MAX; gv.bin[nd].chrg(nz).tedust = 1.f; gv.bin[nd].chrg(nz).hcon1 = -DBL_MAX; gv.bin[nd].chrg(nz).hots1 = -DBL_MAX; gv.bin[nd].chrg(nz).bolflux1 = -DBL_MAX; gv.bin[nd].chrg(nz).pe1 = -DBL_MAX; gv.bin[nd].chrg(nz).BolFlux = -DBL_MAX; gv.bin[nd].chrg(nz).GrainHeat = -DBL_MAX; gv.bin[nd].chrg(nz).GrainHeatColl = -DBL_MAX; gv.bin[nd].chrg(nz).GasHeatPhotoEl = -DBL_MAX; gv.bin[nd].chrg(nz).GasHeatTherm = -DBL_MAX; gv.bin[nd].chrg(nz).GrainCoolTherm = -DBL_MAX; gv.bin[nd].chrg(nz).ChemEnIon = -DBL_MAX; gv.bin[nd].chrg(nz).ChemEnH2 = -DBL_MAX; gv.bin[nd].chrg(nz).HeatingRate2 = -DBL_MAX; /* sanity check */ ASSERT( gv.bin[nd].chrg(nz).ipThresInf <= gv.bin[nd].chrg(nz).ipThresInfVal ); return; } /* this routine updates all quantities that depend on grain charge, radius and temperature * * NB NB - All global data in grain.c and grainvar.h that are charge dependent should * be calculated here or in UpdatePot1 (except gv.bin[nd].chrg(nz).FracPop * which is special). * * NB NB - the code assumes that the data calculated here may vary throughout the model, * e.g. because of a dependence on grain temperature */ STATIC void UpdatePot2(size_t nd, long nz) { DEBUG_ENTRY( "UpdatePot2()" ); /* >>chng 00 jun 19, add in loss rate due to thermionic emission of electrons, PvH */ double ThermExp = gv.bin[nd].chrg(nz).ThresInf*TE1RYD/gv.bin[nd].tedust; /* ThermExp is guaranteed to be >= 0. */ gv.bin[nd].chrg(nz).ThermRate = THERMCONST*gv.bin[nd].ThermEff*POW2(gv.bin[nd].tedust)*exp(-ThermExp); # if defined( WD_TEST2 ) || defined( IGNORE_THERMIONIC ) gv.bin[nd].chrg(nz).ThermRate = 0.; # endif return; } /* Helper function to calculate primary and secondary yields and the average electron energy at infinity */ STATIC void Yfunc(long nd, long nz, const realnum y0[], const realnum y1[], const realnum maxval[], double Elo, const double Ehi[], const double Eel[], /*@out@*/ realnum Yp[], /*@out@*/ realnum Ys[], /*@out@*/ realnum Ehp[], /*@out@*/ realnum Ehs[], long ilo, long ihi) { DEBUG_ENTRY( "Yfunc()" ); if( ihi <= ilo ) return; long Zg = gv.bin[nd].chrg(nz).DustZ; double eps; pe_type pcase = gv.which_pe[gv.bin[nd].matType]; if( pcase == PE_CAR ) eps = 117./EVRYD; else if( pcase == PE_SIL ) eps = 155./EVRYD; else { fprintf( ioQQQ, " Yfunc: unknown type for PE effect: %d\n" , pcase ); cdEXIT(EXIT_FAILURE); } avx_ptr<realnum> y2pr(ilo, ihi), y2sec(ilo, ihi), y01cap(ilo, ihi); y2pa( Elo, Ehi, Zg, Ehp, y2pr.ptr0(), ilo, ihi ); y2s( Elo, Ehi, Zg, y2pr.ptr0(), Ehs, y2sec.ptr0(), ilo, ihi ); if( y1 == NULL ) { for( long i=ilo; i < ihi; ++i ) y01cap[i] = min(y0[i],maxval[i]); } else { for( long i=ilo; i < ihi; ++i ) y01cap[i] = min(y0[i]*y1[i],maxval[i]); } for( long i=ilo; i < ihi; ++i ) { ASSERT( Ehi[i] >= Elo ); if( y2pr[i] > 0.f ) { Yp[i] = y2pr[i]*y01cap[i]; /* this is Eq. 18 of WDB06 */ /* Eel may be negative near threshold -> set yield to zero */ realnum f3 = max(Eel[i],0.)/(eps*elec_esc_length(Eel[i],nd)*gv.bin[nd].eyc); Ys[i] = y2sec[i]*f3*y01cap[i]; } else { Yp[i] = 0.f; Ys[i] = 0.f; Ehp[i] = 0.f; Ehs[i] = 0.f; } } } // overloaded version of Yfunc exploiting the fact that Ehi and Eel are independent of frequency STATIC void Yfunc(long nd, long nz, const realnum y01[], const realnum maxval[], double Elo, double Ehi, double Eel, /*@out@*/ realnum Yp[], /*@out@*/ realnum Ys[], /*@out@*/ realnum Ehp[], /*@out@*/ realnum Ehs[], long ilo, long ihi) { DEBUG_ENTRY( "Yfunc()" ); if( ihi <= ilo ) return; ASSERT( Ehi >= Elo ); // since both Elo and Ehi are constant, there is no frequency dependence of the results of // y2pa() and y2s() -> we only evaluate one frequency and copy this to the rest of the array. avx_ptr<realnum> y2pr(ilo, ilo+1), y2sec(ilo, ilo+1); avx_ptr<double> Ehiloc(ilo, ilo+1); Ehiloc[ilo] = Ehi; long Zg = gv.bin[nd].chrg(nz).DustZ; y2pa( Elo, Ehiloc.ptr0(), Zg, Ehp, y2pr.ptr0(), ilo, ilo+1 ); if( y2pr[ilo] > 0.f ) { y2s( Elo, Ehiloc.ptr0(), Zg, y2pr.ptr0(), Ehs, y2sec.ptr0(), ilo, ilo+1 ); for( long i=ilo+1; i < ihi; ++i ) { Ehp[i] = Ehp[ilo]; Ehs[i] = Ehs[ilo]; } double eps; pe_type pcase = gv.which_pe[gv.bin[nd].matType]; if( pcase == PE_CAR ) eps = 117./EVRYD; else if( pcase == PE_SIL ) eps = 155./EVRYD; else { fprintf( ioQQQ, " Yfunc: unknown type for PE effect: %d\n" , pcase ); cdEXIT(EXIT_FAILURE); } /* this is Eq. 18 of WDB06 */ /* Eel may be negative near threshold -> set yield to zero */ realnum f3 = max(Eel,0.)/(eps*elec_esc_length(Eel,nd)*gv.bin[nd].eyc); for( long i=ilo; i < ihi; ++i ) { realnum y01cap = min(y01[i],maxval[i]); Yp[i] = y2pr[ilo]*y01cap; Ys[i] = y2sec[ilo]*f3*y01cap; } } else { memset( Yp+ilo, 0, size_t((ihi-ilo)*sizeof(Yp[ilo])) ); memset( Ys+ilo, 0, size_t((ihi-ilo)*sizeof(Ys[ilo])) ); memset( Ehp+ilo, 0, size_t((ihi-ilo)*sizeof(Ehp[ilo])) ); memset( Ehs+ilo, 0, size_t((ihi-ilo)*sizeof(Ehs[ilo])) ); } } /* This calculates the y0 function for band electrons (Sect. 4.1.3/4.1.4 of WDB06) */ STATIC void y0b(size_t nd, long nz, /*@out@*/realnum yzero[], long ilo, long ihi) { DEBUG_ENTRY( "y0b()" ); if( ihi <= ilo ) return; if( gv.lgWD01 ) y0b01( nd, nz, yzero, ilo, ihi ); else { realnum Ethres_low = 20./EVRYD; realnum Ethres_high = 50./EVRYD; long ip20 = rfield.ithreshC(Ethres_low); long ip50 = rfield.ithreshC(Ethres_high); long ipr1a = ilo; //long ipr1b = min(ip20,ihi); long ipr2a = max(ilo,ip20); long ipr2b = min(ip50,ihi); long ipr3a = max(ilo,ip50); long ipr3b = ihi; y0b01( nd, nz, yzero, ipr1a, ipr2b ); avx_ptr<realnum> arg(ipr2a, ipr2b), val(ipr2a, ipr2b), val2(ipr2a, ipr2b); for( int i=ipr2a; i < ipr2b; i++ ) arg[i] = realnum(rfield.anu(i))/Ethres_low; vlog( arg.ptr0(), val.ptr0(), ipr2a, ipr2b ); for( int i=ipr2a; i < ipr2b; i++ ) arg[i] = gv.bin[nd].y0b06[i]/yzero[i]; vlog( arg.ptr0(), val2.ptr0(), ipr2a, ipr2b ); for( int i=ipr2a; i < ipr2b; i++ ) /* constant 1.09135666... is 1./log(50./20.) */ arg[i] = val2[i]*val[i]*1.0913566679f; vexp( arg.ptr0(), val.ptr0(), ipr2a, ipr2b ); for( int i=ipr2a; i < ipr2b; i++ ) yzero[i] *= val[i]; for( int i=ipr3a; i < ipr3b; i++ ) yzero[i] = gv.bin[nd].y0b06[i]; } // result may underflow to zero if anu(ilo) is very close to threshold ASSERT( yzero[ilo] >= 0.f ); for( int i=ilo+1; i < ihi; i++ ) ASSERT( yzero[i] > 0.f ); } /* This calculates the y0 function for band electrons (Eq. 16 of WD01) */ STATIC void y0b01(size_t nd, long nz, /*@out@*/realnum yzero[], long ilo, long ihi) { DEBUG_ENTRY( "y0b01()" ); pe_type pcase = gv.which_pe[gv.bin[nd].matType]; switch( pcase ) { case PE_CAR: /* >>refer grain physics Bakes & Tielens, 1994, ApJ, 427, 822 */ for( int i=ilo; i < ihi; i++ ) { double xv = max((rfield.anu(i)-gv.bin[nd].chrg(nz).ThresSurfVal)/gv.bin[nd].DustWorkFcn,0.); double xv2 = xv*xv; xv = xv2*xv2*xv; yzero[i] = realnum(xv/((1./9.e-3) + (3.7e-2/9.e-3)*xv)); } break; case PE_SIL: /* >>refer grain physics Weingartner & Draine, 2001 */ for( int i=ilo; i < ihi; i++ ) { double xv = max((rfield.anu(i)-gv.bin[nd].chrg(nz).ThresSurfVal)/gv.bin[nd].DustWorkFcn,0.); yzero[i] = realnum(xv/(2.+10.*xv)); } break; default: fprintf( ioQQQ, " y0b01: unknown type for PE effect: %d\n" , pcase ); cdEXIT(EXIT_FAILURE); } } /* This calculates the y0 function for primary/secondary and Auger electrons (Eq. 9 of WDB06) */ STATIC double y0psa(size_t nd, long ns, /* shell number */ long i, /* incident photon energy is anu[i] */ double Eel) /* emitted electron energy */ { DEBUG_ENTRY( "y0psa()" ); ASSERT( i >= gv.bin[nd].sd[ns].ipLo ); /* this is l_e/l_a */ double leola = elec_esc_length(Eel,nd)*gv.bin[nd].inv_att_len[i]; ASSERT( leola > 0. ); /* this is Eq. 9 of WDB06 */ double yzero; if( leola < 1.e4 ) yzero = gv.bin[nd].sd[ns].p[i]*leola*(1. - leola*log(1.+1./leola)); else { double x = 1./leola; yzero = gv.bin[nd].sd[ns].p[i]*(((-1./5.*x+1./4.)*x-1./3.)*x+1./2.); } ASSERT( yzero > 0. ); return yzero; } /* This calculates the y1 function for primary/secondary and Auger electrons (Eq. 6 of WDB06) */ STATIC double y1psa(size_t nd, long i, /* incident photon energy is anu[i] */ double Eel) /* emitted electron energy */ { DEBUG_ENTRY( "y1psa()" ); double bf, beta = gv.bin[nd].AvRadius*gv.bin[nd].inv_att_len[i]; if( beta > 1.e-4 ) bf = pow2(beta) - 2.*beta + 2. - 2.*exp(-beta); else bf = ((1./60.*beta - 1./12.)*beta + 1./3.)*pow3(beta); double af, alpha = beta + gv.bin[nd].AvRadius/elec_esc_length(Eel,nd); if( alpha > 1.e-4 ) af = pow2(alpha) - 2.*alpha + 2. - 2.*exp(-alpha); else af = ((1./60.*alpha - 1./12.)*alpha + 1./3.)*pow3(alpha); double yone = pow2(beta/alpha)*af/bf; ASSERT( yone > 0. ); return yone; } /* This calculates the y2 function for primary and Auger electrons (Eq. 8 of WDB06) */ inline void y2pa(double Elo, const double Ehi[], long Zg, /*@out@*/realnum Ehp[], /*@out@*/realnum y2pr[], long ilo, long ihi) { DEBUG_ENTRY( "y2pa()" ); if( Zg > -1 ) { for( long i=ilo; i < ihi; ++i ) { if( Ehi[i] > 0. ) { double x = Elo/Ehi[i]; Ehp[i] = 0.5f*realnum(Ehi[i]*(1.-2.*x)/(1.-3.*x)); // use Taylor expansion for small arguments to avoid blowing assert y2pr[i] = ( abs(x) > 1e-4 ) ? realnum((1.-3.*x)/pow3(1.-x)) : realnum(1. - (3. + 8.*x)*x*x); ASSERT( Ehp[i] > 0.f && Ehp[i] <= realnum(Ehi[i]) && y2pr[i] > 0.f && y2pr[i] <= 1.f ); } else { Ehp[i] = 0.f; y2pr[i] = 0.f; } } } else { for( long i=ilo; i < ihi; ++i ) { if( Ehi[i] > Elo ) { Ehp[i] = 0.5f*realnum(Elo+Ehi[i]); y2pr[i] = 1.f; ASSERT( Ehp[i] >= realnum(Elo) && Ehp[i] <= realnum(Ehi[i]) ); } else { Ehp[i] = 0.f; y2pr[i] = 0.f; } } } } /* This calculates the y2 function for secondary electrons (Eqs. 20-21 of WDB06) */ inline void y2s(double Elo, const double Ehi[], long Zg, const realnum y2pr[], /*@out@*/realnum Ehs[], /*@out@*/realnum y2sec[], long ilo, long ihi) { DEBUG_ENTRY( "y2s()" ); if( ihi <= ilo ) return; avx_ptr<realnum> arg(ilo, ihi), val(ilo, ihi); avx_ptr<double> arg2(ilo, ihi), val2(ilo, ihi), alpha(ilo, ihi); avx_ptr<bool> lgVecFun(ilo, ihi); memset( arg.data(), 0, size_t((ihi-ilo)*sizeof(arg[ilo])) ); memset( arg2.data(), 0, size_t((ihi-ilo)*sizeof(arg2[ilo])) ); memset( lgVecFun.data(), 0, size_t((ihi-ilo)*sizeof(lgVecFun[ilo])) ); long iveclo = -1, ivechi = -1; double yl = Elo*INV_ETILDE; double sR0 = (1. + yl*yl); double sqR0 = sqrt(sR0); if( Zg > -1 ) { double asinh_yl = asinh(yl); avx_ptr<double> E0(ilo, ihi), N0(ilo, ihi); for( long i=ilo; i < ihi; ++i ) { double yh = Ehi[i]*INV_ETILDE; double x = yh - yl; arg2[i] = 1. + x*x; } vsqrt(arg2.ptr0(), val2.ptr0(), ilo, ihi); for( long i=ilo; i < ihi; ++i ) { if( !gv.lgWD01 && Ehi[i] > 0. && y2pr[i] > 0.f ) { double yh = Ehi[i]*INV_ETILDE; double x = yh - yl; if( x < 0.01 ) { // use series expansions to avoid cancellation error double x2 = x*x, x3 = x2*x, x4 = x3*x, x5 = x4*x; double yh2 = yh*yh, yh3 = yh2*yh, yh4 = yh3*yh, yh5 = yh4*yh; double help1 = 2.*x-yh; double help2 = (6.*x3-15.*yh*x2+12.*yh2*x-3.*yh3)/4.; double help3 = (22.*x5-95.*yh*x4+164.*yh2*x3-141.*yh3*x2+60.*yh4*x-10.*yh5)/16.; N0[i] = yh*(help1 - help2 + help3)/x2; help1 = (3.*x-yh)/3.; help2 = (15.*x3-25.*yh*x2+15.*yh2*x-3.*yh3)/20.; help3 = (1155.*x5-3325.*yh*x4+4305.*yh2*x3-2961.*yh3*x2+1050.*yh4*x-150.*yh5)/ 1680.; E0[i] = ETILDE*yh2*(help1 - help2 + help3)/x2; } else { double sqRh = val2[i]; alpha[i] = sqRh/(sqRh - 1.); if( yh/sqR0 < 0.01 ) { // use series expansions to avoid cancellation error double z = yh*(yh - 2.*yl)/sR0; N0[i] = ((((7./256.*z-5./128.)*z+1./16.)*z-1./8.)*z+1./2.)*z/(sqRh-1.); double yl2 = yl*yl, yl3 = yl2*yl, yl4 = yl3*yl; double help1 = yl/2.; double help2 = (2.*yl2-1.)/3.; double help3 = (6.*yl3-9.*yl)/8.; double help4 = (8.*yl4-24.*yl2+3.)/10.; double h = yh/sR0; E0[i] = -alpha[i]*Ehi[i]*(((help4*h+help3)*h+help2)*h+help1)*h/sqR0; } else { N0[i] = alpha[i]*(1./sqR0 - 1./sqRh); arg[i] = realnum(x); if( iveclo < 0 ) iveclo = i; ivechi = i + 1; lgVecFun[i] = true; E0[i] = alpha[i]*ETILDE*(asinh_yl - yh/sqRh); } } ASSERT( N0[i] > 0. && N0[i] <= 1. ); } } vfast_asinh(arg.ptr0(), val.ptr0(), iveclo, ivechi); for( long i=ilo; i < ihi; ++i ) { if( !gv.lgWD01 && Ehi[i] > 0. && y2pr[i] > 0.f ) { if( lgVecFun[i] ) E0[i] += alpha[i]*ETILDE*val[i]; Ehs[i] = realnum(E0[i]/N0[i]); ASSERT( Ehs[i] > 0.f && Ehs[i] <= realnum(Ehi[i]) ); y2sec[i] = realnum(N0[i]); } else { Ehs[i] = 0.f; y2sec[i] = 0.f; } } } else { for( long i=ilo; i < ihi; ++i ) { double yh = Ehi[i]*INV_ETILDE; double x = yh - yl; arg2[i] = 1. + x*x; } vsqrt(arg2.ptr0(), val2.ptr0(), ilo, ihi); for( long i=ilo; i < ihi; ++i ) { if( !gv.lgWD01 && Ehi[i] > Elo && y2pr[i] > 0.f ) { double yh = Ehi[i]*INV_ETILDE; double x = yh - yl; double x2 = x*x; if( x > 0.025 ) { double sqRh = val2[i]; alpha[i] = sqRh/(sqRh - 1.); arg[i] = realnum(x); if( iveclo < 0 ) iveclo = i; ivechi = i + 1; lgVecFun[i] = true; Ehs[i] = realnum(alpha[i]*ETILDE*(yl - yh/sqRh)); } else { // use series expansion to avoid cancellation error Ehs[i] = realnum(Ehi[i] - (Ehi[i]-Elo)*((-37./840.*x2 + 1./10.)*x2 + 1./3.)); } } } vfast_asinh(arg.ptr0(), val.ptr0(), iveclo, ivechi); for( long i=ilo; i < ihi; ++i ) { if( !gv.lgWD01 && Ehi[i] > Elo && y2pr[i] > 0.f ) { if( lgVecFun[i] ) Ehs[i] += realnum(alpha[i]*ETILDE)*val[i]; ASSERT( Ehs[i] >= realnum(Elo) && Ehs[i] <= realnum(Ehi[i]) ); y2sec[i] = 1.f; } else { Ehs[i] = 0.f; y2sec[i] = 0.f; } } } } STATIC void UpdateRecomZ0(size_t nd, long nz) { DEBUG_ENTRY( "UpdateRecomZ0()" ); long Zg = gv.bin[nd].chrg(nz).DustZ; double d[5], phi_s_up[LIMELM+1], phi_s_dn[2]; phi_s_up[0] = gv.bin[nd].chrg(nz).ThresSurf; for( long i=1; i <= LIMELM; i++ ) GetPotValues(nd,Zg+i,&d[0],&d[1],&phi_s_up[i],&d[2],&d[3],&d[4],INCL_TUNNEL); phi_s_dn[0] = gv.bin[nd].chrg(nz).ThresSurfInc; GetPotValues(nd,Zg-2,&d[0],&d[1],&phi_s_dn[1],&d[2],&d[3],&d[4],NO_TUNNEL); /* >>chng 01 may 09, use GrainIonColl which properly tracks step-by-step charge changes */ for( long nelem=0; nelem < LIMELM; nelem++ ) { if( dense.lgElmtOn[nelem] ) { for( long ion=0; ion <= nelem+1; ion++ ) { GrainIonColl(nd,nz,nelem,ion,phi_s_up,phi_s_dn, &gv.bin[nd].chrg(nz).RecomZ0[nelem][ion], &gv.bin[nd].chrg(nz).RecomEn[nelem][ion], &gv.bin[nd].chrg(nz).ChemEn[nelem][ion]); } } } return; } STATIC void GetPotValues(size_t nd, long Zg, /*@out@*/ double *ThresInf, /*@out@*/ double *ThresInfVal, /*@out@*/ double *ThresSurf, /*@out@*/ double *ThresSurfVal, /*@out@*/ double *PotSurf, /*@out@*/ double *Emin, bool lgUseTunnelCorr) { DEBUG_ENTRY( "GetPotValues()" ); /* >>chng 01 may 07, this routine now completely supports the hybrid grain charge model, * the change for this routine is that now it is only fed integral charge states; calculation * of IP has also been changed in accordance with Weingartner & Draine, 2001, PvH */ double dZg = (double)Zg; /* this is average grain potential in Rydberg */ double dstpot = chrg2pot(dZg,nd); /* >>chng 01 mar 20, include O(a^-2) correction terms in ionization potential */ /* these are correction terms for the ionization potential that are * important for small grains. See Weingartner & Draine, 2001, Eq. 2 */ double IP_v = gv.bin[nd].DustWorkFcn + dstpot - 0.5*one_elec(nd) + (dZg+2.)*AC0/gv.bin[nd].AvRadius*one_elec(nd); /* >>chng 01 mar 01, use new expresssion for ThresInfVal, ThresSurfVal following the discussion * with Joe Weingartner. Also include the Schottky effect (see * >>refer grain physics Spitzer, 1948, ApJ, 107, 6, * >>refer grain physics Draine & Sutin, 1987, ApJ, 320, 803), PvH */ if( Zg <= -1 ) { pot_type pcase = gv.which_pot[gv.bin[nd].matType]; double IP; IP = gv.bin[nd].DustWorkFcn - gv.bin[nd].BandGap + dstpot - 0.5*one_elec(nd); switch( pcase ) { case POT_CAR: IP -= AC1G/(gv.bin[nd].AvRadius+AC2G)*one_elec(nd); break; case POT_SIL: /* do nothing */ break; default: fprintf( ioQQQ, " GetPotValues detected unknown type for ionization pot: %d\n" , pcase ); cdEXIT(EXIT_FAILURE); } /* prevent valence electron from becoming less bound than attached electron; this * can happen for very negative, large graphitic grains and is not physical, PvH */ IP_v = MAX2(IP,IP_v); if( Zg < -1 ) { /* >>chng 01 apr 20, use improved expression for tunneling effect, PvH */ double help = fabs(dZg+1); /* this is the barrier height solely due to the Schottky effect */ *Emin = -ThetaNu(help)*one_elec(nd); if( lgUseTunnelCorr ) { /* this is the barrier height corrected for tunneling effects */ *Emin *= 1. - 2.124e-4/(pow(gv.bin[nd].AvRadius,(realnum)0.45)*pow(help,0.26)); } } else { *Emin = 0.; } *ThresInf = IP - *Emin; *ThresInfVal = IP_v - *Emin; *ThresSurf = *ThresInf; *ThresSurfVal = *ThresInfVal; *PotSurf = *Emin; } else { *ThresInf = IP_v; *ThresInfVal = IP_v; *ThresSurf = *ThresInf - dstpot; *ThresSurfVal = *ThresInfVal - dstpot; *PotSurf = dstpot; *Emin = 0.; } return; } /* given grain nd in charge state nz, and incoming ion (nelem,ion), * detemine outgoing ion (nelem,Z0) and chemical energy ChEn released * ChemEn is net contribution of ion recombination to grain heating */ STATIC void GrainIonColl(size_t nd, long int nz, long int nelem, long int ion, const double phi_s_up[], /* phi_s_up[LIMELM+1] */ const double phi_s_dn[], /* phi_s_dn[2] */ /*@out@*/long *Z0, /*@out@*/realnum *ChEn, /*@out@*/realnum *ChemEn) { DEBUG_ENTRY( "GrainIonColl()" ); long save = ion; if( ion > 0 && rfield.anu(Heavy.ipHeavy[nelem][ion-1]-1) > (realnum)phi_s_up[0] ) { /* ion will get electron(s) */ *ChEn = 0.f; *ChemEn = 0.f; long Zg = gv.bin[nd].chrg(nz).DustZ; double phi_s = phi_s_up[0]; do { *ChEn += rfield.anu(Heavy.ipHeavy[nelem][ion-1]-1) - (realnum)phi_s; *ChemEn += rfield.anu(Heavy.ipHeavy[nelem][ion-1]-1); /* this is a correction for the imperfections in the n-charge state model: * since the transfer gets modeled as n single-electron transfers, instead of one * n-electron transfer, a correction for the difference in binding energy is needed */ *ChemEn -= (realnum)(phi_s - phi_s_up[0]); --ion; ++Zg; phi_s = phi_s_up[save-ion]; } while( ion > 0 && rfield.anu(Heavy.ipHeavy[nelem][ion-1]-1) > (realnum)phi_s ); *Z0 = ion; } else if( ion <= nelem && gv.bin[nd].chrg(nz).DustZ > gv.bin[nd].LowestZg && rfield.anu(Heavy.ipHeavy[nelem][ion]-1) < (realnum)phi_s_dn[0] ) { /* grain will get electron(s) */ *ChEn = 0.f; *ChemEn = 0.f; long Zg = gv.bin[nd].chrg(nz).DustZ; double phi_s = phi_s_dn[0]; do { *ChEn += (realnum)phi_s - rfield.anu(Heavy.ipHeavy[nelem][ion]-1); *ChemEn -= rfield.anu(Heavy.ipHeavy[nelem][ion]-1); /* this is a correction for the imperfections in the n-charge state model: * since the transfer gets modeled as n single-electron transfers, instead of one * n-electron transfer, a correction for the difference in binding energy is needed */ *ChemEn += (realnum)(phi_s - phi_s_dn[0]); ++ion; --Zg; double d[5]; if( ion-save < 2 ) phi_s = phi_s_dn[ion-save]; else GetPotValues(nd,Zg-1,&d[0],&d[1],&phi_s,&d[2],&d[3],&d[4],NO_TUNNEL); } while( ion <= nelem && Zg > gv.bin[nd].LowestZg && rfield.anu(Heavy.ipHeavy[nelem][ion]-1) < (realnum)phi_s ); *Z0 = ion; } else { /* nothing happens */ *ChEn = 0.f; *ChemEn = 0.f; *Z0 = ion; } /* printf(" GrainIonColl: nelem %ld ion %ld -> %ld, ChEn %.6f\n",nelem,save,*Z0,*ChEn); */ return; } /* initialize grain-ion charge transfer rates on grain species nd */ STATIC void GrainChrgTransferRates(long nd) { DEBUG_ENTRY( "GrainChrgTransferRates()" ); double fac0 = STICK_ION*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3; # ifndef IGNORE_GRAIN_ION_COLLISIONS for( long nz=0; nz < gv.bin[nd].nChrg; nz++ ) { ChargeBin& gptr = gv.bin[nd].chrg(nz); double fac1 = gptr.FracPop*fac0; if( fac1 == 0. ) continue; for( long ion=0; ion <= LIMELM; ion++ ) { /* >>chng 00 jul 19, replace classical results with results including image potential * to correct for polarization of the grain as charged particle approaches. */ double eta, xi; GrainScreen(ion,nd,nz,&eta,&xi); double fac2 = eta*fac1; if( fac2 == 0. ) continue; for( long nelem=MAX2(0,ion-1); nelem < LIMELM; nelem++ ) { if( dense.lgElmtOn[nelem] && ion != gptr.RecomZ0[nelem][ion] ) { gv.GrainChTrRate[nelem][ion][gptr.RecomZ0[nelem][ion]] += (realnum)(fac2*GetAveVelocity( dense.AtomicWeight[nelem] )*atmdat.lgCTOn); } } } } # endif return; } /* this routine updates all grain quantities that depend on radius, * except gv.dstab and gv.dstsc which are updated in GrainUpdateRadius2() */ STATIC void GrainUpdateRadius1() { DEBUG_ENTRY( "GrainUpdateRadius1()" ); for( long nelem=0; nelem < LIMELM; nelem++ ) { gv.elmSumAbund[nelem] = 0.f; } /* grain abundance may be a function of depth */ for( size_t nd=0; nd < gv.bin.size(); nd++ ) { gv.bin[nd].GrnDpth = (realnum)GrnStdDpth(nd); gv.bin[nd].dstAbund = (realnum)(gv.bin[nd].dstfactor*gv.GrainMetal*gv.bin[nd].GrnDpth); ASSERT( gv.bin[nd].dstAbund > 0.f ); /* grain unit conversion, <unit>/H (default depl) -> <unit>/cm^3 (actual depl) */ gv.bin[nd].cnv_H_pCM3 = dense.gas_phase[ipHYDROGEN]*gv.bin[nd].dstAbund; gv.bin[nd].cnv_CM3_pH = 1./gv.bin[nd].cnv_H_pCM3; /* grain unit conversion, <unit>/cm^3 (actual depl) -> <unit>/grain */ gv.bin[nd].cnv_CM3_pGR = gv.bin[nd].cnv_H_pGR/gv.bin[nd].cnv_H_pCM3; gv.bin[nd].cnv_GR_pCM3 = 1./gv.bin[nd].cnv_CM3_pGR; /* >>chng 01 dec 05, calculate the number density of each element locked in grains, * summed over all grain bins. this number uses the actual depletion of the grains * and is already multiplied with hden, units cm^-3. */ for( long nelem=0; nelem < LIMELM; nelem++ ) { gv.elmSumAbund[nelem] += gv.bin[nd].elmAbund[nelem]*(realnum)gv.bin[nd].cnv_H_pCM3; } } return; } /* this routine adds all the grain opacities in gv.dstab and gv.dstsc, this could not be * done in GrainUpdateRadius1 since charge and FracPop must be converged first */ STATIC void GrainUpdateRadius2() { DEBUG_ENTRY( "GrainUpdateRadius2()" ); memset( get_ptr(gv.dstab), 0, size_t(rfield.nflux_with_check*sizeof(gv.dstab[0])) ); memset( get_ptr(gv.dstsc), 0, size_t(rfield.nflux_with_check*sizeof(gv.dstsc[0])) ); /* >>chng 06 oct 05 rjrw, reorder loops */ /* >>chng 11 dec 12 reorder loops so they can be vectorized, PvH */ for( size_t nd=0; nd < gv.bin.size(); nd++ ) { double dstAbund = gv.bin[nd].dstAbund; /* >>chng 01 mar 26, from nupper to nflux */ for( long i=0; i < rfield.nflux; i++ ) { /* these are total absorption and scattering cross sections, * the latter should contain the asymmetry factor (1-g) */ /* this is effective area per proton, scaled by depletion * dareff(nd) = darea(nd) * dstAbund(nd) */ /* grain abundance may be a function of depth */ /* >>chng 02 dec 30, separated scattering cross section and asymmetry factor, PvH */ gv.dstab[i] += gv.bin[nd].dstab1[i]*dstAbund; } for( long i=0; i < rfield.nflux; i++ ) { gv.dstsc[i] += gv.bin[nd].pure_sc1[i]*gv.bin[nd].asym[i]*dstAbund; } for( long nz=0; nz < gv.bin[nd].nChrg; nz++ ) { ChargeBin& gptr = gv.bin[nd].chrg(nz); if( gptr.DustZ <= -1 ) { double FracAbund = gptr.FracPop*dstAbund; for( long i=gptr.ipThresInf; i < rfield.nflux; i++ ) gv.dstab[i] += FracAbund*gptr.cs_pdt[i]; } } } for( long i=0; i < rfield.nflux; i++ ) { /* this must be positive, zero in case of uncontrolled underflow */ ASSERT( gv.dstab[i] > 0. && gv.dstsc[i] > 0. ); } return; } /* GrainTemperature computes grains temperature, and gas cooling */ STATIC void GrainTemperature(size_t nd, /*@out@*/ realnum *dccool, /*@out@*/ double *hcon, /*@out@*/ double *hots, /*@out@*/ double *hla) { DEBUG_ENTRY( "GrainTemperature()" ); /* sanity checks */ ASSERT( nd < gv.bin.size() ); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " GrainTemperature starts for grain %s\n", gv.bin[nd].chDstLab ); } /* >>chng 01 may 07, this routine now completely supports the hybrid grain * charge model, and the average charge state is not used anywhere anymore, PvH */ /* direct heating by incident continuum (all energies) */ *hcon = 0.; /* heating by diffuse ots fields */ *hots = 0.; /* heating by Ly alpha alone, for output only, is already included in hots */ *hla = 0.; long ipLya = iso_sp[ipH_LIKE][ipHYDROGEN].trans(ipH2p,ipH1s).ipCont() - 1; /* integrate over ionizing continuum; energy goes to dust and gas * GasHeatPhotoEl is what heats the gas */ gv.bin[nd].GasHeatPhotoEl = 0.; gv.bin[nd].GrainCoolTherm = 0.; gv.bin[nd].thermionic = 0.; realnum dcheat = 0.f; *dccool = 0.f; gv.bin[nd].BolFlux = 0.; /* >>chng 04 jan 25, moved initialization of phiTilde to qheat_init(), PvH */ for( long nz=0; nz < gv.bin[nd].nChrg; nz++ ) { ChargeBin& gptr = gv.bin[nd].chrg(nz); /* >>chng 04 may 31, introduced lgReEvaluate2 to save time when iterating Tdust, PvH */ bool lgReEvaluate1 = gptr.hcon1 < 0.; bool lgReEvaluate2 = gptr.hots1 < 0.; long ip0 = 0; long ip1 = min(gptr.ipThresInf,rfield.nPositive); long ip2 = rfield.nPositive; double hcon1, hots1, pe1, bolflux1, hla1; if( lgReEvaluate1 ) { hcon1 = reduce_ab( get_ptr(gv.bin[nd].dstab1_x_anu), get_ptr(rfield.flux[0]), ip0, ip1 ) + reduce_ab( gptr.fac1.ptr0(), get_ptr(rfield.flux[0]), ip1, ip2 ); gptr.hcon1 = hcon1; } else { hcon1 = gptr.hcon1; } if( lgReEvaluate2 ) { hots1 = reduce_ab( get_ptr(gv.bin[nd].dstab1_x_anu), get_ptr(rfield.SummedDif), ip0, ip1 ) + reduce_ab( gptr.fac1.ptr0(), get_ptr(rfield.SummedDif), ip1, ip2 ); # ifdef WD_TEST2 pe1 = reduce_ab( gptr.fac2.ptr0(), get_ptr(rfield.flux[0]), ip1, ip2 ); # else pe1 = reduce_ab( gptr.fac2.ptr0(), get_ptr(rfield.SummedCon), ip1, ip2 ); # endif # ifndef NDEBUG bolflux1 = reduce_ab( get_ptr(gv.bin[nd].dstab1_x_anu), get_ptr(rfield.SummedCon), ip0, ip2 ); if( gptr.DustZ <= -1 ) bolflux1 += reduce_abc( gptr.cs_pdt.ptr0(), rfield.anuptr(), get_ptr(rfield.SummedCon), ip1, ip2 ); # else bolflux1 = 0.; # endif gptr.hots1 = hots1; gptr.pe1 = pe1; gptr.bolflux1 = bolflux1; } else { hots1 = gptr.hots1; pe1 = gptr.pe1; bolflux1 = gptr.bolflux1; } /* heating by Ly A on dust in this zone, * only used for printout; Ly-a is already in OTS fields */ /* >>chng 00 apr 18, moved calculation of hla, by PvH */ /* >>chng 04 feb 01, moved calculation of hla1 outside loop for optimization, PvH */ if( ipLya < MIN2(gptr.ipThresInf,rfield.nPositive) ) { hla1 = rfield.otslin[ipLya]*gv.bin[nd].dstab1_x_anu[ipLya]; } else if( ipLya < rfield.nPositive ) { /* >>chng 00 apr 18, include photo-electric effect, by PvH */ hla1 = rfield.otslin[ipLya]*gptr.fac1[ipLya]; } else { hla1 = 0.; } ASSERT( hcon1 >= 0. && hots1 >= 0. && hla1 >= 0. && bolflux1 >= 0. && pe1 >= 0. ); *hcon += gptr.FracPop*hcon1; *hots += gptr.FracPop*hots1; *hla += gptr.FracPop*hla1; gv.bin[nd].BolFlux += gptr.FracPop*bolflux1; if( gv.lgDHetOn ) gv.bin[nd].GasHeatPhotoEl += gptr.FracPop*pe1; # ifndef NDEBUG if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " Zg %ld bolflux: %.4e\n", gptr.DustZ, gptr.FracPop*bolflux1*EN1RYD*gv.bin[nd].cnv_H_pCM3 ); } # endif /* add in thermionic emissions (thermal evaporation of electrons), it gives a cooling * term for the grain. thermionic emissions will not be treated separately in quantum * heating since they are only important when grains are heated to near-sublimation * temperatures; under those conditions quantum heating effects will never be important. * in order to maintain energy balance they will be added to the ion contribution though */ /* ThermRate is normalized per cm^2 of grain surface area, scales with total grain area */ double rate = gptr.FracPop*gptr.ThermRate*gv.bin[nd].IntArea*gv.bin[nd].cnv_H_pCM3; /* >>chng 01 mar 02, PotSurf[nz] term was incorrectly taken into account, PvH */ double EhatThermionic = 2.*BOLTZMANN*gv.bin[nd].tedust + MAX2(gptr.PotSurf*EN1RYD,0.); gv.bin[nd].GrainCoolTherm += rate * (EhatThermionic + gptr.ThresSurf*EN1RYD); gv.bin[nd].thermionic += rate * (EhatThermionic - gptr.PotSurf*EN1RYD); } /* norm is used to convert all heating rates to erg/cm^3/s */ double norm = EN1RYD*gv.bin[nd].cnv_H_pCM3; /* hcon is radiative heating by incident radiation field */ *hcon *= norm; /* hots is total heating of the grain by diffuse fields */ *hots *= norm; /* heating by Ly alpha alone, for output only, is already included in hots */ *hla *= norm; gv.bin[nd].BolFlux *= norm; /* heating by thermal collisions with gas does work * DCHEAT is grain collisional heating by gas * DCCOOL is gas cooling due to collisions with grains * they are different since grain surface recombinations * heat the grains, but do not cool the gas ! */ /* >>chng 03 nov 06, moved call after renorm of BolFlux, so that GrainCollHeating can look at it, PvH */ GrainCollHeating(nd,&dcheat,dccool); /* GasHeatPhotoEl is what heats the gas */ gv.bin[nd].GasHeatPhotoEl *= norm; if( gv.lgBakesPAH_heat ) { /* this is a dirty hack to get BT94 PE heating rate * for PAH's included, for Lorentz Center 2004 PDR meeting, PvH */ /*>>>refer PAH heating Bakes, E.L.O., & Tielens, A.G.G.M. 1994, ApJ, 427, 822 */ /* >>chng 05 aug 12, change from +=, which added additional heating to what exists already, * to simply = to set the heat, this equation gives total heating */ gv.bin[nd].GasHeatPhotoEl = 1.e-24*hmi.UV_Cont_rel2_Habing_TH85_depth* dense.gas_phase[ipHYDROGEN]*(4.87e-2/(1.0+4e-3*pow((hmi.UV_Cont_rel2_Habing_TH85_depth* /*>>chng 06 jul 21, use phycon.sqrte in next two lines */ phycon.sqrte/dense.eden),0.73)) + 3.65e-2*pow(phycon.te/1.e4,0.7)/ (1.+2.e-4*(hmi.UV_Cont_rel2_Habing_TH85_depth*phycon.sqrte/dense.eden)))/gv.bin.size(); } /* >>chng 06 jun 01, add optional scale factor, set with command * set grains heat, to rescale PE heating as per Allers et al. 2005 */ gv.bin[nd].GasHeatPhotoEl *= gv.GrainHeatScaleFactor; /* find power absorbed by dust and resulting temperature * * hcon is heating from incident continuum (all energies) * hots is heating from ots continua and lines * dcheat is net grain collisional and chemical heating by * particle collisions and recombinations * GrainCoolTherm is grain cooling by thermionic emissions * * GrainHeat is net heating of this grain type, * to be balanced by radiative cooling */ gv.bin[nd].GrainHeat = *hcon + *hots + dcheat - gv.bin[nd].GrainCoolTherm; /* remember collisional heating for this grain species */ gv.bin[nd].GrainHeatColl = dcheat; /* >>chng 04 may 31, replace ASSERT of GrainHeat > 0. with if-statement and let * GrainChargeTemp sort out the consquences of GrainHeat becoming negative, PvH */ /* in case where the thermionic rates become very large, * or collisional cooling dominates, this may become negative */ if( gv.bin[nd].GrainHeat > 0. ) { bool lgOutOfBounds; /* now find temperature, GrainHeat is sum of total heating of grain * >>chng 97 jul 17, divide by abundance here */ double y, x = log(MAX2(DBL_MIN,gv.bin[nd].GrainHeat*gv.bin[nd].cnv_CM3_pH)); /* >>chng 96 apr 27, as per Peter van Hoof comment */ splint_safe(gv.bin[nd].dstems,gv.dsttmp,gv.bin[nd].dstslp,NDEMS,x,&y,&lgOutOfBounds); gv.bin[nd].tedust = (realnum)exp(y); } else { gv.bin[nd].GrainHeat = -1.; gv.bin[nd].tedust = -1.; } if( thermal.ConstGrainTemp > 0. ) { bool lgOutOfBounds; /* use temperature set with constant grain temperature command */ gv.bin[nd].tedust = thermal.ConstGrainTemp; /* >>chng 04 jun 01, make sure GrainHeat is consistent with value of tedust, PvH */ double y, x = log(gv.bin[nd].tedust); splint_safe(gv.dsttmp,gv.bin[nd].dstems,gv.bin[nd].dstslp2,NDEMS,x,&y,&lgOutOfBounds); gv.bin[nd].GrainHeat = exp(y)*gv.bin[nd].cnv_H_pCM3; } /* save for later possible printout */ gv.bin[nd].TeGrainMax = (realnum)MAX2(gv.bin[nd].TeGrainMax,gv.bin[nd].tedust); if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " >GrainTemperature finds %s Tdst %.5e hcon %.4e ", gv.bin[nd].chDstLab, gv.bin[nd].tedust, *hcon); fprintf( ioQQQ, "hots %.4e dcheat %.4e GrainCoolTherm %.4e\n", *hots, dcheat, gv.bin[nd].GrainCoolTherm ); } return; } /* helper routine for initializing quantities related to the photo-electric effect */ STATIC void PE_init(size_t nd, long nz, long i, /*@out@*/ double *cs1, /*@out@*/ double *cs2, /*@out@*/ double *cs_tot, /*@out@*/ double *cool1, /*@out@*/ double *cool2, /*@out@*/ double *ehat1, /*@out@*/ double *ehat2) { DEBUG_ENTRY( "PE_init()" ); ChargeBin& gptr = gv.bin[nd].chrg(nz); long ipLo1 = gptr.ipThresInfVal; long ipLo2 = gptr.ipThresInf; /* sanity checks */ ASSERT( nd < gv.bin.size() ); ASSERT( nz >= 0 && nz < gv.bin[nd].nChrg ); ASSERT( i >= 0 && i < rfield.nPositive ); /** \todo xray - add fluoresence in energy balance */ /* contribution from valence band */ if( i >= ipLo1 ) { /* effective cross section for photo-ejection */ *cs1 = gv.bin[nd].dstab1[i]*gptr.yhat[i]; /* >>chng 00 jul 17, use description of Weingartner & Draine, 2001 */ /* ehat1 is the average energy of the escaping electron at infinity */ *ehat1 = gptr.ehat[i]; /* >>chng 01 nov 27, changed de-excitation energy to conserve energy, * this branch treats valence band ionizations, but for negative grains an * electron from the conduction band will de-excite into the hole in the * valence band, reducing the amount of potential energy lost. It is assumed * that no photons are ejected in the process. PvH */ /* >>chng 06 mar 19, reorganized this routine in the wake of the introduction * of the WDB06 X-ray physics. The basic functionality is still the same, but * the meaning is not. A single X-ray photon can eject multiple electrons from * either the conduction band, valence band or an inner shell. In the WDB06 * approximation all these electrons are assumed to be ejected from a grain * with the same charge. After the primary ejection, Auger cascades will fill * up any inner shell holes, so energetically it is as if all these electrons * come from the outermost band (either conduction or valence band, depending * on the grain charge). Recombination will also be into the outermost band * so that way energy conservation is assured. It is assumed that these Auger * cascades are so fast that they can be treated as a single event as far as * quantum heating is concerned. */ /* cool1 is the amount by which photo-ejection cools the grain */ if( gptr.DustZ <= -1 ) *cool1 = gptr.ThresSurf + gptr.PotSurf + *ehat1; else *cool1 = gptr.ThresSurfVal + gptr.PotSurf + *ehat1; ASSERT( *ehat1 >= 0. && *cool1 >= gptr.PotSurf ); } else { *cs1 = 0.; *ehat1 = 0.; *cool1 = 0.; } /* contribution from conduction band */ if( gptr.DustZ <= -1 && i >= ipLo2 ) { /* effective cross section for photo-detechment */ *cs2 = gptr.cs_pdt[i]; /* ehat2 is the average energy of the escaping electron at infinity */ *ehat2 = rfield.anu(i) - gptr.ThresSurf - gptr.PotSurf; /* cool2 is the amount by which photo-detechment cools the grain */ *cool2 = rfield.anu(i); ASSERT( *ehat2 >= 0. && *cool2 > 0. ); } else { *cs2 = 0.; *ehat2 = 0.; *cool2 = 0.; } *cs_tot = gv.bin[nd].dstab1[i] + *cs2; return; } /* GrainCollHeating compute grains collisional heating cooling */ STATIC void GrainCollHeating(size_t nd, /*@out@*/ realnum *dcheat, /*@out@*/ realnum *dccool) { long int ion, nelem, nz; H2_type ipH2; double Accommodation, CollisionRateElectr, /* rate electrons strike grains */ CollisionRateMol, /* rate molecules strike grains */ CollisionRateIon, /* rate ions strike grains */ CoolTot, CoolBounce, CoolEmitted, CoolElectrons, CoolMolecules, CoolPotential, CoolPotentialGas, eta, HeatTot, HeatBounce, HeatCollisions, HeatElectrons, HeatIons, HeatMolecules, HeatRecombination, /* sum of abundances of ions times velocity times ionization potential times eta */ HeatChem, HeatCor, Stick, ve, WeightMol, xi; /* energy deposited into grain by formation of a single H2 molecule, in eV, * >>refer grain physics Takahashi J., Uehara H., 2001, ApJ, 561, 843 */ const double H2_FORMATION_GRAIN_HEATING[H2_TOP] = { 0.20, 0.4, 1.72 }; DEBUG_ENTRY( "GrainCollHeating()" ); /* >>chng 01 may 07, this routine now completely supports the hybrid grain * charge model, and the average charge state is not used anywhere anymore, PvH */ /* this subroutine evaluates the gas heating-cooling rate * (erg cm^-3 s^-1) due to grain gas collisions. * the net effect can be positive or negative, * depending on whether the grains or gas are hotter * the physics is described in * >>refer grain physics Baldwin, Ferland, Martin et al., 1991, ApJ 374, 580 */ HeatTot = 0.; CoolTot = 0.; HeatIons = 0.; gv.bin[nd].ChemEn = 0.; /* loop over the charge states */ for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { ChargeBin& gptr = gv.bin[nd].chrg(nz); /* HEAT1 will be rate collisions heat the grain * COOL1 will be rate collisions cool the gas kinetics */ double Heat1 = 0.; double Cool1 = 0.; double ChemEn1 = 0.; /* ============================================================================= */ /* heating/cooling due to neutrals and positive ions */ /* loop over all stages of ionization */ for( ion=0; ion <= LIMELM; ion++ ) { /* this is heating of grains due to recombination energy of species, * and assumes that every ion is fully neutralized upon striking the grain surface. * all radiation produced in the recombination process is absorbed within the grain * * ion=0 are neutrals, ion=1 are single ions, etc * each population is weighted by the AVERAGE velocity * */ CollisionRateIon = 0.; CoolPotential = 0.; CoolPotentialGas = 0.; HeatRecombination = 0.; HeatChem = 0.; /* >>chng 00 jul 19, replace classical results with results including image potential * to correct for polarization of the grain as charged particle approaches. */ GrainScreen(ion,nd,nz,&eta,&xi); for( nelem=MAX2(0,ion-1); nelem < LIMELM; nelem++ ) { if( dense.lgElmtOn[nelem] && dense.xIonDense[nelem][ion] > 0. ) { double CollisionRateOne; /* >>chng 00 apr 05, use correct accomodation coefficient, by PvH * the coefficient is defined at the end of appendix A.10 of BFM * assume ion sticking prob is unity */ #if defined( IGNORE_GRAIN_ION_COLLISIONS ) Stick = 0.; #elif defined( WD_TEST2 ) Stick = ( ion == gptr.RecomZ0[nelem][ion] ) ? 0. : STICK_ION; #else Stick = ( ion == gptr.RecomZ0[nelem][ion] ) ? gv.bin[nd].AccomCoef[nelem] : STICK_ION; #endif /* this is rate with which charged ion strikes grain */ /* >>chng 00 may 02, this had left 2./SQRTPI off */ /* >>chng 00 may 05, use average speed instead of 2./SQRTPI*Doppler, PvH */ CollisionRateOne = Stick*dense.xIonDense[nelem][ion]* GetAveVelocity( dense.AtomicWeight[nelem] ); CollisionRateIon += CollisionRateOne; /* >>chng 01 nov 26, use PotSurfInc when appropriate: * the values for the surface potential used here make it * consistent with the rest of the code and preserve energy. * NOTE: For incoming particles one should use PotSurfInc with * Schottky effect for positive ion, for outgoing particles * one should use PotSurf for Zg+ion-Z_0-1 (-1 because PotSurf * assumes electron going out), these corrections are small * and will be neglected for now, PvH */ if( ion >= gptr.RecomZ0[nelem][ion] ) { CoolPotential += CollisionRateOne * (double)ion * gptr.PotSurf; CoolPotentialGas += CollisionRateOne * (double)gptr.RecomZ0[nelem][ion] * gptr.PotSurf; } else { CoolPotential += CollisionRateOne * (double)ion * gptr.PotSurfInc; CoolPotentialGas += CollisionRateOne * (double)gptr.RecomZ0[nelem][ion] * gptr.PotSurfInc; } /* this is sum of all energy liberated as ion recombines to Z0 in grain */ /* >>chng 00 jul 05, subtract energy needed to get * electron out of grain potential well, PvH */ /* >>chng 01 may 09, chemical energy now calculated in GrainIonColl, PvH */ HeatRecombination += CollisionRateOne * gptr.RecomEn[nelem][ion]; HeatChem += CollisionRateOne * gptr.ChemEn[nelem][ion]; } } /* >>chng 00 may 01, Boltzmann factor had multiplied all of factor instead * of only first and last term. pvh */ /* equation 29 from Balwin et al 91 */ /* this is direct collision rate, 2kT * xi, first term in eq 29 */ HeatCollisions = CollisionRateIon * 2.*BOLTZMANN*phycon.te*xi; /* this is change in energy due to charge acceleration within grain's potential * this is exactly balanced by deceleration of incoming electrons and accelaration * of outgoing photo-electrons and thermionic emissions; all these terms should * add up to zero (total charge of grain should remain constant) */ CoolPotential *= eta*EN1RYD; CoolPotentialGas *= eta*EN1RYD; /* this is recombination energy released within grain */ HeatRecombination *= eta*EN1RYD; HeatChem *= eta*EN1RYD; /* energy carried away by neutrals after recombination, so a cooling term */ CoolEmitted = CollisionRateIon * 2.*BOLTZMANN*gv.bin[nd].tedust*eta; /* total GraC 0 in the emission line output */ Heat1 += HeatCollisions - CoolPotential + HeatRecombination - CoolEmitted; /* rate kinetic energy lost from gas - gas cooling - eq 32 in BFM */ /* this GrGC 0 in the main output */ /* >>chng 00 may 05, reversed sign of gas cooling contribution */ Cool1 += HeatCollisions - CoolEmitted - CoolPotentialGas; ChemEn1 += HeatChem; } /* remember grain heating by ion collisions for quantum heating treatment */ HeatIons += gptr.FracPop*Heat1; if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " Zg %ld ions heat/cool: %.4e %.4e\n", gptr.DustZ, gptr.FracPop*Heat1*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3, gptr.FracPop*Cool1*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3 ); } /* ============================================================================= */ /* heating/cooling due to electrons */ ion = -1; Stick = ( gptr.DustZ <= -1 ) ? gv.bin[nd].StickElecNeg : gv.bin[nd].StickElecPos; /* VE is mean (not RMS) electron velocity */ /*ve = TePowers.sqrte*6.2124e5;*/ ve = sqrt(8.*BOLTZMANN/PI/ELECTRON_MASS*phycon.te); /* electron arrival rate - eqn 29 again */ CollisionRateElectr = Stick*dense.eden*ve; /* >>chng 00 jul 19, replace classical results with results including image potential * to correct for polarization of the grain as charged particle approaches. */ GrainScreen(ion,nd,nz,&eta,&xi); if( gptr.DustZ > gv.bin[nd].LowestZg ) { HeatCollisions = CollisionRateElectr*2.*BOLTZMANN*phycon.te*xi; /* this is change in energy due to charge acceleration within grain's potential * this term (perhaps) adds up to zero when summed over all charged particles */ CoolPotential = CollisionRateElectr * (double)ion*gptr.PotSurfInc*eta*EN1RYD; /* >>chng 00 jul 05, this is term for energy released due to recombination, PvH */ HeatRecombination = CollisionRateElectr * gptr.ThresSurfInc*eta*EN1RYD; HeatBounce = 0.; CoolBounce = 0.; } else { HeatCollisions = 0.; CoolPotential = 0.; HeatRecombination = 0.; /* >>chng 00 jul 05, add in terms for electrons that bounce off grain, PvH */ /* >>chng 01 mar 09, remove these terms, their contribution is negligible, and replace * them with similar terms that describe electrons that are captured by grains at Z_min, * these electrons are not in a bound state and the grain will quickly autoionize, PvH */ HeatBounce = CollisionRateElectr * 2.*BOLTZMANN*phycon.te*xi; /* >>chng 01 mar 14, replace (2kT_g - phi_g) term with -EA; for autoionizing states EA is * usually higher than phi_g, so more energy is released back into the electron gas, PvH */ CoolBounce = CollisionRateElectr * (-gptr.ThresSurfInc-gptr.PotSurfInc)*EN1RYD*eta; CoolBounce = MAX2(CoolBounce,0.); } /* >>chng 00 may 02, CoolPotential had not been included */ /* >>chng 00 jul 05, HeatRecombination had not been included */ HeatElectrons = HeatCollisions-CoolPotential+HeatRecombination+HeatBounce-CoolBounce; Heat1 += HeatElectrons; CoolElectrons = HeatCollisions+HeatBounce-CoolBounce; Cool1 += CoolElectrons; if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " Zg %ld electrons heat/cool: %.4e %.4e\n", gptr.DustZ, gptr.FracPop*HeatElectrons*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3, gptr.FracPop*CoolElectrons*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3 ); } /* add quantum heating due to recombination of electrons, subtract thermionic cooling */ /* calculate net heating rate in erg/H/s at standard depl * include contributions for recombining electrons, autoionizing electrons * and subtract thermionic emissions here since it is inverse process * * NB - in extreme conditions this rate may become negative (if there * is an intense radiation field leading to very hot grains, but no ionizing * photons, hence very few free electrons). we assume that the photon rates * are high enough under those circumstances to avoid phiTilde becoming negative, * but we will check that in qheat1 anyway. */ gptr.HeatingRate2 = HeatElectrons*gv.bin[nd].IntArea/4. - gv.bin[nd].GrainCoolTherm*gv.bin[nd].cnv_CM3_pH; /* >>chng 04 jan 25, moved inclusion into phitilde to qheat_init(), PvH */ /* heating/cooling above is in erg/s/cm^2 -> multiply with projected grain area per cm^3 */ /* GraC 0 is integral of dcheat, the total collisional heating of the grain */ HeatTot += gptr.FracPop*Heat1; /* GrGC 0 total cooling of gas integrated */ CoolTot += gptr.FracPop*Cool1; gv.bin[nd].ChemEn += gptr.FracPop*ChemEn1; } /* ============================================================================= */ /* heating/cooling due to molecules */ /* these rates do not depend on charge, hence they are outside of nz loop */ /* sticking prob for H2 onto grain, * estimated from accomodation coefficient defined at end of A.10 in BFM */ WeightMol = 2.*dense.AtomicWeight[ipHYDROGEN]; Accommodation = 2.*gv.bin[nd].atomWeight*WeightMol/POW2(gv.bin[nd].atomWeight+WeightMol); /* molecular hydrogen onto grains */ #ifndef IGNORE_GRAIN_ION_COLLISIONS /*CollisionRateMol = Accommodation*findspecies("H2")->den* */ CollisionRateMol = Accommodation*hmi.H2_total* sqrt(8.*BOLTZMANN/PI/ATOMIC_MASS_UNIT/WeightMol*phycon.te); /* >>chng 03 feb 12, added grain heating by H2 formation on the surface, PvH * >>refer grain H2 heat Takahashi & Uehara, ApJ, 561, 843 */ ipH2 = gv.which_H2distr[gv.bin[nd].matType]; /* this is rate in erg/cm^3/s */ /* >>chng 04 may 26, changed dense.gas_phase[ipHYDROGEN] -> dense.xIonDense[ipHYDROGEN][0], PvH */ gv.bin[nd].ChemEnH2 = gv.bin[nd].rate_h2_form_grains_used*dense.xIonDense[ipHYDROGEN][0]* H2_FORMATION_GRAIN_HEATING[ipH2]*EN1EV; /* convert to rate per cm^2 of projected grain surface area used here */ gv.bin[nd].ChemEnH2 /= gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3; #else CollisionRateMol = 0.; gv.bin[nd].ChemEnH2 = 0.; #endif /* now add in CO */ WeightMol = dense.AtomicWeight[ipCARBON] + dense.AtomicWeight[ipOXYGEN]; Accommodation = 2.*gv.bin[nd].atomWeight*WeightMol/POW2(gv.bin[nd].atomWeight+WeightMol); #ifndef IGNORE_GRAIN_ION_COLLISIONS CollisionRateMol += Accommodation*findspecieslocal("CO")->den* sqrt(8.*BOLTZMANN/PI/ATOMIC_MASS_UNIT/WeightMol*phycon.te); #else CollisionRateMol = 0.; #endif /* xi and eta are unity for neutrals and so ignored */ HeatCollisions = CollisionRateMol * 2.*BOLTZMANN*phycon.te; CoolEmitted = CollisionRateMol * 2.*BOLTZMANN*gv.bin[nd].tedust; HeatMolecules = HeatCollisions - CoolEmitted + gv.bin[nd].ChemEnH2; HeatTot += HeatMolecules; /* >>chng 00 may 05, reversed sign of gas cooling contribution */ CoolMolecules = HeatCollisions - CoolEmitted; CoolTot += CoolMolecules; gv.bin[nd].RateUp = 0.; gv.bin[nd].RateDn = 0.; HeatCor = 0.; for( nz=0; nz < gv.bin[nd].nChrg; nz++ ) { double d[4]; double rate_dn = GrainElecRecomb1(nd,nz,&d[0],&d[1]); double rate_up = GrainElecEmis1(nd,nz,&d[0],&d[1],&d[2],&d[3]); gv.bin[nd].RateUp += gv.bin[nd].chrg(nz).FracPop*rate_up; gv.bin[nd].RateDn += gv.bin[nd].chrg(nz).FracPop*rate_dn; /** \todo 2 a self-consistent treatment for the heating by Compton recoil should be used */ HeatCor += (gv.bin[nd].chrg(nz).FracPop*rate_up*gv.bin[nd].chrg(nz).ThresSurf - gv.bin[nd].chrg(nz).FracPop*rate_dn*gv.bin[nd].chrg(nz).ThresSurfInc + gv.bin[nd].chrg(nz).FracPop*rate_up*gv.bin[nd].chrg(nz).PotSurf - gv.bin[nd].chrg(nz).FracPop*rate_dn*gv.bin[nd].chrg(nz).PotSurfInc)*EN1RYD; } /* >>chng 01 nov 24, correct for imperfections in the n-charge state model, * these corrections should add up to zero, but are actually small but non-zero, PvH */ HeatTot += HeatCor; if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " molecules heat/cool: %.4e %.4e heatcor: %.4e\n", HeatMolecules*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3, CoolMolecules*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3, HeatCor*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3 ); } *dcheat = (realnum)(HeatTot*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3); *dccool = ( gv.lgDColOn ) ? (realnum)(CoolTot*gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3) : 0.f; gv.bin[nd].ChemEn *= gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3; gv.bin[nd].ChemEnH2 *= gv.bin[nd].IntArea/4.*gv.bin[nd].cnv_H_pCM3; /* add quantum heating due to molecule/ion collisions */ /* calculate heating rate in erg/H/s at standard depl * include contributions from molecules/neutral atoms and recombining ions * * in fully ionized conditions electron heating rates will be much higher * than ion and molecule rates since electrons are so much faster and grains * tend to be positive. in non-ionized conditions the main contribution will * come from neutral atoms and molecules, so it is appropriate to treat both * the same. in fully ionized conditions we don't care since unimportant. * * NB - if grains are hotter than ambient gas, the heating rate may become negative. * if photon rates are not high enough to prevent phiTilde from becoming negative, * we will raise a flag while calculating the quantum heating in qheat1 */ /* >>chng 01 nov 26, add in HeatCor as well, otherwise energy imbalance will result, PvH */ gv.bin[nd].HeatingRate1 = (HeatMolecules+HeatIons+HeatCor)*gv.bin[nd].IntArea/4.; /* >>chng 04 jan 25, moved inclusion into phiTilde to qheat_init(), PvH */ return; } /* GrainDrift computes grains drift velocity */ void GrainDrift() { long int i, loop; double alam, corr, dmomen, fac, fdrag, g0, g2, phi2lm, psi, rdust, si, vdold, volmom; DEBUG_ENTRY( "GrainDrift()" ); vector<realnum> help( rfield.nPositive ); for( i=0; i < rfield.nPositive; i++ ) { help[i] = (rfield.flux[0][i]+rfield.ConInterOut[i]+rfield.outlin[0][i]+rfield.outlin_noplot[i])* rfield.anu(i); } for( size_t nd=0; nd < gv.bin.size(); nd++ ) { /* find momentum absorbed by grain */ dmomen = 0.; for( i=0; i < rfield.nPositive; i++ ) { /* >>chng 02 dec 30, separated scattering cross section and asymmetry factor, PvH */ dmomen += help[i]*(gv.bin[nd].dstab1[i] + gv.bin[nd].pure_sc1[i]*gv.bin[nd].asym[i]); } ASSERT( dmomen >= 0. ); dmomen *= EN1RYD*4./gv.bin[nd].IntArea; /* now find force on grain, and drift velocity */ fac = 2*BOLTZMANN*phycon.te; /* now PSI defined by * >>refer grain physics Draine and Salpeter 79 Ap.J. 231, 77 (1979) */ psi = gv.bin[nd].dstpot*TE1RYD/phycon.te; if( psi > 0. ) { rdust = 1.e-6; alam = log(20.702/rdust/psi*phycon.sqrte/dense.SqrtEden); } else { alam = 0.; } phi2lm = POW2(psi)*alam; corr = 2.; /* >>chng 04 jan 31, increased loop limit 10 -> 50, precision -> 0.001, PvH */ for( loop = 0; loop < 50 && fabs(corr-1.) > 0.001; loop++ ) { vdold = gv.bin[nd].DustDftVel; /* interactions with protons */ si = gv.bin[nd].DustDftVel/phycon.sqrte*7.755e-5; g0 = 1.5045*si*sqrt(1.+0.4418*si*si); g2 = si/(1.329 + POW3(si)); /* drag force due to protons, both linear and square in velocity * equation 4 from D+S Ap.J. 231, p77. */ fdrag = fac*dense.xIonDense[ipHYDROGEN][1]*(g0 + phi2lm*g2); /* drag force due to interactions with electrons */ si = gv.bin[nd].DustDftVel/phycon.sqrte*1.816e-6; g0 = 1.5045*si*sqrt(1.+0.4418*si*si); g2 = si/(1.329 + POW3(si)); fdrag += fac*dense.eden*(g0 + phi2lm*g2); /* drag force due to collisions with hydrogen and helium atoms */ si = gv.bin[nd].DustDftVel/phycon.sqrte*7.755e-5; g0 = 1.5045*si*sqrt(1.+0.4418*si*si); fdrag += fac*(dense.xIonDense[ipHYDROGEN][0] + 1.1*dense.xIonDense[ipHELIUM][0])*g0; /* drag force due to interactions with helium ions */ si = gv.bin[nd].DustDftVel/phycon.sqrte*1.551e-4; g0 = 1.5045*si*sqrt(1.+0.4418*si*si); g2 = si/(1.329 + POW3(si)); fdrag += fac*dense.xIonDense[ipHELIUM][1]*(g0 + phi2lm*g2); /* this term does not work * 2 HEIII*(G0+4.*PSI**2*(ALAM-0.693)*G2) ) * this is total momentum absorbed by dust per unit vol */ volmom = dmomen/SPEEDLIGHT; if( fdrag > 0. ) { corr = sqrt(volmom/fdrag); gv.bin[nd].DustDftVel = (realnum)(vdold*corr); } else { corr = 1.; gv.lgNegGrnDrg = true; gv.bin[nd].DustDftVel = 0.; } if( trace.lgTrace && trace.lgDustBug ) { fprintf( ioQQQ, " %2ld new drift velocity:%10.2e momentum absorbed:%10.2e\n", loop, gv.bin[nd].DustDftVel, volmom ); } } } return; } /* GrnVryDpth sets the grain abundance as a function of depth into cloud * this is intended as a playpen where the user can alter things at will * standard, documented, code should go in GrnStdDpth */ STATIC double GrnVryDpth( /* nd is the number of the grain bin. The values are listed in the Cloudy output, * under "Average Grain Properties", and can easily be obtained by doing a trial * run without varying the grain abundance and setting stop zone to 1 */ size_t nd) { DEBUG_ENTRY( "GrnVryDpth()" ); if( nd >= gv.bin.size() ) { fprintf( ioQQQ, "invalid parameter for GrnVryDpth\n" ); cdEXIT(EXIT_FAILURE); } /* --- DEFINE THE USER-SUPPLIED GRAIN ABUNDANCE FUNCTION HERE --- */ /* This is the code that gets activated by the keyword "function" on the command line */ /* NB some quantities may still be undefined on the first call to this routine. */ /* the scale factor is the hydrogen atomic fraction, small when gas is ionized or molecular and * unity when atomic. This function is observed for PAHs across the Orion Bar, the PAHs are * strong near the ionization front and weak in the ionized and molecular gas */ double GrnVryDpth_v = dense.xIonDense[ipHYDROGEN][0]/dense.gas_phase[ipHYDROGEN]; /* This routine must return a scale factor >= 1.e-10 for the grain abundance at this position. * See Section A.3 in Hazy for more details on how grain abundances are calculated. The function * A_rel(r) mentioned there is this function times the multiplication factor set with the METALS * command (usually 1) and the multiplication factor set with the GRAINS command */ return max(1.e-10,GrnVryDpth_v); }
31.915856
113
0.635153
[ "vector", "model" ]
34d0a001f86abc839b7d792c37f0a0fac0b105f2
6,683
hpp
C++
test/src/minko/render/DrawCallPoolTest.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
478
2015-01-04T16:59:53.000Z
2022-03-07T20:28:07.000Z
test/src/minko/render/DrawCallPoolTest.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
83
2015-01-15T21:45:06.000Z
2021-11-08T11:01:48.000Z
test/src/minko/render/DrawCallPoolTest.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
175
2015-01-04T03:30:39.000Z
2020-01-27T17:08:14.000Z
/* Copyright (c) 2014 Aerys 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 "minko/Minko.hpp" #include "minko/MinkoTests.hpp" #include "gtest/gtest.h" namespace minko { namespace render { class DrawCallPoolTest : public ::testing::Test { protected: template<typename T> void testStateBindingToDefaultValueSwap(T stateMaterialValue, const std::string& stateName, const std::string& effectFile, std::function<T(DrawCall*)> valueFunc) { auto fx = MinkoTests::loadEffect(effectFile); ASSERT_NE(fx, nullptr); ASSERT_EQ(fx->techniques().size(), 1); ASSERT_EQ(fx->techniques().at("default").size(), 1); auto pass = fx->techniques().at("default")[0]; DrawCallPool pool; data::Store rootData; data::Store rendererData; data::Store targetData; auto material = material::Material::create(); targetData.addProvider(material->data(), component::Surface::MATERIAL_COLLECTION_NAME); auto geom = geometry::QuadGeometry::create(MinkoTests::canvas()->context()); targetData.addProvider(geom->data(), component::Surface::GEOMETRY_COLLECTION_NAME); render::EffectVariables variables{ { "materialUuid", material->uuid() }, { "geometryUuid", geom->uuid() } }; pool.addDrawCalls(fx, "default", variables, rootData, rendererData, targetData); const auto& drawCalls = pool.drawCalls().begin()->second; auto drawCall = drawCalls.at(0u).empty() ? drawCalls.at(1u).front() : drawCalls.at(0u).front(); auto stateDefaultValues = drawCall->pass()->stateBindings().defaultValues; material->data()->set(stateName, stateMaterialValue); pool.update(); auto drawCallValue = valueFunc(drawCall); auto stateDefaultValue = stateDefaultValues.get<T>(stateName); auto hasProperty = drawCall->targetData().hasProperty(stateName); ASSERT_TRUE(hasProperty); ASSERT_EQ(valueFunc(drawCall), material->data()->get<T>(stateName)); material->data()->unset(stateName); pool.update(); drawCallValue = valueFunc(drawCall); stateDefaultValue = stateDefaultValues.get<T>(stateName); ASSERT_EQ(valueFunc(drawCall), stateDefaultValues.get<T>(stateName)); } void testStateTargetBindingToDefaultValueSwap(const std::string& effectFile, const std::string& stateName, TextureSampler stateMaterialValue, const std::string& renderTargetName, math::ivec2 renderTargetSize) { auto assets = file::AssetLibrary::create(MinkoTests::canvas()->context()); auto fx = MinkoTests::loadEffect(effectFile, assets); ASSERT_NE(fx, nullptr); ASSERT_EQ(fx->techniques().size(), 1); ASSERT_EQ(fx->techniques().at("default").size(), 1); auto pass = fx->techniques().at("default")[0]; DrawCallPool pool; data::Store rootData; data::Store rendererData; data::Store targetData; auto material = material::Material::create(); targetData.addProvider(material->data(), component::Surface::MATERIAL_COLLECTION_NAME); auto geom = geometry::QuadGeometry::create(MinkoTests::canvas()->context()); targetData.addProvider(geom->data(), component::Surface::GEOMETRY_COLLECTION_NAME); render::EffectVariables variables{ { "materialUuid", material->uuid() }, { "geometryUuid", geom->uuid() } }; pool.addDrawCalls(fx, "default", variables, rootData, rendererData, targetData); auto drawCall = pool.drawCalls().begin()->second.at(0u).front(); auto stateDefaultValues = drawCall->pass()->stateBindings().defaultValues; material->data()->set(stateName, stateMaterialValue); pool.update(); auto hasProperty = drawCall->targetData().hasProperty(stateName); ASSERT_TRUE(hasProperty); ASSERT_EQ(drawCall->target(), material->data()->get<TextureSampler>(stateName)); material->data()->unset(stateName); pool.update(); auto states = drawCall->pass()->states(); ASSERT_EQ(drawCall->target(), stateDefaultValues.get<TextureSampler>(stateName)); ASSERT_NE(states.target(), States::DEFAULT_TARGET); ASSERT_EQ(states.target(), assets->texture(renderTargetName)->sampler()); ASSERT_NE(assets->texture(renderTargetName), nullptr); ASSERT_EQ(assets->texture(renderTargetName)->width(), renderTargetSize[0]); ASSERT_EQ(assets->texture(renderTargetName)->height(), renderTargetSize[1]); } }; } }
44.553333
111
0.576388
[ "geometry", "render" ]
34d455f5e2ae664101ae626be74df811fba654e3
1,702
cpp
C++
src/HTTP/HTMLDocument.cpp
b10h4z4rd1337/CppServer
983f682bd129ab615e8433304584467a716ec455
[ "Apache-2.0" ]
3
2018-01-03T10:33:43.000Z
2022-03-13T20:04:39.000Z
src/HTTP/HTMLDocument.cpp
b10h4z4rd1337/CppServer
983f682bd129ab615e8433304584467a716ec455
[ "Apache-2.0" ]
null
null
null
src/HTTP/HTMLDocument.cpp
b10h4z4rd1337/CppServer
983f682bd129ab615e8433304584467a716ec455
[ "Apache-2.0" ]
1
2022-03-13T20:04:47.000Z
2022-03-13T20:04:47.000Z
// // HTMLDocument.cpp // Cpp_Server // // Created by Mathias Tahas on 22.04.17. // Copyright © 2017 Mathias Tahas. All rights reserved. // #include "HTMLDocument.hpp" #include "FileIO.hpp" #include "Parser.hpp" #include <sstream> using namespace CppServer; using namespace FileIO; HTMLDocument HTMLDocument::fromFile(const string &fileName) { return HTMLDocument(loadFile(fileName)); } HTMLDocument HTMLDocument::fromString(const string &html) { return HTMLDocument(new string(html)); } HTMLDocument::HTMLDocument(string* html) : html(shared_ptr<string>(html)), size(html->size()) { fileHandles = shared_ptr<vector<FileHandler>>(new vector<FileHandler>()); vector<string> *res = parseRessources(*html); loadRessources(res); delete res; } void HTMLDocument::setAutoParsePostParamters(bool b) { this->autoParse = b; } vector<string>* HTMLDocument::parseRessources(const string& html) { vector<string> *result = new vector<string>; size_t pos = 0; while ((pos = html.find("src=", pos)) != string::npos) { pos += 5; size_t len = html.find(" ", pos + 1) - pos - 1; result->push_back(html.substr(pos, len)); } return result; } void HTMLDocument::loadRessources(vector<string> *files) { for (auto name : *files) { FileHandler handler(name); fileHandles->push_back(handler); } } void HTMLDocument::operator()(Request &req, Response &res) { string html = *(this->html); if (autoParse) { html = Parser::parse(html, req.parameters); } res.setHeader("Content-Type", "text/html"); res.setHeader("Content-Length", (stringstream() << html.size()).str()); res.write(html); }
26.59375
95
0.663925
[ "vector" ]
34d5b8396b7a3ae9207edf0444064d2ded93b5b7
48,192
cpp
C++
src/GameState.cpp
jemeador/monopoly
b4945fbb3cb527f54d3875b367b906e35e07acda
[ "MIT" ]
null
null
null
src/GameState.cpp
jemeador/monopoly
b4945fbb3cb527f54d3875b367b906e35e07acda
[ "MIT" ]
16
2021-02-13T04:38:20.000Z
2021-05-02T23:16:10.000Z
src/GameState.cpp
jemeador/monopoly
b4945fbb3cb527f54d3875b367b906e35e07acda
[ "MIT" ]
null
null
null
#include"GameState.h" #include"Board.h" #include"DisplayStrings.h" using namespace monopoly; #include<algorithm> #include<iostream> #include<numeric> GameState::GameState(GameSetup setup) : rng() , phase(TurnPhase::WaitingForRoll) , bank() , decks(init_decks(setup)) , players(init_players(setup)) , doublesStreak(0) , lastDiceRoll(0, 0) , pendingTradeAgreement() , pendingDebtSettlements() , currentAuction() , propertiesPendingAuction() , pendingAcquisitions() , pendingPurchaseDecision(false) , pendingRoll(true) , activePlayerIndex(Player::p1) { std::seed_seq seedSeq(setup.seed.begin(), setup.seed.end()); rng = std::mt19937(seedSeq); decks[DeckType::CommunityChest].shuffle(rng); decks[DeckType::Chance].shuffle(rng); } bool GameState::is_game_over() const { return phase == TurnPhase::GameOver; } int GameState::get_turn() const { return turn; } Bank GameState::get_bank() const { return bank; } int GameState::get_player_count() const { return players.size(); } int GameState::get_players_remaining_count() const { return std::count_if(players.begin(), players.end(), [](Player const& player) { return !player.eliminated; }); } bool GameState::get_player_eliminated(int playerIndex) const { return players[playerIndex].eliminated; } int GameState::get_player_funds(int playerIndex) const { return players[playerIndex].funds; } Space GameState::get_player_position(int playerIndex) const { return players[playerIndex].position; } int GameState::get_player_turns_remaining_in_jail(int playerIndex) const { return players[playerIndex].turnsRemainingInJail; } int GameState::get_active_player_index() const { return activePlayerIndex; } std::set<Property> GameState::get_player_deeds(int playerIndex) const { return players[playerIndex].deeds; } std::set<DeckType> GameState::get_player_get_out_of_jail_free_cards(int playerIndex) const { return players[playerIndex].getOutOfJailFreeCards; } int GameState::get_controlling_player_index() const { switch (phase) { case TurnPhase::WaitingForTradeOfferResponse: return pendingTradeAgreement->consideringPlayer; case TurnPhase::WaitingForDebtSettlement: return pendingDebtSettlements.front ().debtor; case TurnPhase::WaitingForBids: return currentAuction.biddingOrder.front (); case TurnPhase::WaitingForAcquisitionManagement: return pendingAcquisitions.front().recipient; case TurnPhase::WaitingForBuyPropertyInput: return activePlayerIndex; case TurnPhase::WaitingForRoll: return activePlayerIndex; case TurnPhase::WaitingForTurnEnd: return activePlayerIndex; case TurnPhase::GameOver: return activePlayerIndex; } return activePlayerIndex; } int GameState::get_next_player_index(int playerIndex) const { if (playerIndex == -1) { playerIndex = activePlayerIndex; } int nextIndex = playerIndex; do { nextIndex = (nextIndex + 1) % static_cast<int> (players.size()); } while (players[nextIndex].eliminated && nextIndex != playerIndex); return nextIndex; } int GameState::get_net_worth(int playerIndex) const { auto const& p = players[playerIndex]; std::vector<int> values; int netWorth = p.funds; // Add property values std::transform(begin(p.deeds), end(p.deeds), std::back_inserter(values), [this](Property p) -> int { return mortgagedProperties.count(p) ? mortgage_value_of_property(p) : price_of_property(p); }); netWorth = std::accumulate(begin(values), end(values), netWorth); values.clear(); // Add building values std::transform(begin(p.deeds), end(p.deeds), std::back_inserter(values), [this](Property p) -> int { return get_building_level(p) * price_per_house_on_property(p); }); netWorth = std::accumulate(begin(values), end(values), netWorth); return netWorth; } int GameState::get_property_owner_index(Property property) const { if (property == Property::Invalid) { return -1; } for (auto p = 0; p < players.size(); ++p) { if (players[p].deeds.count(property)) return p; } return Player::None; } bool GameState::get_property_is_mortgaged(Property property) const { return mortgagedProperties.count(property) > 0; } int GameState::get_properties_owned_in_group(Property property) const { auto const owner = get_property_owner_index(property); auto const ownedGroupCount = owner ? get_properties_owned_in_group_by_player(owner, property_group(property)) : 0; return ownedGroupCount; } int GameState::get_properties_owned_in_group_by_player(int playerIndex, PropertyGroup group) const { if (playerIndex == Player::None) return 0; auto const& deeds = players[playerIndex].deeds; return std::count_if(deeds.begin(), deeds.end(), [group](Property property) { return property_is_in_group(property, group); }); } TurnPhase GameState::get_turn_phase() const { return phase; } int GameState::get_building_level(Property property) const { auto const buildingLevelIt = buildingLevels.find(property); if (buildingLevelIt != buildingLevels.end()) { return buildingLevelIt->second; } return 0; } int GameState::get_min_building_level_in_group(PropertyGroup group) const { int min = HotelLevel; for (auto property : properties_in_group(group)) { min = std::min(get_building_level(property), min); } return min; } int GameState::get_max_building_level_in_group(PropertyGroup group) const { int max = 0; for (auto property : properties_in_group(group)) { max = std::max(get_building_level(property), max); } return max; } std::map<Property, int> const& GameState::get_building_levels() const { return buildingLevels; } Trade GameState::get_pending_trade_offer() const { return pendingTradeAgreement.value_or(Trade{}); } Auction GameState::get_current_auction() const { return currentAuction; } int GameState::calculate_rent(Property property) const { auto const ownerIndex = get_property_owner_index(property); if (ownerIndex == Player::None) { return 0; } auto const group = property_group(property); auto const ownedDeedsInGroup = get_properties_owned_in_group_by_player(ownerIndex, group); if (group == PropertyGroup::Railroad) { return rent_price_of_railroad(ownedDeedsInGroup); } else if (group == PropertyGroup::Utility) { return rent_price_of_utility(ownedDeedsInGroup, lastDiceRoll); } else { // group is real estate auto const buildingLevelIt = buildingLevels.find(property); if (buildingLevelIt != buildingLevels.end() && buildingLevelIt->second > 0) { return rent_price_of_improved_real_estate(property, buildingLevelIt->second); } else if (properties_in_group(group).size() == ownedDeedsInGroup) { return 2 * rent_price_of_real_estate(property); } else { return rent_price_of_real_estate(property); } } } int GameState::calculate_closing_costs_on_sale(Property property) const { if (mortgagedProperties.count(property)) { return mortgage_value_of_property(property) * MortgageInterestRate; } else { return 0; } } int GameState::calculate_liquid_assets_value(int playerIndex) const { auto const& p = players[playerIndex]; return p.funds + calculate_liquid_value_of_deeds (p.deeds) + calculate_liquid_value_of_buildings (p.deeds); } int GameState::calculate_liquid_value_of_deeds(std::set<Property> deeds) const { std::vector<int> values; std::transform(begin(deeds), end(deeds), std::back_inserter(values), [this](Property p) -> int { return mortgagedProperties.count(p) ? 0 : mortgage_value_of_property(p); }); return std::accumulate(begin(values), end(values), 0); } int GameState::calculate_liquid_value_of_buildings(std::set<Property> properties) const { std::vector<int> values; std::transform(begin(properties), end(properties), std::back_inserter(values), [this](Property p) -> int { return get_building_level(p) * sell_price_per_house_on_property(p); }); return std::accumulate(begin(values), end(values), 0); } int GameState::calculate_liquid_value_of_promise(Promise promise) const { return promise.cash + calculate_liquid_value_of_deeds(promise.deeds); } std::pair<int, int> GameState::random_dice_roll() { std::uniform_int_distribution<int> rollDie(1, 6); lastDiceRoll = std::pair<int, int>{ rollDie(rng), rollDie(rng) }; return lastDiceRoll; } std::pair<int, int> GameState::get_last_dice_roll() const { return lastDiceRoll; } bool GameState::check_if_player_is_allowed_to_roll(int actorIndex) const { if (phase != TurnPhase::WaitingForRoll) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_use_get_out_jail_free_card(int actorIndex) const { if (phase != TurnPhase::WaitingForRoll) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } auto const& player = players.at(actorIndex); if (player.turnsRemainingInJail == 0) { return false; } if (player.getOutOfJailFreeCards.empty()) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_pay_bail(int actorIndex) const { if (phase != TurnPhase::WaitingForRoll) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } auto const& player = players.at(actorIndex); if (player.turnsRemainingInJail == 0) { return false; } if (player.funds < BailCost) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_buy_property(int actorIndex) const { if (!check_if_player_is_allowed_to_auction_property(actorIndex)) { return false; } auto const landedOnProperty = space_to_property(players[actorIndex].position); if (players[actorIndex].funds < price_of_property(landedOnProperty)) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_auction_property(int actorIndex) const { if (phase != TurnPhase::WaitingForBuyPropertyInput) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } auto const landedOnProperty = space_to_property(players[actorIndex].position); assert(landedOnProperty != Property::Invalid); // shouldn't be waiting for buy on non-property if (landedOnProperty == Property::Invalid) { return false; } auto ownerIndex = get_property_owner_index(landedOnProperty); assert(ownerIndex == Player::None); // shouldn't be waiting for buy if player owned if (ownerIndex != Player::None) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_mortgage(int actorIndex, Property property) const { if (phase == TurnPhase::WaitingForBids || phase == TurnPhase::GameOver) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } if (get_property_owner_index(property) != actorIndex) { return false; } if (get_property_is_mortgaged(property)) { return false; } if (get_max_building_level_in_group(property_group(property)) > 0) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_unmortgage(int actorIndex, Property property) const { if (phase == TurnPhase::WaitingForBids || phase == TurnPhase::WaitingForDebtSettlement || phase == TurnPhase::GameOver) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } if (get_property_owner_index(property) != actorIndex) { return false; } if (!get_property_is_mortgaged(property)) { return false; } if (players[actorIndex].funds < unmortgage_price_of_property(property)) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_buy_building(int actorIndex, Property property) const { if (property == Property::Invalid) { return false; } if (phase == TurnPhase::WaitingForBids || phase == TurnPhase::WaitingForDebtSettlement || phase == TurnPhase::GameOver) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } if (players[actorIndex].funds < price_per_house_on_property(property)) { return false; } auto const currentBuildingLevel = get_building_level(property); if (currentBuildingLevel == HotelLevel) { return false; } for (auto p : properties_in_group(property_group(property))) { if (get_property_owner_index(p) != actorIndex) { return false; } if (currentBuildingLevel > get_building_level(p)) { return false; } if (get_property_is_mortgaged(p)) { return false; } } if (currentBuildingLevel + 1 < HotelLevel && bank.houses == 0) { return false; } if (currentBuildingLevel + 1 == HotelLevel && bank.hotels == 0) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_sell_building(int actorIndex, Property property) const { if (property == Property::Invalid) { return false; } if (phase == TurnPhase::WaitingForBids || phase == TurnPhase::GameOver) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } auto const currentBuildingLevel = get_building_level(property); if (currentBuildingLevel == 0) { return false; } for (auto p : properties_in_group(property_group(property))) { if (get_property_owner_index(p) != actorIndex) { return false; } if (currentBuildingLevel < get_building_level(p)) { return false; } if (get_property_is_mortgaged(p)) { return false; } } if (currentBuildingLevel == HotelLevel && bank.houses < HotelLevel - 1) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_sell_all_buildings(int actorIndex, PropertyGroup group) const { if (phase == TurnPhase::WaitingForBids || phase == TurnPhase::GameOver) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } if (get_min_building_level_in_group(group) == 0) { return false; } for (auto p : properties_in_group(group)) { if (get_property_owner_index(p) != actorIndex) { return false; } } return true; } bool GameState::check_if_player_is_allowed_to_bid(int actorIndex, int amount) const { // If a player can't decline a bid, they can't bid; but we still have to check the amount bid if (! check_if_player_is_allowed_to_decline_bid (actorIndex)) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } if (amount <= currentAuction.highestBid) { return false; } // Avoid letting players involuntarily bankrupt themselves by bidding too much if (amount + calculate_closing_costs_on_sale(currentAuction.property) > calculate_liquid_assets_value(actorIndex)) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_decline_bid(int actorIndex) const { if (phase != TurnPhase::WaitingForBids) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_trade_with_player(int actorIndex, int consideringIndex) const { if (phase == TurnPhase::WaitingForBids) { return false; } if (get_controlling_player_index() != actorIndex) { return false; } if (actorIndex == consideringIndex) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_decline_trade(int actorIndex) const { if (phase != TurnPhase::WaitingForTradeOfferResponse) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_end_turn(int actorIndex) const { if (phase != TurnPhase::WaitingForTurnEnd) { return false; } if (get_controlling_player_index () != actorIndex) { return false; } return true; } bool GameState::check_if_player_is_allowed_to_resign(int actorIndex) const { if (get_controlling_player_index () != actorIndex) { return false; } if (phase == TurnPhase::GameOver) { return false; } return true; } bool GameState::check_if_trade_is_valid(Trade trade) const { if (phase == TurnPhase::WaitingForBids) { return false; } if (get_controlling_player_index() != trade.offeringPlayer) { return false; } if (trade.offeringPlayer == trade.consideringPlayer) { return false; } if (trade.offer.cash > 0 && trade.consideration.cash > 0) { // don't trade cash for cash return false; } auto check_validity_in_one_direction = [this](Trade t) { if (t.offer == Promise{}) { // can't offer nothing return false; } if (t.offer.cash < 0) { // can't trade debt, use a positive value return false; } if (!check_if_player_can_fulfill_promise(t.offeringPlayer, t.offer)) { return false; } if (!check_if_player_can_pay_closing_costs(t.offeringPlayer, t.offer, t.consideration)) { return false; } return true; }; if (!check_validity_in_one_direction(trade)) { return false; } if (!check_validity_in_one_direction(reciprocal_trade(trade))) { return false; } return true; } bool GameState::check_if_player_can_fulfill_promise(int playerIndex, Promise promise) const { auto const& promisingPlayer = players[playerIndex]; if (promise.cash > 0 && promise.cash > promisingPlayer.funds) { return false; } for (auto const deed : promise.deeds) { if (promisingPlayer.deeds.count(deed) == 0) { return false; } if (get_max_building_level_in_group(property_group(deed)) > 0) { return false; } } for (auto const gojfc : promise.getOutOfJailFreeCards) { if (promisingPlayer.getOutOfJailFreeCards.count(gojfc) == 0) { return false; } } return true; } bool GameState::check_if_player_can_pay_closing_costs(int playerIndex, Promise lostAssets, Promise gainedAssets) const { auto liquidValue = calculate_liquid_assets_value(playerIndex); liquidValue -= calculate_liquid_value_of_promise(lostAssets); liquidValue += calculate_liquid_value_of_promise(gainedAssets); return liquidValue >= 0; } void GameState::player_action_roll(int playerIndex) { std::cout << player_name(playerIndex) << " rolled the dice" << std::endl; force_roll(playerIndex, random_dice_roll()); resolve_game_state(); } void GameState::player_action_use_get_out_of_jail_free_card(int playerIndex, DeckType preferredDeckType) { assert(check_if_player_is_allowed_to_use_get_out_jail_free_card(playerIndex)); std::cout << player_name(playerIndex) << " used a get out of jail free card" << std::endl; auto& player = players[playerIndex]; if (player.turnsRemainingInJail == 0) return; if (player.getOutOfJailFreeCards.size() == 0) return; auto const usedDeckType = (player.getOutOfJailFreeCards.count(preferredDeckType)) ? preferredDeckType : *player.getOutOfJailFreeCards.begin(); std::cout << player_name(playerIndex) << " used a " << to_string(usedDeckType) << " Get Out of Jail Free card" << std::endl; force_return_get_out_of_jail_free_card(playerIndex, usedDeckType); force_leave_jail(playerIndex); resolve_game_state(); } void GameState::player_action_pay_bail(int playerIndex) { assert(check_if_player_is_allowed_to_pay_bail(playerIndex)); std::cout << player_name(playerIndex) << " paid bail" << std::endl; force_pay_bail(playerIndex); resolve_game_state(); } void GameState::player_action_buy_property(int playerIndex) { assert(check_if_player_is_allowed_to_buy_property(playerIndex)); auto const landedOnProperty = space_to_property(players[playerIndex].position); std::cout << player_name(playerIndex) << " bought " << to_string(landedOnProperty) << std::endl; force_subtract_funds(playerIndex, price_of_property(landedOnProperty)); force_give_deed(playerIndex, landedOnProperty); pendingPurchaseDecision = false; resolve_game_state(); } void GameState::player_action_auction_property(int playerIndex) { assert(check_if_player_is_allowed_to_auction_property(playerIndex)); auto const landedOnProperty = space_to_property(players[playerIndex].position); std::cout << player_name(playerIndex) << " declined to buy " << to_string(landedOnProperty) << std::endl; propertiesPendingAuction.push(landedOnProperty); pendingPurchaseDecision = false; resolve_game_state(); } void GameState::player_action_mortgage(int playerIndex, Property property) { assert(check_if_player_is_allowed_to_mortgage(playerIndex, property)); std::cout << player_name(playerIndex) << " mortgaged " << to_string(property) << std::endl; force_set_mortgaged(property, true); force_add_funds(playerIndex, mortgage_value_of_property(property)); resolve_game_state(); } void GameState::player_action_unmortgage(int playerIndex, Property property) { assert(check_if_player_is_allowed_to_unmortgage(playerIndex, property)); std::cout << player_name(playerIndex) << " unmortgaged " << to_string(property) << std::endl; force_set_mortgaged(property, false); force_subtract_funds(playerIndex, unmortgage_price_of_property(property)); resolve_game_state(); } void GameState::player_action_buy_building(int playerIndex, Property property) { assert(check_if_player_is_allowed_to_buy_building(playerIndex, property)); std::cout << player_name(playerIndex) << " bought a building on " << to_string(property) << std::endl; force_add_building(property); force_subtract_funds(playerIndex, price_per_house_on_property(property)); resolve_game_state(); } void GameState::player_action_sell_building(int playerIndex, Property property) { assert(check_if_player_is_allowed_to_sell_building(playerIndex, property)); std::cout << player_name(playerIndex) << " sold a building on " << to_string(property) << std::endl; force_remove_building(property); force_add_funds(playerIndex, sell_price_per_house_on_property(property)); resolve_game_state(); } void GameState::player_action_sell_all_buildings(int playerIndex, PropertyGroup group) { assert(check_if_player_is_allowed_to_sell_all_buildings(playerIndex, group)); std::cout << player_name(playerIndex) << " sold all bulding in color group " << to_string(group) << std::endl; force_sell_all_buildings(playerIndex, group); resolve_game_state(); } void GameState::player_action_bid(int playerIndex, int amount) { assert(check_if_player_is_allowed_to_bid (playerIndex, amount)); std::cout << player_name(playerIndex) << " bid $" << amount << std::endl; currentAuction.highestBid = amount; currentAuction.biddingOrder.erase(currentAuction.biddingOrder.begin ()); currentAuction.biddingOrder.push_back(playerIndex); resolve_game_state(); } void GameState::player_action_decline_bid(int playerIndex) { assert(check_if_player_is_allowed_to_decline_bid (playerIndex)); std::cout << player_name(playerIndex) << " has declined to bid" << std::endl; currentAuction.biddingOrder.erase(currentAuction.biddingOrder.begin ()); resolve_game_state(); } void GameState::player_action_offer_trade(Trade trade) { assert(check_if_trade_is_valid (trade)); if (pendingTradeAgreement && trades_are_reciprocal(trade, *pendingTradeAgreement)) { pendingTradeAgreement = {}; std::cout << player_name(trade.offeringPlayer) << " accepted the offer from " << trade.consideringPlayer << std::endl; force_trade(trade); } else { if (pendingTradeAgreement) { std::cout << player_name(trade.offeringPlayer) << " made a counter-offer to " << trade.consideringPlayer << std::endl; } else { std::cout << player_name(trade.offeringPlayer) << " offered a trade to " << trade.consideringPlayer << std::endl; } pendingTradeAgreement = trade; } resolve_game_state(); } void GameState::player_action_decline_trade(int playerIndex) { assert(check_if_player_is_allowed_to_decline_trade(playerIndex)); std::cout << player_name(playerIndex) << " rejected the offer" << std::endl; pendingTradeAgreement = {}; resolve_game_state(); } void GameState::player_action_end_turn(int playerIndex) { assert(check_if_player_is_allowed_to_end_turn(playerIndex)); std::cout << player_name(playerIndex) << " ended their turn" << std::endl; force_start_turn(get_next_player_index()); resolve_game_state(); } void GameState::player_action_resign(int resigneeIndex) { assert(check_if_player_is_allowed_to_resign(resigneeIndex)); std::cout << player_name(resigneeIndex) << " declared bankruptcy! " << std::endl; std::optional<int> creditor; for (auto debtIt = pendingDebtSettlements.begin(); debtIt != pendingDebtSettlements.end();) { if (debtIt->debtor == resigneeIndex) { if (debtIt->creditor) { creditor = debtIt->creditor; pendingDebtSettlements.erase(debtIt++); continue; } } ++debtIt; } if (creditor) { std::cout << player_name(resigneeIndex) << " must hand over all assets to " << player_name(*creditor) << std::endl; force_bankrupt_by_player(resigneeIndex, *creditor); } else { std::cout << player_name(resigneeIndex) << " will have their properties put up for auction" << std::endl; force_bankrupt_by_bank(resigneeIndex); } if (check_if_player_is_allowed_to_auction_property (resigneeIndex)) { player_action_auction_property(resigneeIndex); } if (check_if_player_is_allowed_to_decline_trade (resigneeIndex)) { player_action_decline_trade(resigneeIndex); } if (check_if_player_is_allowed_to_decline_bid(resigneeIndex)) { player_action_decline_bid(resigneeIndex); } if (activePlayerIndex == resigneeIndex) { force_finish_turn(); force_start_turn(get_next_player_index()); } players[resigneeIndex].eliminated = true; resolve_game_state(); } void GameState::force_start_turn(int playerIndex) { ++turn; pendingRoll = true; activePlayerIndex = playerIndex; resolve_game_state(); } void GameState::force_finish_turn() { doublesStreak = 0; pendingRoll = false; resolve_game_state(); } void GameState::force_funds(int playerIndex, int funds) { players[playerIndex].funds = funds; std::cout << player_name(playerIndex) << " has $" << funds << std::endl; } void GameState::force_add_funds(int playerIndex, int funds) { players[playerIndex].funds += funds; std::cout << player_name(playerIndex) << " collects $" << funds << std::endl; } void GameState::force_subtract_funds(int playerIndex, int funds) { players[playerIndex].funds -= funds; std::cout << player_name(playerIndex) << " pays $" << funds << std::endl; if (players[playerIndex].funds < 0) force_liquidate_to_pay_bank_prompt(playerIndex, -players[playerIndex].funds); } void GameState::force_transfer_funds(int fromPlayerIndex, int toPlayerIndex, int funds) { if (fromPlayerIndex == toPlayerIndex) return; players[fromPlayerIndex].funds -= funds; players[toPlayerIndex].funds += funds; std::cout << player_name(fromPlayerIndex) << " pays $" << funds << " to " << player_name(toPlayerIndex) << std::endl; if (players[fromPlayerIndex].funds < 0) force_liquidate_to_pay_player_prompt(fromPlayerIndex, toPlayerIndex, -players[fromPlayerIndex].funds); } void GameState::force_go_to_jail(int playerIndex) { force_position(playerIndex, Space::Jail); if (players[playerIndex].turnsRemainingInJail != MaxJailTurns) std::cout << player_name(playerIndex) << " went to jail!" << std::endl; players[playerIndex].turnsRemainingInJail = MaxJailTurns; force_finish_turn(); } void GameState::force_pay_bail(int playerIndex) { force_subtract_funds(playerIndex, BailCost); force_leave_jail(playerIndex); } void GameState::force_leave_jail(int playerIndex) { players[playerIndex].turnsRemainingInJail = 0; } void GameState::force_roll(int playerIndex, std::pair<int, int> roll) { assert_valid_die_value(roll.first); assert_valid_die_value(roll.second); activePlayerIndex = playerIndex; lastDiceRoll = roll; std::cout << player_name(playerIndex) << " rolled [" << roll.first << "] [" << roll.second << "]" << std::endl; if (roll.first == roll.second) { doublesStreak += 1; } else { doublesStreak = 0; } if (players[playerIndex].turnsRemainingInJail > 0) { if (doublesStreak > 0) { doublesStreak = 0; std::cout << player_name(playerIndex) << " rolled doubles and left jail" << std::endl; force_leave_jail(playerIndex); } else { auto& t = players[playerIndex].turnsRemainingInJail; t -= 1; if (t > 0) { std::cout << player_name(playerIndex) << " is stuck in jail" << std::endl; force_finish_turn(); return; } else { std::cout << player_name(playerIndex) << " must pay fine" << std::endl; force_pay_bail(playerIndex); } } } else if (doublesStreak == 3) { std::cout << player_name(playerIndex) << " went to jail for rolling 3 doubles in a row" << std::endl; force_go_to_jail(playerIndex); return; } pendingRoll = doublesStreak > 0; if (pendingRoll) std::cout << player_name(playerIndex) << " gets an extra roll for rolling doubles" << std::endl; int const sum = roll.first + roll.second; force_advance(playerIndex, sum); } void GameState::force_advance(int playerIndex, int dist) { auto const currentPos = players[playerIndex].position; std::cout << player_name(playerIndex) << " advanced " << dist << " spaces" << std::endl; if (advancing_will_pass_go(currentPos, dist)) { std::cout << player_name(playerIndex) << " passed " << to_string(Space::Go) << std::endl; force_add_funds(playerIndex, GoSalary); } force_land(playerIndex, add_distance(players[playerIndex].position, dist)); } void GameState::force_advance_without_landing(int playerIndex, int dist) { auto const currentPos = players[playerIndex].position; std::cout << player_name(playerIndex) << " advanced " << dist << " spaces" << std::endl; if (advancing_will_pass_go(currentPos, dist)) { std::cout << player_name(playerIndex) << " passed " << to_string(Space::Go) << std::endl; force_add_funds(playerIndex, GoSalary); } force_position(playerIndex, add_distance(players[playerIndex].position, dist)); } void GameState::force_advance_to(int playerIndex, Space space) { auto const currentPos = players[playerIndex].position; force_advance(playerIndex, distance(currentPos, space)); } void GameState::force_advance_to_without_landing(int playerIndex, Space space) { auto const currentPos = players[playerIndex].position; force_advance_without_landing(playerIndex, distance(currentPos, space)); } void GameState::force_land(int playerIndex, Space space) { activePlayerIndex = playerIndex; std::cout << player_name(playerIndex) << " landed on " << to_string(space) << std::endl; force_leave_jail(playerIndex); force_position(playerIndex, space); if (space_is_property(space)) { auto const property = space_to_property(space); auto const ownerIndex = get_property_owner_index(property); if (ownerIndex == Player::None) { force_property_offer(playerIndex, property); } else if (ownerIndex != playerIndex) { auto const rent = calculate_rent(property); force_transfer_funds(playerIndex, ownerIndex, rent); } } else { switch (space) { case Space::IncomeTax: force_income_tax(playerIndex); break; case Space::LuxuryTax: force_luxury_tax(playerIndex); break; case Space::CommunityChest_1: case Space::CommunityChest_2: case Space::CommunityChest_3: force_draw_community_chest_card(playerIndex); break; case Space::Chance_1: case Space::Chance_2: case Space::Chance_3: force_draw_chance_card(playerIndex); break; case Space::GoToJail: force_go_to_jail(playerIndex); break; default: // Nothing happens when landing on Go, or Jail, or FreeParking break; } } resolve_game_state(); } void GameState::force_position(int playerIndex, Space space) { players[playerIndex].position = space; } void GameState::force_property_offer(int playerIndex, Property property) { if (bank.deeds.count(property)) { force_property_offer_prompt(playerIndex, property); } } void GameState::force_stack_deck(DeckType deckType, DeckContainer const& cards) { decks[deckType].stack_deck(cards); } void GameState::force_draw_chance_card(int playerIndex) { force_draw_card(playerIndex, DeckType::Chance); } void GameState::force_draw_community_chest_card(int playerIndex) { force_draw_card(playerIndex, DeckType::CommunityChest); } void GameState::force_draw_card(int playerIndex, DeckType deckType) { auto& deck = decks[deckType]; std::cout << player_name(playerIndex) << " draws a " + to_string(deckType) + " card " << std::endl; auto const card = deck.draw(); std::cout << "\t" << card_data(card).effectText << std::endl; apply_card_effect(*this, playerIndex, card); } void GameState::force_income_tax(int playerIndex) { auto const netWorth = get_net_worth(playerIndex); assert(netWorth >= 0); auto const tax = std::min<int>(200, static_cast<int> (ceil(netWorth * 0.1))); std::cout << player_name(playerIndex) << " pays income tax (" << tax << ")" << std::endl; force_subtract_funds(playerIndex, tax); } void GameState::force_luxury_tax(int playerIndex) { auto const tax = 100; std::cout << player_name(playerIndex) << " pays luxury tax (" << tax << ")" << std::endl; force_subtract_funds(playerIndex, tax); } void GameState::force_give_deed(int playerIndex, Property deed) { auto const countErased = bank.deeds.erase(deed); assert(countErased == 1); auto const insertRet = players[playerIndex].deeds.insert(deed); assert(insertRet.second); } void GameState::force_give_deeds(int playerIndex, std::set<Property> deeds) { for (auto deed : deeds) force_give_deed(playerIndex, deed); } void GameState::force_transfer_deed(int fromPlayerIndex, int toPlayerIndex, Property deed) { assert(get_building_level(deed) == 0); auto const countErased = players[fromPlayerIndex].deeds.erase(deed); assert(countErased == 1); auto const insertRet = players[toPlayerIndex].deeds.insert(deed); assert(insertRet.second); if (get_property_is_mortgaged(deed)) { force_subtract_funds(toPlayerIndex, calculate_closing_costs_on_sale (deed)); } } void GameState::force_transfer_deeds(int fromPlayerIndex, int toPlayerIndex, std::set<Property> deeds) { for (auto deed : deeds) force_transfer_deed(fromPlayerIndex, toPlayerIndex, deed); } void GameState::force_set_mortgaged(Property property, bool mortgaged) { if (mortgaged) { mortgagedProperties.insert(property); } else { mortgagedProperties.erase(property); } } void GameState::force_sell_all_buildings(int playerIndex, PropertyGroup group) { auto const properties = properties_in_group(group); for (auto property : properties) { auto &buildingLevel = buildingLevels[property]; auto const ownerIndex = get_property_owner_index(property); assert(ownerIndex != Player::None); if (ownerIndex == Player::None) continue; force_add_funds(ownerIndex, buildingLevel * sell_price_per_house_on_property(property)); if (buildingLevel == HotelLevel) { bank.hotels += 1; } if (buildingLevel < HotelLevel) { bank.houses += buildingLevel; } buildingLevel = 0; } resolve_game_state(); } void GameState::force_add_building(Property property) { auto& buildingLevel = buildingLevels[property]; ++buildingLevel; if (buildingLevel < HotelLevel) { assert(bank.houses > 0); bank.houses -= 1; } if (buildingLevel == HotelLevel) { assert(bank.hotels > 0); bank.hotels -= 1; bank.houses += HotelLevel - 1; } assert(buildingLevel <= HotelLevel); } void GameState::force_remove_building(Property property) { auto& buildingLevel = buildingLevels[property]; if (buildingLevel < HotelLevel) { bank.houses += 1; } if (buildingLevel == HotelLevel) { assert(bank.houses > 0); bank.hotels += 1; bank.houses -= HotelLevel - 1; } --buildingLevel; assert(buildingLevel >= 0); } void GameState::force_set_building_levels(std::map<Property, int> newBuildingLevels) { Property property; int desiredBuildingLevel; for (auto const &pair : newBuildingLevels) { std::tie(property, desiredBuildingLevel) = pair; while (get_building_level(property) > desiredBuildingLevel) { force_remove_building(property); } while (get_building_level(property) < desiredBuildingLevel) { force_add_building(property); } } } void GameState::force_give_get_out_of_jail_free_card(int playerIndex, DeckType deckType) { auto& deck = decks[deckType]; deck.remove_card(get_out_of_jail_free_card(deckType)); players[playerIndex].getOutOfJailFreeCards.insert(deckType); } void GameState::force_transfer_get_out_of_jail_free_card(int fromPlayerIndex, int toPlayerIndex, DeckType deckType) { auto& fromCards = players[fromPlayerIndex].getOutOfJailFreeCards; auto& toCards = players[toPlayerIndex].getOutOfJailFreeCards; if (fromCards.erase(deckType)) toCards.insert(deckType); } void GameState::force_transfer_get_out_of_jail_free_cards(int fromPlayerIndex, int toPlayerIndex, std::set<DeckType> deckTypes) { for (auto deckType : deckTypes) { force_transfer_get_out_of_jail_free_card(fromPlayerIndex, toPlayerIndex, deckType); } } void GameState::force_return_get_out_of_jail_free_card(int playerIndex, DeckType deckType) { auto& player = players[playerIndex]; player.getOutOfJailFreeCards.erase(deckType); decks[deckType].add_card(get_out_of_jail_free_card(deckType)); } void GameState::force_return_get_out_of_jail_free_cards(int playerIndex) { for (auto deckType : { DeckType::CommunityChest, DeckType::Chance }) { force_return_get_out_of_jail_free_card(playerIndex, deckType); } } void GameState::force_bankrupt_by_bank(int debtorPlayerIndex) { auto& debtor = players[debtorPlayerIndex]; for (auto deed : debtor.deeds) { if (get_building_level(deed) > 0) { force_sell_all_buildings(debtorPlayerIndex, property_group(deed)); // selling all at once guarantees tearing down evenly } } for (auto property : debtor.deeds) { propertiesPendingAuction.push(property); } debtor.funds = 0; bank.deeds.insert(debtor.deeds.begin(), debtor.deeds.end()); debtor.deeds.clear(); force_return_get_out_of_jail_free_cards(debtorPlayerIndex); } void GameState::force_bankrupt_by_player(int debtorPlayerIndex, int creditorPlayerIndex) { auto& debtor = players[debtorPlayerIndex]; for (auto deed : debtor.deeds) { if (get_building_level(deed) > 0) { force_sell_all_buildings(debtorPlayerIndex, property_group(deed)); // selling all at once guarantees tearing down evenly } } force_transfer_funds(debtorPlayerIndex, creditorPlayerIndex, debtor.funds); // likely negative force_transfer_deeds(debtorPlayerIndex, creditorPlayerIndex, debtor.deeds); force_transfer_get_out_of_jail_free_cards(debtorPlayerIndex, creditorPlayerIndex); } void GameState::force_property_offer_prompt(int playerIndex, Property property) { std::cout << player_name(playerIndex) << ": Buy " << to_string(property) << " or let it go to auction?" << std::endl; activePlayerIndex = playerIndex; pendingPurchaseDecision = true; resolve_game_state(); } void GameState::force_liquidate_to_pay_bank_prompt(int debtorPlayerIndex, int amount) { std::cout << player_name(debtorPlayerIndex) << ": You are in debt. Manage property or trade to come up with the funds OR declare bankruptcy!" << std::endl; Debt debt; debt.debtor = debtorPlayerIndex; debt.amount = amount; pendingDebtSettlements.push_back(debt); } void GameState::force_liquidate_to_pay_player_prompt(int debtorPlayerIndex, int creditorPlayerIndex, int amount) { std::cout << player_name(debtorPlayerIndex) << ": You are in debt to " << player_name(creditorPlayerIndex) << ". Manage property or trade to come up with the funds OR declare bankruptcy!" << std::endl; Debt debt; debt.debtor = debtorPlayerIndex; debt.amount = amount; debt.creditor = creditorPlayerIndex; pendingDebtSettlements.push_back(debt); } void GameState::force_trade(Trade trade) { force_transfer_promise(trade.offeringPlayer, trade.consideringPlayer, trade.offer); force_transfer_promise(trade.consideringPlayer, trade.offeringPlayer, trade.consideration); // Seems a bit silly that you can trade cash for cash } void GameState::force_transfer_promise(int fromPlayerIndex, int toPlayerIndex, Promise promise) { force_transfer_funds(fromPlayerIndex, toPlayerIndex, promise.cash); force_transfer_deeds(fromPlayerIndex, toPlayerIndex, promise.deeds); force_transfer_get_out_of_jail_free_cards(fromPlayerIndex, toPlayerIndex, promise.getOutOfJailFreeCards); } Player GameState::init_player(GameSetup const& setup) { Player p; p.funds = setup.startingFunds; return p; } std::vector<Player> GameState::init_players(GameSetup const& setup) { return std::vector<Player>(setup.playerCount, init_player(setup)); } Deck GameState::init_deck(GameSetup const& setup, DeckType deck_type) { return Deck(deck_type); } std::map<DeckType, Deck> GameState::init_decks(GameSetup const& setup) { return { { DeckType::Chance, init_deck(setup, DeckType::Chance) }, { DeckType::CommunityChest, init_deck(setup, DeckType::CommunityChest) }, }; } void GameState::resolve_game_state() { if (get_players_remaining_count () < 2) { phase = TurnPhase::GameOver; } else if (pendingTradeAgreement.has_value ()) { phase = TurnPhase::WaitingForTradeOfferResponse; } else if (!pendingDebtSettlements.empty()) { resolve_debt_settlements(); } else if (currentAuction) { resolve_auction(); } else if (pendingAuctionSale.has_value()) { resolve_auction_sale(); } else if (!propertiesPendingAuction.empty()) { resolve_queued_auction(propertiesPendingAuction.front()); } else if (!pendingAcquisitions.empty()) { phase = TurnPhase::WaitingForAcquisitionManagement; } else if (pendingPurchaseDecision) { phase = TurnPhase::WaitingForBuyPropertyInput; } else if (pendingRoll) { phase = TurnPhase::WaitingForRoll; } else if (activePlayerIndex != get_next_player_index ()) { phase = TurnPhase::WaitingForTurnEnd; } } void GameState::resolve_debt_settlements() { assert(! pendingDebtSettlements.empty ()); auto const debt = pendingDebtSettlements.front(); if (players[debt.debtor].funds >= 0) { pendingDebtSettlements.pop_front(); resolve_game_state(); } else { phase = TurnPhase::WaitingForDebtSettlement; } } void GameState::resolve_auction() { auto const highestBidderIndex = currentAuction.biddingOrder.back(); auto const nextBidderIndex = currentAuction.biddingOrder.front(); std::cout << to_string (currentAuction.property) << " going to " << player_name(highestBidderIndex) << " for $" << currentAuction.highestBid << std::endl; phase = TurnPhase::WaitingForBids; if (currentAuction.biddingOrder.size() > 1) { if (check_if_player_is_allowed_to_bid(nextBidderIndex, currentAuction.highestBid + 1)) { std::cout << player_name(nextBidderIndex) << ": Bid or decline?" << std::endl; } else { std::cout << player_name(nextBidderIndex) << " can't afford to bid more than " << currentAuction.highestBid << std::endl; player_action_decline_bid(nextBidderIndex); resolve_game_state(); } } else { std::cout << player_name(highestBidderIndex) << " won the auction of " << to_string(currentAuction.property) << " for $" << currentAuction.highestBid << std::endl; auto const payment = currentAuction.highestBid + calculate_closing_costs_on_sale(currentAuction.property); pendingAuctionSale = { highestBidderIndex, currentAuction.property }; currentAuction = {}; force_subtract_funds(highestBidderIndex, payment); resolve_game_state(); } } void GameState::resolve_auction_sale() { assert(pendingAuctionSale.has_value()); auto const highestBidderIndex = pendingAuctionSale->first; auto const property = pendingAuctionSale->second; assert(pendingDebtSettlements.empty()); if (! players[highestBidderIndex].eliminated) { std::cout << player_name(highestBidderIndex) << " received " << to_string(property) << std::endl; force_give_deed(highestBidderIndex, property); } else { std::cout << player_name(highestBidderIndex) << " won the bid, but declared bankruptcy, " << to_string(property) << " goes back up for auction" << std::endl; propertiesPendingAuction.push(property); } pendingAuctionSale = {}; resolve_game_state(); } void GameState::resolve_queued_auction(Property property) { std::cout << "Auctioning property " << to_string (property) << std::endl; currentAuction = Auction{}; // Determine order of auction for (int i = get_next_player_index(activePlayerIndex); i != activePlayerIndex; i = get_next_player_index(i)) { currentAuction.biddingOrder.push_back(i); } // Active player starts with a bid of 0, so they go last currentAuction.biddingOrder.push_back(activePlayerIndex); currentAuction.highestBid = 0; currentAuction.property = property; propertiesPendingAuction.pop(); resolve_game_state(); }
35.566052
171
0.689222
[ "vector", "transform" ]
34e632f1581d5b32d27a8b284ca08742e9521d35
2,682
cpp
C++
Week1/MTE140-LectureNotes#1-Selection-Sort-Implementation.cpp
ahtchow/mte-140
0dee938d5801544e8f592ee7a81a16bed8bbbf29
[ "BSD-4-Clause-UC" ]
null
null
null
Week1/MTE140-LectureNotes#1-Selection-Sort-Implementation.cpp
ahtchow/mte-140
0dee938d5801544e8f592ee7a81a16bed8bbbf29
[ "BSD-4-Clause-UC" ]
null
null
null
Week1/MTE140-LectureNotes#1-Selection-Sort-Implementation.cpp
ahtchow/mte-140
0dee938d5801544e8f592ee7a81a16bed8bbbf29
[ "BSD-4-Clause-UC" ]
null
null
null
#include <iostream> #include <vector> #include <functional> using namespace std; // TODO: Implement the Selection Sort algorithm from Lecture Notes #1 // By completing this code exercise on your own, you should be able to: // (1) Implement the selection sort algorithm // (2) Pass vectors by reference into functions // (3) Use functions as parameter values in software design // PURPOSE: Swap two elements in a vector that is passed by reference void swap_vector_data(vector<int>& data, unsigned int val1, unsigned int val2) { int temp = data[val1]; data[val1] = data[val2]; data[val2] = temp; } // PURPOSE: Sort the given vector of integers based on specified order // INPUTS: data - vector reference that contains unsorted elements // compare - function comparator that specifies sorting order void selection_sort(vector<int>& data, function<bool(int,int)> compare) { // iterate from first to second-last element for (unsigned int current = 0; current < data.size() - 1; ++current) { // store current index as temporary extreme value unsigned int extreme_index = current; // iterate from the current to last element for (unsigned int index = current; index < data.size(); ++index) { // update extreme_index if new local extreme value is found if (compare(data[extreme_index], data[index])) extreme_index = index; } // swap the current and extreme_index values if needed if (current != extreme_index) swap_vector_data(data, current, extreme_index); } } // PURPOSE: Comparator for ascending sort order bool compare_asc(int val1, int val2) { // if true, the values are not in order return val1 > val2; } // PURPOSE: Comparator for descending sort order bool compare_desc(int val1, int val2) { // if true, the values are not in order return val1 < val2; } // PURPOSE: Run sanity tests for selection_sort() void test_selection_sort() { // initialize vector data vector<int> data; data.push_back(42); data.push_back(3); data.push_back(4); data.push_back(15); data.push_back(2); data.push_back(7); // run the selection sort ascending selection_sort(data, compare_asc); // print results for verification cout << "Selection Sort Test: Ascending Order" << endl; for (auto element : data) { cout << element << endl; } // run the selection sort descending selection_sort(data, compare_desc); // print results for verification cout << endl << endl << "Selection Sort Test: Descending Order" << endl; for (auto element : data) { cout << element << endl; } } int main() { test_selection_sort(); return 0; }
30.827586
81
0.691648
[ "vector" ]
34e9c7df9007ba5a867b60ba9ec13cc65276ed12
5,665
cpp
C++
src/controller/src/mcp23x08.cpp
johnmgreenwell/cpld-alu
5a8c1022d1aedaf551c2ee3efaef6eb39feabdf2
[ "MIT" ]
null
null
null
src/controller/src/mcp23x08.cpp
johnmgreenwell/cpld-alu
5a8c1022d1aedaf551c2ee3efaef6eb39feabdf2
[ "MIT" ]
null
null
null
src/controller/src/mcp23x08.cpp
johnmgreenwell/cpld-alu
5a8c1022d1aedaf551c2ee3efaef6eb39feabdf2
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------- // Name : mcp23x08.cpp // Purpose : MCP23X08 IO-Expander Chip Controller Class // Description : This source file accompanies header file mcp23x08.h // Platform : Multiple // Framework : Arduino // Language : C++ // Copyright : MIT License 2021, John Greenwell //---------------------------------------------------------------------------- #include <Arduino.h> #include <Wire.h> #include <SPI.h> #include "mcp23x08.h" namespace PeripheralIO { MCP23X08::MCP23X08() : _wire(nullptr), _spi(nullptr), _address(0), _cs(0) { } /*! @brief Initialize MCP23X08 using I2C @param address 3 LSB matching device external biasing @param wire I2C object connected to the device */ void MCP23X08::begin(uint8_t address, TwoWire& wire) { _address = MCP23X08_ADDR | (address & 0x07); _wire = &wire; _mcpWrite = &PeripheralIO::MCP23X08::i2cWrite; _mcpRead = &PeripheralIO::MCP23X08::i2cRead; } /*! @brief Initialize MCP23X08 using hardware SPI @param address 2 LSB matching device external biasing @param cs_pin CS pin number @param spi SPI object connected to the device */ void MCP23X08::begin(uint8_t address, uint8_t cs_pin, SPIClass& spi) { _address = (MCP23X08_ADDR << 1) | ((address & 0x03) << 1); _cs = cs_pin; _spi = &spi; _mcpWrite = &PeripheralIO::MCP23X08::spiWrite; _mcpRead = &PeripheralIO::MCP23X08::spiRead; ::pinMode(_cs, OUTPUT); ::digitalWrite(_cs, HIGH); } /*! @brief Set mode for specific pin @param pin Pin to change IO mode @param mode IO Mode (i.e. OUTPUT, INPUT, INPUT_PULLUP) @return Boolean true for completion, false for bad input */ bool MCP23X08::pinMode(uint8_t pin, uint8_t mode) const { uint8_t data = 0; if (pin > 7) return false; data = read(MCP23X08_IODIR); if (mode == INPUT) { data |= (1 << pin); } else if (mode == OUTPUT) { data &= ~(1 << pin); } else if (mode == INPUT_PULLUP){ data |= (1 << pin); write(MCP23X08_GPPU, read(MCP23X08_GPPU) | (1 << pin)); } else { return false; } write(MCP23X08_IODIR, data); return true; } /*! @brief Assign same pin mode to entire GPIO port @param mode IO Mode (i.e. OUTPUT, INPUT, INPUT_PULLUP) */ void MCP23X08::portMode(uint8_t mode) const { if (mode == INPUT) { write(MCP23X08_IODIR, 0xFF); } else if (mode == OUTPUT) { write(MCP23X08_IODIR, 0x00); } else if (mode == INPUT_PULLUP){ write(MCP23X08_GPPU, 0xFF); write(MCP23X08_IODIR, 0xFF); } } /*! @brief Set value for specific pin @param pin Pin to set @param val Logic level (i.e. HIGH, LOW) @result Boolean true for completion, false for bad input */ bool MCP23X08::digitalWrite(uint8_t pin, uint8_t val) const { uint8_t data = 0; if (pin > 7) return false; data = read(MCP23X08_GPIO); data = (val == HIGH) ? (data | 1 << pin) : (data & ~(1 << pin)); write(MCP23X08_GPIO, data); return true; } /*! @brief Read value on specific pin @param pin Pin to read @result Value read */ uint8_t MCP23X08::digitalRead(uint8_t pin) const { if (pin > 7) return 0x00; return ((read(MCP23X08_GPIO) >> pin) & 0x01); } /*! @brief Write to entire GPIO port @param val Value to write to GPIO port */ void MCP23X08::write(uint8_t val) const { write(MCP23X08_OLAT, val); } /*! @brief Write value to specific register @param reg Register to access @param val Value to write to register */ void MCP23X08::write(uint8_t reg, uint8_t val) const { (this->*_mcpWrite)(reg, val); } /*! @brief Read from entire GPIO port @return Value read from GPIO port */ uint8_t MCP23X08::read() const { return read(MCP23X08_GPIO); } /*! @brief Read value from specific register @param reg Register to access @return Value read from register */ uint8_t MCP23X08::read(uint8_t reg) const { return (this->*_mcpRead)(reg); } // Private: Hardware SPI Write Function void MCP23X08::spiWrite(uint8_t reg, uint8_t byte) const { ::digitalWrite(_cs, LOW); _spi->transfer(_address); _spi->transfer(reg); _spi->transfer(byte); ::digitalWrite(_cs, HIGH); } // Private: Hardware SPI Read Function uint8_t MCP23X08::spiRead(uint8_t reg) const { uint8_t data = 0; ::digitalWrite(_cs, LOW); _spi->transfer(_address | 0x01); _spi->transfer(reg); data = _spi->transfer(0); ::digitalWrite(_cs, HIGH); return data; } // Private: Hardware I2C Write Function void MCP23X08::i2cWrite(uint8_t reg, uint8_t byte) const { _wire->beginTransmission(_address); _wire->write(reg); _wire->write(byte); _wire->endTransmission(); } // Private: Hardware I2C Read Function uint8_t MCP23X08::i2cRead(uint8_t reg) const { uint8_t data = 0; _wire->beginTransmission(_address); _wire->write(reg); _wire->endTransmission(0); _wire->requestFrom(_address, (uint8_t)1); if (_wire->available()) data = Wire.read(); _wire->endTransmission(); return data; } // Base Address and Register Defines const uint8_t MCP23X08_ADDR = 0x20; // 7-bit addr const uint8_t MCP23X08_IODIR = 0x00; const uint8_t MCP23X08_IPOL = 0x01; const uint8_t MCP23X08_GPINTEN = 0x02; const uint8_t MCP23X08_DEFVAL = 0x03; const uint8_t MCP23X08_INTCON = 0x04; const uint8_t MCP23X08_IOCON = 0x05; const uint8_t MCP23X08_GPPU = 0x06; const uint8_t MCP23X08_INTF = 0x07; const uint8_t MCP23X08_INTCAP = 0x08; const uint8_t MCP23X08_GPIO = 0x09; const uint8_t MCP23X08_OLAT = 0x0A; }
27.634146
78
0.642012
[ "object" ]
34eefd5cf0e7e38fa4328be2de12feaee9932785
7,125
cpp
C++
src/apps/S3DAnalyzer/worker/videosynchronizer.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
8
2017-04-16T16:38:15.000Z
2020-04-20T03:23:15.000Z
src/apps/S3DAnalyzer/worker/videosynchronizer.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
40
2017-04-12T17:24:44.000Z
2017-12-21T18:41:23.000Z
src/apps/S3DAnalyzer/worker/videosynchronizer.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
6
2017-07-13T21:51:09.000Z
2021-05-18T16:22:03.000Z
#include "videosynchronizer.h" #include "live_capture_device_factory.h" #include <QDebug> #include <QImage> #include <QTimer> #include <s3d/cv/video/stereo_demuxer/stereo_demuxer_cv_side_by_side.h> #include <s3d/cv/video/stereo_demuxer/stereo_demuxer_factory_cv.h> #include <s3d/video/capture/ffmpeg/file_video_capture_device_3d.h> #include <s3d/video/capture/ffmpeg/file_video_capture_device_ffmpeg.h> #include <s3d/video/file_parser/ffmpeg/video_file_parser_ffmpeg.h> #include <s3d/video/stereo_demuxer/stereo_demuxer.h> VideoSynchronizer::VideoSynchronizer() : m_videoCaptureDevice{}, m_stereoDemuxerFactory{std::make_unique<s3d::StereoDemuxerFactoryCV>()} {} gsl::owner<VideoSynchronizer*> VideoSynchronizer::clone() const { return new VideoSynchronizer; } VideoSynchronizer::~VideoSynchronizer() = default; void VideoSynchronizer::resume() { if (m_videoCaptureDevice != nullptr) { m_videoCaptureDevice->Resume(); } } void VideoSynchronizer::pause() { if (m_videoCaptureDevice != nullptr) { m_videoCaptureDevice->MaybeSuspend(); } } void VideoSynchronizer::next() { if (m_videoCaptureDevice != nullptr) { m_videoCaptureDevice->RequestRefreshFrame(); } } void VideoSynchronizer::stop() { if (m_videoCaptureDevice != nullptr) { m_videoCaptureDevice->StopAndDeAllocate(); m_videoLoaded = false; } } void VideoSynchronizer::seekTo(std::chrono::microseconds timestamp) { if (m_videoCaptureDevice != nullptr) { m_videoCaptureDevice->MaybeSeekTo(timestamp); } } std::chrono::microseconds VideoSynchronizer::videoDuration() { return m_videoDuration; } void VideoSynchronizer::OnIncomingCapturedData(const Images& data, const s3d::VideoCaptureFormat& frameFormat, std::chrono::microseconds timestamp) { m_mutex.lock(); if ((m_stereoDemuxer == nullptr && stereoDemuxerRequired()) || stereoFormatChanged()) { updateStereoDemuxer(frameFormat); } auto frameSize = frameFormat.frameSize; // should demux stereo if (m_stereoDemuxer != nullptr && !data.empty()) { m_stereoDemuxer->setSize(frameFormat.frameSize); m_stereoDemuxer->setPixelFormat(frameFormat.pixelFormat); frameSize = m_stereoDemuxer->demuxedSize(); m_stereoDemuxer->demux(data[0], &m_dataLeft, &m_dataRight); // don't need copy, already done in demux m_imageLeft = QImage(m_dataLeft.data(), frameSize.getWidth(), frameSize.getHeight(), QImage::Format_ARGB32); m_imageRight = QImage(m_dataRight.data(), frameSize.getWidth(), frameSize.getHeight(), QImage::Format_ARGB32); } // input in separate images else if (data.size() > 1) { m_imageLeft = QImage(data[0].data(), frameSize.getWidth(), frameSize.getHeight(), QImage::Format_ARGB32) .copy(); m_imageRight = QImage(data[1].data(), frameSize.getWidth(), frameSize.getHeight(), QImage::Format_ARGB32) .copy(); } // no input.. outputing black image else { m_imageLeft = QImage(frameSize.getWidth(), frameSize.getHeight(), QImage::Format::Format_ARGB32); m_imageRight = QImage(frameSize.getWidth(), frameSize.getHeight(), QImage::Format::Format_ARGB32); m_imageLeft.fill(Qt::black); m_imageRight.fill(Qt::black); } m_timestamp = timestamp; m_imagesDirty = true; m_mutex.unlock(); } void VideoSynchronizer::checkForIncomingImage() { bool imagesDirty = false; QImage leftImageCopy, rightImageCopy; { m_mutex.lock(); if (m_imagesDirty) { leftImageCopy = m_imageLeft.copy(); rightImageCopy = m_imageRight.copy(); imagesDirty = true; m_imagesDirty = false; } m_mutex.unlock(); } if (imagesDirty) { // should use Qt::QueuedConnection for minimal time spent in timer callback emit incomingImagePair(leftImageCopy, rightImageCopy, m_timestamp); } } void VideoSynchronizer::setStereoVideoFormat(s3d::Stereo3DFormat format) { m_stereoFormat = format; } void VideoSynchronizer::setLeftFilename(std::string filename) { m_leftFilename = std::move(filename); m_leftFileReady = true; } void VideoSynchronizer::setRightFilename(std::string filename) { m_rightFilename = std::move(filename); m_rightFileReady = true; } void VideoSynchronizer::loadStereoVideo() { loadStereoVideo(m_leftFilename, m_rightFilename, m_stereoFormat); } void VideoSynchronizer::loadStereoVideo(const std::string& leftFile, const std::string& rightFile, s3d::Stereo3DFormat stereoFormat) { // stop the video before loading the next stop(); // reset file state m_leftFileReady = false; m_rightFileReady = false; m_videoLoaded = true; m_liveCamera = false; s3d::VideoFileParserFFmpeg parser(leftFile); s3d::VideoCaptureFormat format; if (!parser.Initialize(&format)) { m_videoLoaded = false; return; } m_videoDuration = parser.VideoDuration(); m_stereoDemuxer = s3d::StereoDemuxerFactoryCV{}.create(stereoFormat, format.frameSize, format.pixelFormat); if (stereoFormat == s3d::Stereo3DFormat::Separate) { m_videoCaptureDevice = std::make_unique<s3d::FileVideoCaptureDevice3D>(leftFile + ";" + rightFile); } else { m_videoCaptureDevice = std::make_unique<s3d::FileVideoCaptureDeviceFFmpeg>(leftFile); } m_timer = createAndStartTimer(); s3d::VideoCaptureFormat suggestedFormat{{}, -1, s3d::VideoPixelFormat::BGRA}; m_videoCaptureDevice->AllocateAndStart(suggestedFormat, this); // start paused m_videoCaptureDevice->MaybeSuspend(); m_videoCaptureDevice->RequestRefreshFrame(); } std::unique_ptr<QTimer> VideoSynchronizer::createAndStartTimer() { auto timer = std::make_unique<QTimer>(this); timer->setTimerType(Qt::PreciseTimer); connect(timer.get(), SIGNAL(timeout()), this, SLOT(checkForIncomingImage())); timer->start(10); return timer; } bool VideoSynchronizer::isVideoLoaded() { return m_videoLoaded; } bool VideoSynchronizer::stereoFormatChanged() { return m_stereoDemuxer != nullptr && m_stereoDemuxer->getStereoFormat() != m_stereoFormat; } void VideoSynchronizer::updateStereoDemuxer(const s3d::VideoCaptureFormat& format) { m_stereoDemuxer = m_stereoDemuxerFactory->create(m_stereoFormat, format.frameSize, format.pixelFormat); } bool VideoSynchronizer::stereoDemuxerRequired() { return m_stereoFormat != s3d::Stereo3DFormat::Separate && !m_liveCamera; } bool VideoSynchronizer::isVideoReadyToLoad() { if (m_stereoFormat == s3d::Stereo3DFormat::Separate) { return m_leftFileReady && m_rightFileReady; } return m_leftFileReady; } void VideoSynchronizer::loadLiveCamera() { // stop the currently playing video stop(); m_liveCamera = true; m_videoCaptureDevice = LiveCaptureDeviceFactory{}.create(); // 1280x720, 60fps, BGRA, 2D or 3D supported s3d::VideoCaptureFormat format = m_videoCaptureDevice->DefaultFormat(); format.stereo3D = true; m_timer = createAndStartTimer(); m_videoCaptureDevice->AllocateAndStart(format, this); }
30.448718
103
0.718737
[ "3d" ]
34f107afdd3953541663587d20a555d6e16ea45f
3,546
cc
C++
src/unittest/test_memory.cc
sylvainbouxin/MiyukiRenderer
88242b9e18ca7eaa1c751ab07f585fac8b591b5a
[ "MIT" ]
null
null
null
src/unittest/test_memory.cc
sylvainbouxin/MiyukiRenderer
88242b9e18ca7eaa1c751ab07f585fac8b591b5a
[ "MIT" ]
null
null
null
src/unittest/test_memory.cc
sylvainbouxin/MiyukiRenderer
88242b9e18ca7eaa1c751ab07f585fac8b591b5a
[ "MIT" ]
1
2019-09-11T20:20:54.000Z
2019-09-11T20:20:54.000Z
// // Created by Shiina Miyuki on 2019/2/3. // #include "../core/memory.h" #include "../core/util.h" #define BOOST_AUTO_TEST_MAIN #define BOOST_TEST_MODULE TestMemory #include <boost/test/unit_test.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/filesystem/fstream.hpp> namespace utf = boost::unit_test; using namespace Miyuki; BOOST_AUTO_TEST_CASE(Benchmark) { MemoryArena arena; const int N = 1000000; for (size_t s = 16; s <= 1024; s *= 2) { auto t = runtime([&]() { for (int i = 0; i < N; i++) { arena.alloc(s); } }); arena.reset(); fmt::print("{}bytes {}M\n", s, N / t / 1e6); } } struct MemoryRegion { uint8_t *head; size_t size; bool noOverlap(const MemoryRegion &rhs) const { return rhs.head >= head + size || head >= rhs.head + rhs.size; } void write() const { for (size_t i = 0; i < size; i++) { head[i] = 0xcc; } } }; BOOST_AUTO_TEST_CASE(Big) { MemoryArena arena; const int N = 100; size_t s = 1024 * 1024; { std::vector<MemoryRegion> regions; for (int i = 0; i < N; i++) { MemoryRegion region; region.head = arena.alloc<uint8_t>(s); region.size = s; region.write(); regions.emplace_back(region); } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (!regions[i].noOverlap(regions[j])) { BOOST_ERROR("Ouch..."); } } } } } BOOST_AUTO_TEST_CASE(TestOverlapSmall) { MemoryArena arena; const int N = 100; size_t s = 4; { std::vector<MemoryRegion> regions; for (int i = 0; i < N; i++) { MemoryRegion region; region.head = arena.alloc<uint8_t>(s); region.size = s; region.write(); regions.emplace_back(region); } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (!regions[i].noOverlap(regions[j])) { BOOST_ERROR("Ouch..."); } } } } } BOOST_AUTO_TEST_CASE(TestOverlap) { MemoryArena arena; const int N = 100; for (size_t s = 16; s <= 1024; s *= 2) { std::vector<MemoryRegion> regions; for (int i = 0; i < N; i++) { MemoryRegion region; region.head = arena.alloc<uint8_t>(s); region.size = s; region.write(); regions.emplace_back(region); } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (!regions[i].noOverlap(regions[j])) { BOOST_ERROR("Ouch..."); } } } } } BOOST_AUTO_TEST_CASE(TestOverlapReset) { MemoryArena arena; const int N = 100; for (size_t s = 16; s <= 1024; s *= 2) { std::vector<MemoryRegion> regions; for (int i = 0; i < N; i++) { MemoryRegion region; region.head = arena.alloc<uint8_t>(s); region.size = s; region.write(); regions.emplace_back(region); } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (!regions[i].noOverlap(regions[j])) { BOOST_ERROR("Ouch..."); } } } arena.reset(); } }
24.797203
70
0.467569
[ "vector" ]
34f453dcdf0a2d7f36c1d60ee08aef1c59c82687
9,910
tpp
C++
core/src/utility/python_utility.tpp
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
17
2018-11-25T19:29:34.000Z
2021-09-20T04:46:22.000Z
core/src/utility/python_utility.tpp
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
1
2020-11-12T15:15:58.000Z
2020-12-29T15:29:24.000Z
core/src/utility/python_utility.tpp
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
4
2018-10-17T12:18:10.000Z
2021-05-28T13:24:20.000Z
#include "utility/python_utility.h" #include <Python.h> #include "easylogging++.h" #include <fstream> #include <iostream> #include <iomanip> #include <algorithm> #include <array> #include "utility/vector_operators.h" #include "control/python_config/settings_file_name.h" template<typename Key, typename Value> std::pair<Key, Value> PythonUtility::getOptionDictBegin(const PyObject *settings, std::string keyString, std::string pathString) { std::pair<Key, Value> firstEntry; if (settings && PyDict_Check(settings)) { // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; // check if input dictionary contains the key PyObject *key = PyUnicode_FromString(keyString.c_str()); if (PyDict_Contains((PyObject *)settings, key)) { //PythonUtility::printDict((PyObject *)settings); PyObject *dict = PyDict_GetItem((PyObject *)settings, key); if (PyDict_Check(dict)) { Py_CLEAR(key); Py_CLEAR(itemList); itemList = PyDict_Items(dict); itemListIndex = 0; if (PyList_Check(itemList)) { if (itemListIndex < PyList_Size(itemList)) { PyObject *tuple = PyList_GetItem(itemList, (Py_ssize_t)itemListIndex); PyObject *tuple_key = PyTuple_GetItem(tuple, (Py_ssize_t)0); PyObject *tuple_value = PyTuple_GetItem(tuple, (Py_ssize_t)1); firstEntry = std::pair<Key, Value>(convertFromPython<Key>::get(tuple_key), convertFromPython<Value>::get(tuple_value)); return firstEntry; } } else { LOG(WARNING) << pathString << "[\"" << keyString << "\"] is not a dict"; } } else { LOG(WARNING) << "Entry " << pathString << "[\"" << keyString << "\"] is not a dict."; } } else { LOG(WARNING) << pathString << "[\"" << keyString << "\"] not set in \"" << Control::settingsFileName << "\"" << std::endl; } } return firstEntry; } template<typename Key, typename Value> void PythonUtility::getOptionDictNext(const PyObject *settings, std::string keyString, std::string pathString, std::pair<Key, Value> &nextPair) { itemListIndex++; // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; if (itemListIndex < PyList_Size(itemList)) { PyObject *tuple = PyList_GetItem(itemList, (Py_ssize_t)itemListIndex); PyObject *key = PyTuple_GetItem(tuple, (Py_ssize_t)0); PyObject *value = PyTuple_GetItem(tuple, (Py_ssize_t)1); nextPair = std::pair<Key, Value>(convertFromPython<Key>::get(key), convertFromPython<Value>::get(value)); } } template<typename Value> Value PythonUtility::getOptionListBegin(const PyObject *settings, std::string keyString, std::string pathString) { if (settings && PyDict_Check(settings)) { // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; // check if input dictionary contains the key PyObject *key = PyUnicode_FromString(keyString.c_str()); if (PyDict_Contains((PyObject *)settings, key)) { // check if it is a list list = PyDict_GetItem((PyObject *)settings, key); if (PyList_Check(list)) { listIndex = 0; if (listIndex < PyList_Size(list)) { PyObject *item = PyList_GetItem(list, (Py_ssize_t)listIndex); Py_CLEAR(key); return convertFromPython<Value>::get(item); } } else { LOG(WARNING) << "" << pathString << "[\"" << keyString << "\"] is not a list!"; Py_CLEAR(key); return convertFromPython<Value>::get(list); } } else { LOG(WARNING) << pathString << "[\"" << keyString << "\"] not found in config file."; } Py_CLEAR(key); } return Value(); } template<typename Value> void PythonUtility::getOptionListNext(const PyObject *settings, std::string keyString, std::string pathString, Value &value) { listIndex++; // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; if (listIndex < PyList_Size(list)) { PyObject *item = PyList_GetItem(list, (Py_ssize_t)listIndex); value = convertFromPython<Value>::get(item); } } template<typename ValueType, int D> std::array<ValueType, D> PythonUtility::getOptionArray(PyObject* settings, std::string keyString, std::string pathString, ValueType defaultValue, ValidityCriterion validityCriterion) { std::array<ValueType,(int)D> defaultValueArray = {}; defaultValueArray.fill(defaultValue); return PythonUtility::getOptionArray<ValueType,D>(settings, keyString, pathString, defaultValueArray, validityCriterion); } template<typename ValueType, int D> std::array<ValueType, D> PythonUtility::getOptionArray(PyObject* settings, std::string keyString, std::string pathString, std::array<ValueType, D> defaultValue, ValidityCriterion validityCriterion) { std::array<ValueType, D> result = defaultValue; if (!settings || !PyDict_Check(settings)) { return result; } if (settings) { // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; // check if input dictionary contains the key PyObject *key = PyUnicode_FromString(keyString.c_str()); if (PyDict_Contains((PyObject *)settings, key)) { // extract the value of the key and check its type PyObject *value = PyDict_GetItem((PyObject *)settings, key); // if the value is `None`, use default value if (value == Py_None) { result = defaultValue; } else { result = PythonUtility::convertFromPython<std::array<ValueType,D>>::get(value, defaultValue); } } else { LOG(WARNING) << pathString << "[\"" << keyString << "\"] not found in config, assuming default values " << defaultValue << "."; Py_CLEAR(key); return defaultValue; } Py_CLEAR(key); } switch(validityCriterion) { case PythonUtility::Positive: for (int i=0; i<D; i++) { if (result[i] <= 0.0) { LOG(WARNING) << "Value " <<result[i]<< " of " << pathString << "[\"" << keyString << "\"] is invalid (not positive). Using default value " << defaultValue[i]<< "."; result[i] = defaultValue[i]; } } case PythonUtility::NonNegative: for (int i=0; i<D; i++) { if (result[i] < 0.0) { LOG(WARNING) << "Value " <<result[i]<< " of " << pathString << "[\"" << keyString << "\"] is invalid (not non-negative). Using default value " << defaultValue[i]<< "."; result[i] = defaultValue[i]; } } break; case PythonUtility::Between1And3: for (int i=0; i<D; i++) { if (result[i] < 1.0 || result[i] > 3.0) { LOG(WARNING) << "Value " <<result[i]<< " of " << pathString << "[\"" << keyString << "\"] is invalid (not between 1 and 3). Using default value " << defaultValue[i]<< "."; result[i] = defaultValue[i]; } } break; case PythonUtility::None: break; }; return result; } template<typename ValueType> void PythonUtility::getOptionVector(const PyObject *settings, std::string keyString, std::string pathString, std::vector<ValueType> &values) { if (settings) { // check if input dictionary contains the key PyObject *key = PyUnicode_FromString(keyString.c_str()); if (PyDict_Contains((PyObject *)settings, key)) { // extract the value of the key and check its type PyObject *value = PyDict_GetItem((PyObject *)settings, key); if (PyList_Check(value)) { // it is a list int listNEntries = PyList_Size(value); // do nothing if it is an empty list if (listNEntries == 0) return; // get the first value from the list ValueType currentValue = PythonUtility::getOptionListBegin<ValueType>(settings, keyString, pathString); // loop over other values for (; !PythonUtility::getOptionListEnd(settings, keyString, pathString); PythonUtility::getOptionListNext<ValueType>(settings, keyString, pathString, currentValue)) { values.push_back(currentValue); } values = convertFromPython<std::vector<ValueType>>::get(value); } else { // Convert using the convertFromPython helper. This is less efficient because the vector gets copied. values = convertFromPython<std::vector<ValueType>>::get(value); } } else { LOG(WARNING) << "" << pathString << "[\"" << keyString << "\"] not set in \"" << Control::settingsFileName << "\". Assuming vector " << values; } Py_CLEAR(key); } } template<int D> PyObject *PythonUtility::convertToPythonList(std::array<long,D> &data) { // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; PyObject *result = PyList_New((Py_ssize_t)D); for (unsigned int i=0; i<D; i++) { PyObject *item = PyLong_FromLong(data[i]); PyList_SetItem(result, (Py_ssize_t)i, item); // steals reference to item } return result; // return value: new reference } template<int D> PyObject *PythonUtility::convertToPythonList(std::array<bool,D> &data) { // start critical section for python API calls // PythonUtility::GlobalInterpreterLock lock; PyObject *result = PyList_New((Py_ssize_t)D); for (unsigned int i=0; i<D; i++) { PyObject *item = (data[i]? Py_True : Py_False); PyList_SetItem(result, (Py_ssize_t)i, item); // steals reference to item } return result; // return value: new reference }
30.776398
154
0.625025
[ "vector" ]
34f82b6c5caf3c11c712c5f6a8e2ceace6f33199
11,743
hpp
C++
chaste/TestCrumbPredictions.hpp
CardiacModelling/PyHillFit
91a9b5dd3a9455dbf0f3a2ea4785402925fab26b
[ "BSD-3-Clause" ]
9
2016-11-21T13:38:59.000Z
2021-11-16T04:03:57.000Z
chaste/TestCrumbPredictions.hpp
CardiacModelling/PyHillFit
91a9b5dd3a9455dbf0f3a2ea4785402925fab26b
[ "BSD-3-Clause" ]
1
2017-02-27T23:11:54.000Z
2017-07-31T17:55:25.000Z
chaste/TestCrumbPredictions.hpp
CardiacModelling/PyHillFit
91a9b5dd3a9455dbf0f3a2ea4785402925fab26b
[ "BSD-3-Clause" ]
2
2020-04-06T11:45:05.000Z
2020-12-17T16:50:04.000Z
/* Copyright (c) 2005-2016, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef TESTCRUMBPREDICTIONS_HPP_ #define TESTCRUMBPREDICTIONS_HPP_ // Includes first #include <cxxtest/TestSuite.h> #include <boost/assign.hpp> // Standard Chaste classes #include "FileFinder.hpp" // ApPredict bolt-on project classes #include "SingleActionPotentialPrediction.hpp" #include "SetupModel.hpp" // This project classes. #include "CrumbDataReader.hpp" #include "CrumbDrugList.hpp" // Should always be last #include "PetscSetupAndFinalize.hpp" class TestCrumbPredictions : public CxxTest::TestSuite { public: void TestCrumbDrugListReader(void) throw(Exception) { FileFinder file("projects/ApPredict/test/drug_list.txt", RelativeTo::ChasteSourceRoot); if (!file.Exists()) { EXCEPTION("Data files are missing."); } CrumbDrugList drug_list(file); TS_ASSERT_EQUALS(drug_list.GetNumDrugs(), 30u); TS_ASSERT_EQUALS(drug_list.GetDrugName(0u), "Amiodarone"); TS_ASSERT_EQUALS(drug_list.GetDrugName(18u), "Propafenone"); TS_ASSERT_EQUALS(drug_list.GetDrugName(29u), "Verapamil"); TS_ASSERT_EQUALS(drug_list.GetRiskCategory("Dofetilide") , HIGH); TS_ASSERT_EQUALS(drug_list.GetRiskCategory("Terfenadine"), INTERMEDIATE); TS_ASSERT_EQUALS(drug_list.GetRiskCategory("Ranolazine") , LOW); TS_ASSERT_DELTA(drug_list.GetClinicalDose("Dofetilide") , 0.0021, 1e-9); TS_ASSERT_DELTA(drug_list.GetClinicalDose("Terfenadine"), 0.0003, 1e-9); TS_ASSERT_DELTA(drug_list.GetClinicalDose("Ranolazine") , 1.9482, 1e-9); } void TestApdPredictionsForCrumbData() throw (Exception) { const unsigned num_samples = 500u; unsigned num_params = 2u; // Load up the drug data FileFinder file("projects/ApPredict/test/drug_list.txt", RelativeTo::ChasteSourceRoot); if (!file.Exists()) { std::cout << "Data file not available." << std::endl; return; } CrumbDrugList drug_list(file); // Channel names in the Crumb paper and derived data files std::vector<std::string> channels = boost::assign::list_of("hERG") ("Nav1.5-peak")("Nav1.5-late")("Cav1.2")("KvLQT1_mink")("Kv4.3")("Kir2.1"); // Corresponding channel names for the ApPredict arguments std::vector<std::string> ap_predict_channels = boost::assign::list_of ("membrane_rapid_delayed_rectifier_potassium_current_conductance") ("membrane_fast_sodium_current_conductance") ("membrane_persistent_sodium_current_conductance") ("membrane_L_type_calcium_current_conductance") ("membrane_slow_delayed_rectifier_potassium_current_conductance") ("membrane_fast_transient_outward_current_conductance") ("membrane_inward_rectifier_potassium_current_conductance"); unsigned model_idx = 6u; // ApPredict code for O'Hara endo model. std::stringstream output_folder; output_folder << "CrumbDataStudy_num_params_" << num_params << "_num_samples_" << num_samples; // Set up an output directory - must be called collectively. boost::shared_ptr<OutputFileHandler> p_base_handler(new OutputFileHandler(output_folder.str(), false)); // Don't wipe the folder, we might be re-running one drug! PetscTools::Barrier("Output folder created"); // Shouldn't be needed but seemed to avoid an error! std::cout << "\n\nOutput folder created, apparently.\n\n"; // Everyone does their own thing now... PetscTools::IsolateProcesses(true); // They all need their own working directory to do CellML conversion in... output_folder << "/" << PetscTools::GetMyRank(); std::cout << "\n\noutput_folder: " << output_folder << "\n\n"; // Loop over each compound for (unsigned drug_idx = 0; drug_idx<drug_list.GetNumDrugs(); drug_idx++) { const std::string drug_name = drug_list.GetDrugName(drug_idx); double concentration = drug_list.GetClinicalDose(drug_name); // If we are running in parallel share out the drugs between processes. if (drug_idx % PetscTools::GetNumProcs() != PetscTools::GetMyRank()) { // Let another processor do this drug continue; } SetupModel setup(1.0, 6u); // Use an O'Hara model boost::shared_ptr<AbstractCvodeCell> p_model = setup.GetModel(); // Run to steady state and record state variables SteadyStateRunner steady_runner(p_model); steady_runner.RunToSteadyState(); N_Vector steady_state_variables = p_model->GetStateVariables(); // Not all of the models have a distinct fast I_to component. // In this case we look for the complete I_to current instead. if (!p_model->HasParameter("membrane_fast_transient_outward_current_conductance") && p_model->HasParameter("membrane_transient_outward_current_conductance") ) { WARNING(p_model->GetSystemName() << " does not have 'membrane_fast_transient_outward_current_conductance' labelled, using combined Ito (fast and slow) instead..."); ap_predict_channels[5u] = "membrane_transient_outward_current_conductance"; } // Record the default conductances for scaling purposes. c_vector<double, 7u> default_conductances; for (unsigned channel_idx = 0u; channel_idx<channels.size(); channel_idx++) { if (p_model->HasParameter(ap_predict_channels[channel_idx])) { default_conductances[channel_idx] = p_model->GetParameter(ap_predict_channels[channel_idx]); } else { WARN_ONCE_ONLY("Model " << p_model->GetSystemName() << " doesn't have '" << ap_predict_channels[channel_idx] << "' labelled, simulations ran without blocking it."); } } // Work out the name and open a log file std::cout << "COMPOUND = " << drug_name << std::endl; std::stringstream output_name; output_name << drug_name << "_apd90_results_num_params_" << num_params << ".dat"; out_stream p_file = p_base_handler->OpenOutputFile(output_name.str()); *p_file << "Sample\tConc(uM)\tAPD90(ms)\tAPD50(ms)\tCaMax(mM)\tCaMin(mM)" << std::endl; // Read in all the data for this compound at once std::vector<CrumbDataReader> data_readers; // One for each channel... for (unsigned channel_idx = 0; channel_idx < channels.size(); channel_idx++) { std::stringstream file_path; file_path << "projects/ApPredict/test/samples/" << drug_name << "_" << channels[channel_idx] << "_hill_pic50_samples.txt"; FileFinder drug_file_name(file_path.str(), RelativeTo::ChasteSourceRoot); CrumbDataReader data_reader(drug_file_name, num_params); data_readers.push_back(data_reader); } // Iterate over the dose-response samples of their probability distributions for (unsigned sample = 0; sample < num_samples; sample++) { // Add some sample drug pIC50 and Hill coefficient for this sample for (unsigned channel_idx = 0; channel_idx < channels.size(); channel_idx++) { if (p_model->HasParameter(ap_predict_channels[channel_idx])) { double ic50 = AbstractDataStructure::ConvertPic50ToIc50(data_readers[channel_idx].GetPic50Sample(sample)); double conductance_scaling_factor = AbstractDataStructure::CalculateConductanceFactor(concentration, // Hill ic50, // IC50 data_readers[channel_idx].GetHillSample(sample)); // Hill p_model->SetParameter(ap_predict_channels[channel_idx],default_conductances[channel_idx]*conductance_scaling_factor); std::cout << drug_name << "\tConc = " << concentration << " uM\t" << channels[channel_idx] << "\tpIC50 = " << data_readers[channel_idx].GetPic50Sample(sample) << "\tHill = " << data_readers[channel_idx].GetHillSample(sample) << "\tscaling = " << conductance_scaling_factor << std::endl; } } // Just run a helper method around the usual options (from ApPredict) SingleActionPotentialPrediction ap_runner(p_model); ap_runner.SuppressOutput(); ap_runner.SetMaxNumPaces(1000u); ap_runner.RunSteadyPacingExperiment(); if (!ap_runner.DidErrorOccur()) { *p_file << sample << "\t" << concentration << "\t" << ap_runner.GetApd90() << "\t" << ap_runner.GetApd50() << "\t" << ap_runner.GetCaMax() << "\t" << ap_runner.GetCaMin() << std::endl; } else { *p_file << sample << "\t" << concentration << "\t" << ap_runner.GetErrorMessage() << std::endl; p_model->SetStateVariables(steady_state_variables); } } p_file->close(); DeleteVector(steady_state_variables); } PetscTools::IsolateProcesses(false); std::cout << "Run complete." << std::endl; } }; #endif // TESTCRUMBPREDICTIONS_HPP_
48.127049
204
0.631355
[ "vector", "model" ]
5a606a14f5fa06c3087fe612d831f1f8fea67650
2,618
cpp
C++
src/registrar/registrar.cpp
MrQuasar173/CATNET
ba6f5ab18241ec141cd078615df54e3aaf90558b
[ "MIT" ]
2
2021-04-13T03:41:05.000Z
2021-07-12T21:46:40.000Z
src/registrar/registrar.cpp
MrQuasar173/CATNET
ba6f5ab18241ec141cd078615df54e3aaf90558b
[ "MIT" ]
null
null
null
src/registrar/registrar.cpp
MrQuasar173/CATNET
ba6f5ab18241ec141cd078615df54e3aaf90558b
[ "MIT" ]
null
null
null
#include "registrar.hpp" #include <message.hpp> #include <tcp_socket.hpp> #include <tcp_server_socket.hpp> #include <tcp_socket.hpp> #include <thread> #include <base.pb.h> #include <encrypt.hpp> #include <log.hpp> #include <message.hpp> #include <vector> #include "../message/include/message.hpp" #include "../message/include/encrypt.hpp" #include "../logging/include/log.hpp" #include <vector> using namespace Registrar; RegistrarState::RegistrarState() { CND_DAEMON_TRACE("Constructing registrar...."); // NOTICE: threads will be implemented when it is neccicary for the // registrar to do multiple things at once. Currently, all the registrar // needs to do is connect to a wasker and inform it that it has connected // this section will also deal with storing participant info with JSON in the future tcp_init(); } void RegistrarState::tcp_init() { CND_DAEMON_TRACE("Creating tcp server socket for registrar..."); s_server.emplace("localhost", 44400); } void RegistrarState::run() { CND_DAEMON_TRACE("Running in registrar mode...."); if (!s_server.has_value()) { tcp_init(); } CND_DAEMON_TRACE("Listening for connections from participants..."); while (true) { s_server->acceptConnection(); if (s_server->isConnected()) { CND_DAEMON_TRACE("Connected to a participant!"); // Call offshoot function CND_DAEMON_TRACE( "Sending test message to confirm connection with participant..."); confirm_connection(); } } } void RegistrarState::confirm_connection() { std::vector<unsigned char> recieved_message{}; if (!s_server->receiveData(&recieved_message)){ CND_DAEMON_TRACE("No test message was recieved from participant."); return; } base::Message recieved_deserialized; deserialize_vector_to_message(recieved_deserialized, recieved_message); CND_DAEMON_TRACE("Test message recieved, replying..."); // TODO: find somewhere to dump/desplay the newly deserialized test message from the participant std::vector<unsigned char> serialized_message; base::Message test = create_test_message(); CND_DAEMON_TRACE("Serializing test message"); if (! serialize_message_to_vector(&test, &serialized_message)) { CND_DAEMON_TRACE("Test message serialization failed."); return; } if (!s_server->sendData(&serialized_message)) { CND_DAEMON_TRACE("Message was sucessfully serialized, but failed to send"); return; } else { CND_DAEMON_TRACE("Message sent!"); } } RegistrarState::~RegistrarState() { CND_DAEMON_TRACE("Destructing registrar...."); }
26.714286
100
0.71505
[ "vector" ]
5a6d5d3933aa474fc06ab0a0cdaca7b75fd9e5a6
32,841
cpp
C++
src/core/core.cpp
dtcxzyw/animgui
0e99e4302fc08d8085ef1fdf55d380a79c04373b
[ "MIT" ]
2
2021-07-14T05:52:26.000Z
2021-12-28T13:39:32.000Z
src/core/core.cpp
dtcxzyw/animgui
0e99e4302fc08d8085ef1fdf55d380a79c04373b
[ "MIT" ]
null
null
null
src/core/core.cpp
dtcxzyw/animgui
0e99e4302fc08d8085ef1fdf55d380a79c04373b
[ "MIT" ]
2
2022-01-01T06:03:11.000Z
2022-02-17T07:36:46.000Z
// SPDX-License-Identifier: MIT #include <animgui/builtins/styles.hpp> #include <animgui/core/animator.hpp> #include <animgui/core/canvas.hpp> #include <animgui/core/command_optimizer.hpp> #include <animgui/core/context.hpp> #include <animgui/core/font_backend.hpp> #include <animgui/core/image_compactor.hpp> #include <animgui/core/input_backend.hpp> #include <animgui/core/statistics.hpp> #include <animgui/core/style.hpp> #include <cmath> #include <cstring> #include <list> #include <optional> #include <random> #include <set> #include <stack> namespace animgui { class state_manager final { std::pmr::unordered_map<identifier, std::pair<size_t, size_t>, identifier_hasher> m_state_location; class state_buffer final { size_t m_state_size, m_alignment; raw_callback m_ctor, m_dtor; std::pmr::memory_resource* m_memory_resource; void* m_buffer; size_t m_buffer_size, m_allocated_size; public: state_buffer(std::pmr::memory_resource* memory_resource, const size_t size, const size_t alignment, const raw_callback ctor, const raw_callback dtor) : m_state_size{ size }, m_alignment{ alignment }, m_ctor{ ctor }, m_dtor{ dtor }, m_memory_resource{ memory_resource }, m_buffer{ nullptr }, m_buffer_size{ 0 }, m_allocated_size{ 0 } {} ~state_buffer() { if(m_buffer) { m_dtor(m_buffer, m_buffer_size); m_memory_resource->deallocate(m_buffer, m_buffer_size * m_state_size, m_alignment); } } state_buffer(const state_buffer& rhs) = delete; state_buffer(state_buffer&& rhs) noexcept : m_state_size{ rhs.m_state_size }, m_alignment{ rhs.m_alignment }, m_ctor{ rhs.m_ctor }, m_dtor{ rhs.m_dtor }, m_memory_resource{ rhs.m_memory_resource }, m_buffer{ rhs.m_buffer }, m_buffer_size{ rhs.m_buffer_size }, m_allocated_size{ rhs.m_allocated_size } { rhs.m_buffer = nullptr; rhs.m_allocated_size = rhs.m_buffer_size = 0; } state_buffer& operator=(const state_buffer& rhs) = delete; state_buffer& operator=(state_buffer&& rhs) noexcept { state_buffer tmp{ std::move(rhs) }; swap(tmp); return *this; } void swap(state_buffer& rhs) noexcept { std::swap(m_state_size, rhs.m_state_size); std::swap(m_alignment, rhs.m_alignment); std::swap(m_ctor, rhs.m_ctor); std::swap(m_memory_resource, rhs.m_memory_resource); std::swap(m_buffer, rhs.m_buffer); std::swap(m_buffer_size, rhs.m_buffer_size); std::swap(m_allocated_size, rhs.m_allocated_size); } size_t new_storage() { if(m_buffer_size == m_allocated_size) { const auto new_size = std::max(static_cast<size_t>(128), m_allocated_size * 2); const auto new_ptr = m_memory_resource->allocate(new_size * m_state_size, m_alignment); memcpy(new_ptr, m_buffer, m_buffer_size * m_state_size); m_memory_resource->deallocate(m_buffer, m_allocated_size * m_state_size, m_alignment); m_allocated_size = new_size; m_buffer = new_ptr; } const auto idx = m_buffer_size; m_ctor(locate(idx), 1); ++m_buffer_size; return idx; } [[nodiscard]] void* locate(const size_t idx) const noexcept { return static_cast<std::byte*>(m_buffer) + idx * m_state_size; } }; std::pmr::unordered_map<size_t, state_buffer> m_state_storage; public: explicit state_manager(std::pmr::memory_resource* memory_resource) : m_state_location{ memory_resource }, m_state_storage{ memory_resource } {} void reset() { m_state_location.clear(); m_state_storage.clear(); } void* storage(const size_t hash, const identifier uid) { const auto iter = m_state_location.find(uid); if(iter == m_state_location.cend()) { auto&& buffer = m_state_storage.find(hash)->second; size_t idx = buffer.new_storage(); m_state_location.emplace(uid, std::make_pair(hash, idx)); return buffer.locate(idx); } if(iter->second.first != hash) throw std::logic_error("hash collision"); return m_state_storage.find(hash)->second.locate(iter->second.second); } void register_type(const size_t hash, size_t size, size_t alignment, raw_callback ctor, raw_callback dtor) { if(!m_state_storage.count(hash)) m_state_storage.emplace( std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(m_state_storage.get_allocator().resource(), size, alignment, ctor, dtor)); } }; struct region_info final { size_t push_command_idx; identifier uid; std::minstd_rand random_engine; bounds_aabb absolute_bounds; vec2 offset; region_info() = delete; }; class canvas_impl final : public canvas { context& m_context; vec2 m_size; float m_delta_t; input_backend& m_input_backend; step_function m_step_function; emitter& m_emitter; state_manager& m_state_manager; std::pmr::memory_resource* m_memory_resource; input_mode m_input_mode; std::pmr::vector<operation> m_commands; std::pmr::deque<region_info> m_region_stack; size_t m_animation_state_hash; std::pmr::vector<std::pair<identifier, vec2>> m_focusable_region; public: canvas_impl(context& context, const vec2 size, const float delta_t, input_backend& input, animator& animator, emitter& emitter, state_manager& state_manager, std::pmr::memory_resource* memory_resource) : m_context{ context }, m_size{ size }, m_delta_t{ delta_t }, m_input_backend{ input }, m_step_function{ animator.step(delta_t) }, m_emitter{ emitter }, m_state_manager{ state_manager }, m_memory_resource{ memory_resource }, m_input_mode{ m_input_backend.get_input_mode() }, m_commands{ m_memory_resource }, m_region_stack{ m_memory_resource }, m_animation_state_hash{ 0 }, m_focusable_region{ memory_resource } { const auto [hash, state_size, alignment] = animator.state_storage(); m_animation_state_hash = hash; m_state_manager.register_type( hash, state_size, alignment, [](void*, size_t) {}, [](void*, size_t) {}); m_region_stack.push_back({ std::numeric_limits<size_t>::max(), identifier{ 0 }, std::minstd_rand{}, // NOLINT(cert-msc51-cpp) bounds_aabb{ 0.0f, size.x, 0.0f, size.y }, { 0.0f, 0.0f } }); } [[nodiscard]] const style& global_style() const noexcept override { return m_context.global_style(); } [[nodiscard]] void* raw_storage(const size_t hash, const identifier uid) override { return m_state_manager.storage(hash, uid); } span<operation> commands() noexcept override { return { m_commands.data(), m_commands.data() + m_commands.size() }; } [[nodiscard]] vec2 reserved_size() const noexcept override { for(auto iter = m_region_stack.rbegin(); iter != m_region_stack.rend(); ++iter) { const auto idx = iter->push_command_idx; if(idx == std::numeric_limits<size_t>::max()) break; if(const auto size = std::get<op_push_region>(m_commands[idx]).bounds.size(); size.x > 0.0f && size.y > 0.0f) return size; } return m_size; } void register_type(const size_t hash, const size_t size, const size_t alignment, const raw_callback ctor, const raw_callback dtor) override { m_state_manager.register_type(hash, size, alignment, ctor, dtor); } void pop_region(const std::optional<bounds_aabb>& bounds) override { m_commands.push_back(op_pop_region{}); const auto& info = m_region_stack.back(); const auto idx = info.push_command_idx; const auto uid = info.uid; m_region_stack.pop_back(); auto&& current_bounds = std::get<op_push_region>(m_commands[idx]).bounds; if(bounds.has_value()) current_bounds = bounds.value(); storage<bounds_aabb>(mix(uid, "last_bounds"_id)) = current_bounds.is_escaped() ? bounds_aabb{ 0.0f, m_size.x, 0.0f, m_size.y } : current_bounds; } [[nodiscard]] identifier current_region_uid() const { return m_region_stack.back().uid; } std::pair<size_t, identifier> push_region(const identifier uid, const std::optional<bounds_aabb>& bounds) override { const auto idx = m_commands.size(); m_commands.push_back(op_push_region{ bounds.value_or(bounds_aabb{ 0.0f, 0.0f, 0.0f, 0.0f }) }); const auto mixed = mix(current_region_uid(), uid); auto last_bounds = storage<bounds_aabb>(mix(mixed, "last_bounds"_id)); const auto& parent = m_region_stack.back(); const vec2 offset{ last_bounds.left, last_bounds.top }; clip_bounds(last_bounds, parent.offset, parent.absolute_bounds); m_region_stack.push_back( { idx, mixed, std::minstd_rand{ static_cast<unsigned>(mixed.id) }, last_bounds, parent.offset + offset }); return { idx, mixed }; } [[nodiscard]] const bounds_aabb& region_bounds() const override { return m_region_stack.back().absolute_bounds; } [[nodiscard]] bool region_hovered() const override { return hovered(region_bounds()); } [[nodiscard]] bool hovered(const bounds_aabb& bounds) const override { const auto [x, y] = m_input_backend.get_cursor_pos(); return bounds.left <= x && x < bounds.right && bounds.top <= y && y < bounds.bottom; } std::pair<size_t, identifier> add_primitive(const identifier uid, primitive primitive) override { const auto idx = m_commands.size(); m_commands.push_back(std::move(primitive)); return { idx, mix(current_region_uid(), uid) }; } [[nodiscard]] std::pmr::memory_resource* memory_resource() const noexcept override { return m_memory_resource; } [[nodiscard]] float step(const identifier id, const float dest) override { return m_step_function(dest, m_animation_state_hash ? raw_storage(m_animation_state_hash, id) : nullptr); } [[nodiscard]] vec2 calculate_bounds(const primitive& primitive) const override { return m_emitter.calculate_bounds(primitive, m_context.global_style()); } identifier region_sub_uid() override { return mix(current_region_uid(), identifier{ m_region_stack.back().random_engine() }); } [[nodiscard]] input_backend& input() const noexcept override { return m_input_backend; } [[nodiscard]] float delta_t() const noexcept override { return m_delta_t; } bool region_request_focus(const bool force) override { if(m_input_mode != input_mode::game_pad) return false; const auto bounds = m_region_stack.back().absolute_bounds; const vec2 center = { (bounds.left + bounds.right) / 2.0f, (bounds.top + bounds.bottom) / 2.0f }; const auto current = current_region_uid(); m_focusable_region.push_back({ current, center }); auto& last_focus = storage<identifier>("glabal_focus"_id); if(force) { last_focus = current; return true; } return last_focus == current; } void finish() { // TODO: mode switching auto& last_focus = storage<identifier>("glabal_focus"_id); if(m_input_mode != input_mode::game_pad || m_focusable_region.empty()) { last_focus = identifier{ 0 }; return; } vec2 focus{ 0.0f, 0.0f }; bool lost_focus = true; for(auto& [id, pos] : m_focusable_region) { if(last_focus == id) { focus = pos; lost_focus = false; break; } } if(lost_focus) { const auto init = std::min_element(m_focusable_region.cbegin(), m_focusable_region.cend(), [](auto lhs, auto rhs) { return std::fabs(lhs.second.y - rhs.second.y) < 0.1f ? lhs.second.x < rhs.second.x : lhs.second.y < rhs.second.y; }); focus = init->second; last_focus = init->first; } auto dir = m_input_backend.action_direction_pulse_repeated(true); if(dir.x * dir.x + dir.y * dir.y < 0.25f) { return; } const auto norm = std::hypot(dir.x, dir.y); dir.x /= norm; dir.y /= norm; auto min_dist = std::numeric_limits<float>::max(); for(auto& [id, pos] : m_focusable_region) { if(id == last_focus) continue; const auto diff = pos - focus; const auto dot = diff.x * dir.x + diff.y * dir.y; if(dot < 0.01f) continue; if(const auto diameter = (diff.x * diff.x + diff.y * diff.y) / std::pow(dot, 1.4f); diameter < min_dist) { min_dist = diameter; last_focus = id; } } } [[nodiscard]] vec2 region_offset() const override { return m_region_stack.back().offset; } }; // TODO: improve performance class codepoint_locator final { std::pmr::unordered_map<font*, std::pmr::unordered_map<uint32_t, texture_region>> m_lut; image_compactor& m_image_compactor; std::pmr::unordered_map<uint32_t, texture_region>& locate(font& font_ref) { const auto iter = m_lut.find(&font_ref); if(iter == m_lut.cend()) return m_lut .emplace(&font_ref, std::pmr::unordered_map<uint32_t, texture_region>{ m_lut.get_allocator().resource() }) .first->second; return iter->second; } public: explicit codepoint_locator(image_compactor& image_compactor, std::pmr::memory_resource* memory_resource) : m_lut{ memory_resource }, m_image_compactor{ image_compactor } {} void reset() { m_lut.clear(); } texture_region locate(font& font_ref, const glyph_id glyph) { auto&& lut = locate(font_ref); const auto iter = lut.find(glyph.idx); if(iter == lut.cend()) { return lut .emplace( glyph.idx, font_ref.render_to_bitmap( glyph, [&](const image_desc& desc) { return m_image_compactor.compact(desc, font_ref.max_scale()); })) .first->second; } return iter->second; } }; class command_fallback_translator final { primitive_type m_supported_primitive; primitive_type m_fallback_primitive; void (*m_quad_emitter)(std::pmr::vector<vertex>&, const vertex&, const vertex&, const vertex&, const vertex&); // CCW static void emit_triangle(std::pmr::vector<vertex>& vertices, const vertex& p1, const vertex& p2, const vertex& p3) { vertices.push_back(p1); vertices.push_back(p2); vertices.push_back(p3); } static void emit_quad_triangle_strip(std::pmr::vector<vertex>& vertices, const vertex& p1, const vertex& p2, const vertex& p3, const vertex& p4) { vertices.push_back(p1); vertices.push_back(p2); vertices.push_back(p4); vertices.push_back(p3); } static void emit_quad_triangles(std::pmr::vector<vertex>& vertices, const vertex& p1, const vertex& p2, const vertex& p3, const vertex& p4) { vertices.push_back(p1); vertices.push_back(p2); vertices.push_back(p3); vertices.push_back(p1); vertices.push_back(p3); vertices.push_back(p4); } void emit_line(std::pmr::vector<vertex>& vertices, const vertex& p1, const vertex& p2, const float width) const { auto dx = p1.pos.x - p2.pos.x, dy = p1.pos.y - p2.pos.y; const auto dist = std::hypotf(dx, dy); if(dist < 0.1f) return; const auto scale = 0.5f * width / dist; dx *= scale; dy *= -scale; std::swap(dx, dy); vertex p11 = p1, p12 = p1, p21 = p2, p22 = p2; p11.pos.x += dx; p11.pos.y += dy; p12.pos.x -= dx; p12.pos.y -= dy; p21.pos.x += dx; p21.pos.y += dy; p22.pos.x -= dx; p22.pos.y -= dy; m_quad_emitter(vertices, p11, p21, p22, p12); } void fallback_lines_adj(const span<const vertex>& input, std::pmr::vector<vertex>& output, const float line_width, const bool make_loop) const { for(size_t i = 1; i < input.size(); ++i) emit_line(output, input[i - 1], input[i], line_width); if(make_loop) emit_line(output, input[input.size() - 1], input[0], line_width); } void fallback_lines(const span<const vertex>& input, std::pmr::vector<vertex>& output, const float line_width) const { for(size_t i = 1; i < input.size(); i += 2) emit_line(output, input[i - 1], input[i], line_width); } void fallback_points(const span<const vertex>& input, std::pmr::vector<vertex>& output, const float point_size) const { const auto offset = point_size * 0.5f; for(auto&& p0 : input) { vertex p1 = p0, p2 = p0, p3 = p0, p4 = p0; p1.pos.x -= offset; p1.pos.y -= offset; p2.pos.x -= offset; p2.pos.y += offset; p3.pos.x += offset; p3.pos.y += offset; p4.pos.x += offset; p4.pos.y -= offset; m_quad_emitter(output, p1, p2, p3, p4); } } void fallback_quads(const span<const vertex>& input, std::pmr::vector<vertex>& output) const { for(size_t base = 0; base < input.size(); base += 4) m_quad_emitter(output, input[base], input[base + 1], input[base + 2], input[base + 3]); } static void fallback_triangle_strip(const span<const vertex>& input, std::pmr::vector<vertex>& output) { for(size_t i = 2; i < input.size(); ++i) { if(i & 1) emit_triangle(output, input[i], input[i - 1], input[i - 2]); else emit_triangle(output, input[i], input[i - 2], input[i - 1]); } } static void fallback_triangle_fan(const span<const vertex>& input, std::pmr::vector<vertex>& output) { for(size_t i = 2; i < input.size(); ++i) emit_triangle(output, input[0], input[i - 1], input[i]); } public: explicit command_fallback_translator(const primitive_type supported_primitive) : m_supported_primitive{ supported_primitive }, m_fallback_primitive{ support_primitive(supported_primitive, primitive_type::triangle_strip) ? primitive_type::triangle_strip : primitive_type::triangles }, m_quad_emitter{ support_primitive(supported_primitive, primitive_type::triangle_strip) ? emit_quad_triangle_strip : emit_quad_triangles } { if(!support_primitive(m_supported_primitive, primitive_type::triangles)) throw std::logic_error{ "Unsupported render backend" }; } void transform(command_queue& command_list) const { uint32_t vertices_offset = 0; std::pmr::vector<vertex> output{ command_list.vertices.get_allocator().resource() }; output.reserve(command_list.vertices.size()); for(auto& [bounds, clip, desc] : command_list.commands) if(desc.index() == 1) { // ReSharper disable once CppTooWideScope auto&& [type, vertices_count, _, point_line_size] = std::get<primitives>(desc); span<const vertex> old{ command_list.vertices.data() + vertices_offset, command_list.vertices.data() + vertices_offset + vertices_count }; vertices_offset += vertices_count; if(!support_primitive(m_supported_primitive, type)) { const auto old_size = output.size(); // ReSharper disable once CppDefaultCaseNotHandledInSwitchStatement CppIncompleteSwitchStatement switch(type) { // NOLINT(clang-diagnostic-switch) case primitive_type::points: fallback_points(old, output, point_line_size); break; case primitive_type::lines: fallback_lines(old, output, point_line_size); break; case primitive_type::line_strip: fallback_lines_adj(old, output, point_line_size, false); break; case primitive_type::line_loop: fallback_lines_adj(old, output, point_line_size, true); break; case primitive_type::triangle_fan: fallback_triangle_fan(old, output); break; case primitive_type::triangle_strip: fallback_triangle_strip(old, output); break; case primitive_type::quads: fallback_quads(old, output); break; } type = m_fallback_primitive; vertices_count = static_cast<uint32_t>(output.size() - old_size); } else { output.insert(output.end(), old.begin(), old.end()); } } command_list.vertices = std::move(output); } }; class smooth_profiler final { std::pmr::deque<uint64_t> m_samples; uint64_t m_sum; public: explicit smooth_profiler(std::pmr::memory_resource* memory_resource) : m_samples{ memory_resource }, m_sum{ 0 } {} uint32_t add_sample(const uint64_t sample) { m_samples.push_back(sample); m_sum += sample; while(m_samples.size() > 600) { m_sum -= m_samples.front(); m_samples.pop_front(); } if(m_samples.size() >= 30) return static_cast<uint32_t>( static_cast<double>(m_sum / m_samples.size()) / // NOLINT(bugprone-integer-division) static_cast<double>(clocks_per_second() / 1'000'000)); // NOLINT(bugprone-integer-division) return 0; } }; class context_impl final : public context { input_backend& m_input_backend; render_backend& m_render_backend; font_backend& m_font_backend; emitter& m_emitter; animator& m_animator; command_optimizer& m_command_optimizer; image_compactor& m_image_compactor; state_manager m_state_manager; codepoint_locator m_codepoint_locator; command_fallback_translator m_command_fallback_translator; std::pmr::memory_resource* m_memory_resource; style m_style; pipeline_statistics m_statistics; std::pmr::deque<uint64_t> m_frame_time_points; smooth_profiler profiler[7]; public: context_impl(input_backend& input_backend, render_backend& render_backend, font_backend& font_backend, emitter& emitter, animator& animator, command_optimizer& command_optimizer, image_compactor& image_compactor, std::pmr::memory_resource* memory_resource) : m_input_backend{ input_backend }, m_render_backend{ render_backend }, m_font_backend{ font_backend }, m_emitter{ emitter }, m_animator{ animator }, m_command_optimizer{ command_optimizer }, m_image_compactor{ image_compactor }, m_state_manager{ memory_resource }, m_codepoint_locator{ image_compactor, memory_resource }, m_command_fallback_translator{ render_backend.supported_primitives() & command_optimizer.supported_primitives() }, m_memory_resource{ memory_resource }, m_style{}, m_statistics{}, m_frame_time_points{ memory_resource }, profiler{ smooth_profiler{ memory_resource }, smooth_profiler{ memory_resource }, smooth_profiler{ memory_resource }, smooth_profiler{ memory_resource }, smooth_profiler{ memory_resource }, smooth_profiler{ memory_resource }, smooth_profiler{ memory_resource } } { set_classic_style(*this); } void reset_cache() override { m_state_manager.reset(); m_codepoint_locator.reset(); m_image_compactor.reset(); } style& global_style() noexcept override { return m_style; } void new_frame(const uint32_t width, const uint32_t height, const float delta_t, const std::function<void(canvas&)>& render_function) override { std::pmr::monotonic_buffer_resource arena{ 1 << 15, m_memory_resource }; const auto tp1 = current_time(); m_frame_time_points.push_back(tp1); while(m_frame_time_points.size() > 600) m_frame_time_points.pop_front(); if(m_frame_time_points.size() >= 30) { m_statistics.smooth_fps = static_cast<uint32_t>(static_cast<double>(m_frame_time_points.size() - 1) / (static_cast<double>(m_frame_time_points.back() - m_frame_time_points.front()) / static_cast<double>(clocks_per_second()))); } else m_statistics.smooth_fps = 0; canvas_impl canvas_root{ *this, vec2{ static_cast<float>(width), static_cast<float>(height) }, delta_t, m_input_backend, m_animator, m_emitter, m_state_manager, &arena }; render_function(canvas_root); canvas_root.finish(); const auto tp2 = current_time(); m_statistics.draw_time = profiler[0].add_sample(tp2 - tp1); m_statistics.generated_operation = static_cast<uint32_t>(canvas_root.commands().size()); auto commands_queue = m_emitter.transform(canvas_root.reserved_size(), canvas_root.commands(), m_style, [&](font& font_ref, const glyph_id glyph) -> texture_region { return m_codepoint_locator.locate(font_ref, glyph); }); const auto tp3 = current_time(); m_statistics.emit_time = profiler[1].add_sample(tp3 - tp2); m_statistics.emitted_draw_call = static_cast<uint32_t>(commands_queue.commands.size()); m_command_fallback_translator.transform(commands_queue); const auto tp4 = current_time(); m_statistics.fallback_time = profiler[2].add_sample(tp4 - tp3); m_statistics.transformed_draw_call = static_cast<uint32_t>(commands_queue.commands.size()); auto optimized_commands = m_command_optimizer.optimize({ width, height }, std::move(commands_queue)); const auto tp5 = current_time(); m_statistics.optimize_time = profiler[3].add_sample(tp5 - tp4); m_statistics.optimized_draw_call = static_cast<uint32_t>(optimized_commands.commands.size()); m_render_backend.update_command_list({ width, height }, std::move(optimized_commands)); m_statistics.frame_time = profiler[4].add_sample(tp5 - tp1 + m_render_backend.render_time() + m_input_backend.input_time()); m_statistics.render_time = profiler[5].add_sample(m_render_backend.render_time()); m_statistics.input_time = profiler[6].add_sample(m_input_backend.input_time()); } texture_region load_image(const image_desc& image, const float max_scale) override { return m_image_compactor.compact(image, max_scale); } [[nodiscard]] std::shared_ptr<font> load_font(const std::pmr::string& name, const float height) const override { return m_font_backend.load_font(name, height); } [[nodiscard]] const pipeline_statistics& statistics() noexcept override { return m_statistics; } }; ANIMGUI_API std::unique_ptr<context> create_animgui_context(input_backend& input_backend, render_backend& render_backend, font_backend& font_backend, emitter& emitter, animator& animator, command_optimizer& command_optimizer, image_compactor& image_compactor, std::pmr::memory_resource* memory_manager) { return std::make_unique<context_impl>(input_backend, render_backend, font_backend, emitter, animator, command_optimizer, image_compactor, memory_manager); } texture_region texture_region::sub_region(const bounds_aabb& bounds) const { const auto w = region.right - region.left, h = region.bottom - region.top; return { tex, { region.left + w * bounds.left, region.left + w * bounds.right, region.top + h * bounds.top, region.top + h * bounds.bottom } }; } } // namespace animgui
51.314063
131
0.552206
[ "render", "vector", "transform" ]
5a6e3afc0d7e6562ae0c05db663a75bde771ce61
5,626
cpp
C++
Editor/LevelEditor/Edit/SceneObject.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
Editor/LevelEditor/Edit/SceneObject.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
Editor/LevelEditor/Edit/SceneObject.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//---------------------------------------------------- // file: CEditObject.cpp //---------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "SceneObject.h" #include "UI_Main.h" #include "bottombar.h" #include "scene.h" #include "d3dutils.h" #include "library.h" #include "EditMesh.h" #define BLINK_TIME 300.f //---------------------------------------------------- CSceneObject::CSceneObject( char *name ):CCustomObject(){ Construct (); Name = name; } CSceneObject::CSceneObject( ):CCustomObject(){ Construct (); } void CSceneObject::Construct(){ ClassID = OBJCLASS_SCENEOBJECT; m_pRefs = 0; m_ObjVer.reset(); m_Center.set(0,0,0); m_fRadius = 0; m_iBlinkTime = 0; } CSceneObject::~CSceneObject(){ Lib.RemoveEditObject(m_pRefs); } //---------------------------------------------------- void CSceneObject::Select(BOOL flag) { inherited::Select(flag); if (flag) m_iBlinkTime=Device.dwTimeGlobal+BLINK_TIME+Device.dwTimeDelta; } //---------------------------------------------------- void CSceneObject::GetFaceWorld(CEditableMesh* M, int idx, Fvector* verts){ const Fvector* PT[3]; M->GetFacePT(idx, PT); _Transform().transform_tiny(verts[0],*PT[0]); _Transform().transform_tiny(verts[1],*PT[1]); _Transform().transform_tiny(verts[2],*PT[2]); } int CSceneObject::GetFaceCount(){ return m_pRefs?m_pRefs->GetFaceCount():0; } int CSceneObject::GetSurfFaceCount(const char* surf_name){ return m_pRefs?m_pRefs->GetSurfFaceCount(surf_name):0; } int CSceneObject::GetVertexCount(){ return m_pRefs?m_pRefs->GetVertexCount():0; } void CSceneObject::OnUpdateTransform(){ inherited::OnUpdateTransform(); // update bounding volume Fbox BB; GetBox (BB); BB.getsphere (m_Center,m_fRadius); } bool CSceneObject::GetBox( Fbox& box ){ if (!m_pRefs) return false; box.xform(m_pRefs->GetBox(),_Transform()); return true; } bool __inline CSceneObject::IsRender(){ if (!m_pRefs) return false; bool bRes = Device.m_Frustum.testSphere(m_Center,m_fRadius); if(bRes&&fraBottomBar->miDrawObjectAnimPath->Checked) RenderAnimation(); return bRes; } void CSceneObject::Render(int priority, bool strictB2F){ inherited::Render(priority,strictB2F); if (!m_pRefs) return; Scene.TurnLightsForObject(this); m_pRefs->Render(_Transform(), priority, strictB2F); if ((1==priority)&&(false==strictB2F)){ if (Selected()){ if (m_iBlinkTime>(int)Device.dwTimeGlobal){ DWORD c=D3DCOLOR_ARGB(iFloor(sqrtf(float(m_iBlinkTime-Device.dwTimeGlobal)/BLINK_TIME)*48),255,255,255); RenderSelection(c); UI.RedrawScene(); } Device.SetShader(Device.m_WireShader); Device.SetTransform(D3DTS_WORLD,_Transform()); DWORD clr = Locked()?0xFFFF0000:0xFFFFFFFF; DU::DrawSelectionBox(m_pRefs->GetBox(),&clr); } } } void CSceneObject::RenderSingle(){ if (!m_pRefs) return; m_pRefs->RenderSingle(_Transform()); } void CSceneObject::RenderAnimation(){ if (!m_pRefs) return; m_pRefs->RenderAnimation(_Transform()); } void CSceneObject::RenderBones(){ if (!m_pRefs) return; m_pRefs->RenderBones(_Transform()); } void CSceneObject::RenderEdge(CEditableMesh* mesh, DWORD color){ if (!m_pRefs) return; if (Device.m_Frustum.testSphere(m_Center,m_fRadius)) m_pRefs->RenderEdge(_Transform(), mesh, color); } void CSceneObject::RenderSelection(DWORD color){ if (!m_pRefs) return; m_pRefs->RenderSelection(_Transform(),0,color); } bool CSceneObject::FrustumPick(const CFrustum& frustum){ if (!m_pRefs) return false; if(Device.m_Frustum.testSphere(m_Center,m_fRadius)) return m_pRefs->FrustumPick(frustum, _Transform()); return false; } bool CSceneObject::SpherePick(const Fvector& center, float radius){ if (!m_pRefs) return false; float R=radius+m_fRadius; float dist_sqr=center.distance_to_sqr(m_Center); if (dist_sqr<R*R) return true; return false; } bool CSceneObject::RayPick(float& dist, Fvector& S, Fvector& D, SRayPickInfo* pinf){ if (!m_pRefs) return false; if (Device.m_Frustum.testSphere(m_Center,m_fRadius)) if (m_pRefs&&m_pRefs->RayPick(dist, S, D, _ITransform(), pinf)){ if (pinf) pinf->s_obj = this; return true; } return false; } bool CSceneObject::BoxPick(const Fbox& box, SBoxPickInfoVec& pinf){ if (!m_pRefs) return false; return m_pRefs->BoxPick(this, box, _ITransform(), pinf); } void CSceneObject::PivotScale(const Fmatrix& prev_inv, const Fmatrix& current, Fvector& amount ){ if (IsDynamic()){ ELog.Msg(mtError,"Dynamic object %s - can't scale.", Name); return; } inherited::PivotScale(prev_inv,current,amount); } void CSceneObject::Scale( Fvector& amount ){ if (IsDynamic()){ ELog.Msg(mtError,"Dynamic object %s - can't scale.", Name); return; } inherited::Scale(amount); } void CSceneObject::GetFullTransformToWorld( Fmatrix& m ){ m.set( _Transform() ); } void CSceneObject::GetFullTransformToLocal( Fmatrix& m ){ m.invert(_Transform()); } void CSceneObject::OnFrame(){ inherited::OnFrame(); if (!m_pRefs) return; if (m_pRefs) m_pRefs->OnFrame(); } CEditableObject* CSceneObject::SetReference(LPCSTR ref_name) { Lib.RemoveEditObject(m_pRefs); m_pRefs = (ref_name&&ref_name[0])?Lib.CreateEditObject(ref_name):0; return m_pRefs; }
27.714286
118
0.638287
[ "mesh", "render", "object" ]
5a79eb2611237e710690a700e87e89431c56e2ca
15,781
cpp
C++
center.cpp
yuantailing/2-center
d9d7408bfda30626160ae569ee36b8f5a5ebe38e
[ "MIT" ]
null
null
null
center.cpp
yuantailing/2-center
d9d7408bfda30626160ae569ee36b8f5a5ebe38e
[ "MIT" ]
null
null
null
center.cpp
yuantailing/2-center
d9d7408bfda30626160ae569ee36b8f5a5ebe38e
[ "MIT" ]
null
null
null
#include "center.h" #include <cassert> #include <cmath> #include <algorithm> #include <chrono> #include <iostream> #include <random> #include <stdexcept> #include "kptree.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif bool quick_case_only = false; static int tmp_dc_case; static Float tmp_dc_rotate_angle; static std::vector<bool> tmp_dc_division_left; int dc_case = 0; Float dc_rotate_angle = 0; std::vector<bool> dc_division_left; // rotate points in S by theta (center is o) static void rotate(std::vector<Coord> &S, Float theta, Coord const &o=Coord(Real(0), Real(0))) { Float c = std::cos(theta); Float s = std::sin(theta); for (Coord &coord: S) { Coord d = coord - o; coord = o + Coord(d.x * c - d.y * s, d.x * s + d.y * c); } } bool DC_separated(Real r, std::vector<Coord> const &S, std::vector<Coord> &centers) { Float delta = M_PI / 36; for (int j = 0; j * delta < M_PI - delta / 2; j++) { Float rotate_angle = j * delta + delta * 0.47631; std::vector<Coord> rotated_S = S; rotate(rotated_S, rotate_angle); std::vector<std::pair<Coord, std::size_t> > paired(rotated_S.size()); for (std::size_t i = 0; i < rotated_S.size(); i++) { paired[i] = std::make_pair(rotated_S[i], i); } std::sort(paired.begin(), paired.end(), [](std::pair<Coord, std::size_t> const &a, std::pair<Coord, std::size_t> const &b) { if (a.first.x != b.first.x) return a.first.x < b.first.x; if (a.first.y != b.first.y) return a.first.y < b.first.y; return a.second < b.second; }); for (std::size_t i = 0; i < paired.size(); i++) rotated_S[i] = paired[i].first; Kptree SL(r, rotated_S), SR(r, rotated_S); for (size_t i = 0; i < rotated_S.size(); i++) SR.insert(i); for (std::size_t i = 0; i <= rotated_S.size(); i++) { if (SL.has_intersection() && SR.has_intersection()) { centers.clear(); centers.push_back(SL.center_avaliable()); centers.push_back(SR.center_avaliable()); rotate(centers, -rotate_angle); tmp_dc_case = 1; tmp_dc_rotate_angle = rotate_angle; tmp_dc_division_left.clear(); tmp_dc_division_left.resize(S.size(), false); for (std::size_t k = 0; k < i; k++) tmp_dc_division_left[paired[k].second] = true; return true; } if (i < rotated_S.size()) { SL.insert(i); SR.remove(i); } } BoundingBox bb = BoundingBox::from_vector(rotated_S); Real long_edge = bb.long_edge(); if (long_edge > r * 5) continue; for (Real lambdax = bb.xmin; lambdax <= bb.xmax; lambdax += 0.3 * r) { } } return false; } bool DC_close(Real r, std::vector<Coord> const &S, std::vector<Coord> &centers) { Float delta = M_PI / 3; for (int j0 = 0; j0 * delta < M_PI - delta / 2; j0++) { Float rotate_angle = j0 * delta + delta * 0.31287; std::vector<Coord> rotated_S = S; rotate(rotated_S, rotate_angle); std::vector<std::pair<Coord, std::size_t> > paired(rotated_S.size()); for (std::size_t i = 0; i < rotated_S.size(); i++) { paired[i] = std::make_pair(rotated_S[i], i); } std::sort(paired.begin(), paired.end(), [](std::pair<Coord, std::size_t> const &a, std::pair<Coord, std::size_t> const &b) { if (a.first.x != b.first.x) return a.first.x < b.first.x; if (a.first.y != b.first.y) return a.first.y < b.first.y; return a.second < b.second; }); for (std::size_t i = 0; i < paired.size(); i++) rotated_S[i] = paired[i].first; BoundingBox bb = BoundingBox::from_vector(rotated_S); Real long_edge = bb.long_edge(); if (long_edge > r * 3) continue; Real de = r * 0.7057413; for (Real zx = bb.xmin + de / 2; zx == bb.xmin + de / 2 || zx <= bb.xmax - de / 2; zx += de) { for (Real zy = bb.ymin + de / 2; zy == bb.xmin + de / 2 || zy <= bb.ymax - de / 2; zy += de) { Coord z(zx, zy); std::vector<std::size_t> Q0, Q1; for (std::size_t i = 0; i < rotated_S.size(); i++) { Coord const &coord = rotated_S[i]; if (coord.y < z.y || (coord.y == z.y && coord.x < z.x)) Q0.push_back(i); else Q1.push_back(i); } std::sort(Q0.begin(), Q0.end(), [&](std::size_t a, std::size_t b) { return to_left(rotated_S[b], z, rotated_S[a]); }); std::sort(Q1.begin(), Q1.end(), [&](std::size_t a, std::size_t b) { return to_left(z, rotated_S[b], rotated_S[a]); }); struct Task { int up, down, left, right; Task(int up, int down, int left, int right): up(up), down(down), left(left), right(right) { } }; std::vector<Task> tasks; std::vector<Task> newTasks; tasks.push_back(Task(0, (int)Q0.size(), 0, (int)Q1.size())); while (!tasks.empty()) { Kptree SL(r, rotated_S), SR(r, rotated_S); int h_pos = (tasks[0].left + tasks[0].right) / 2; int v_pos = 0; for (std::size_t i = 0; i < (size_t)v_pos; i++) SL.insert(Q0[i]); for (std::size_t i = v_pos; i < Q0.size(); i++) SR.insert(Q0[i]); for (std::size_t i = 0; i < (size_t)h_pos; i++) SL.insert(Q1[i]); for (std::size_t i = h_pos; i < Q1.size(); i++) SR.insert(Q1[i]); newTasks.clear(); for (Task const &task: tasks) { if (task.up > task.down || task.left > task.right) continue; int mid = (task.left + task.right) / 2; while (h_pos > mid) { h_pos--; SL.remove(Q1[h_pos]); SR.insert(Q1[h_pos]); } while (v_pos < task.up) { SL.insert(Q0[v_pos]); SR.remove(Q0[v_pos]); v_pos++; } int YNNY = 0; while (v_pos < task.down) { bool Y0 = SL.has_intersection(); bool Y1 = SR.has_intersection(); if (Y0 && Y1) { centers.clear(); centers.push_back(SL.center_avaliable()); centers.push_back(SR.center_avaliable()); rotate(centers, -rotate_angle); tmp_dc_case = 3; tmp_dc_rotate_angle = rotate_angle; tmp_dc_division_left.clear(); tmp_dc_division_left.resize(S.size(), false); for (int i = 0; i < v_pos; i++) tmp_dc_division_left[paired[Q0[i]].second] = true; for (int i = 0; i < h_pos; i++) tmp_dc_division_left[paired[Q1[i]].second] = true; return true; } if (!Y0 && !Y1) { newTasks.push_back(Task(task.up, v_pos - 1, mid + 1, task.right)); newTasks.push_back(Task(v_pos + 1, task.down, task.left, mid - 1)); YNNY = 0; break; } if (Y0 && !Y1) YNNY = 1; else YNNY = 2; SL.insert(Q0[v_pos]); SR.remove(Q0[v_pos]); v_pos++; } while (v_pos < task.down) { SL.insert(Q0[v_pos]); SR.remove(Q0[v_pos]); v_pos++; } if (YNNY == 1) newTasks.push_back(Task(task.up, task.down, mid + 1, task.right)); else if (YNNY == 2) newTasks.push_back(Task(task.up, task.down, task.left, mid - 1)); } tasks = newTasks; } } } } return false; } bool DC(Real r, std::vector<Coord> const &S, std::vector<Coord> &centers) { if (DC_separated(r, S, centers)) return true; if (!quick_case_only && DC_close(r, S, centers)) return true; return false; } bool DC_check(Real r, std::vector<Coord> const &S, std::vector<Coord> const &centers) { for (Coord const &x: S) { bool found = false; for (Coord const &center: centers) { if ((x - center).norm2() <= r * r) { found = true; break; } } if (!found) return false; } return true; } void one_circle(std::vector<Coord> &S, Real &r_out, Coord &center_out) { // S will be modified std::default_random_engine e(0); std::shuffle(S.begin(), S.end(), e); if (S.size() == 0) { r_out = 0; center_out = Coord(0, 0); } else if (S.size() == 1) { r_out = 0; center_out = S[0]; } else if (S.size() == 2) { center_out = (S[0] + S[1]) / 2; r_out = (S[0] - center_out).norm(); } else { Real eps = 1e-6; Coord &d(center_out); d = (S[0] + S[1]) / 2; Real r2 = (S[0] - d).norm2(); for (std::size_t i = 2; i < S.size(); i++) { if ((S[i] - d).norm2() <= r2) continue; d = (S[0] + S[i]) / 2; r2 = (S[0] - d).norm2(); for (std::size_t j = 1; j < i; j++) { if ((S[j] - d).norm2() <= r2) continue; d = (S[i] + S[j]) / 2; r2 = (S[i] - d).norm2(); Real r2eps = std::sqrt(r2) * (1 + eps); r2eps *= r2eps; for (std::size_t k = 0; k < j; k++) { if ((S[k] - d).norm2() <= r2eps) continue; Coord A = S[i] - S[j]; Coord B = S[i] - S[k]; Real c1 = (S[i].norm2() - S[j].norm2()) / 2; Real c2 = (S[i].norm2() - S[k].norm2()) / 2; Real det = A.x * B.y - A.y * B.x; d.x = (c1 * B.y - c2 * A.y) / det; d.y = (c2 * A.x - c1 * B.x) / det; r2 = (S[i] - d).norm2(); r2eps = std::sqrt(r2) * (1 + eps); r2eps *= r2eps; } } } r_out = std::sqrt(r2); } } void fix_circle(Real r, std::vector<Coord> const &S, std::vector<Coord> const &centers, Real eps, Real &r_out, std::vector<Coord> &centers_out) { // centers和centers_out可以相同 if (centers.size() != 2) return; for (std::size_t i = 0; i < dc_division_left.size(); i++) { Real d_left = (S[i] - centers[0]).norm(); Real d_right = (S[i] - centers[1]).norm(); if (dc_division_left[i]) { if (d_left > r + eps && d_left > d_right) dc_division_left[i] = false; } else { if (d_right > r + eps && d_left < d_right) dc_division_left[i] = true; } } std::vector<Coord> Ss[2]; for (std::size_t i = 0; i < S.size(); i++) { Ss[dc_division_left[i] ? 0 : 1].push_back(S[i]); } r_out = 0; centers_out.resize(2); for (std::size_t i = 0; i < 2; i++) { Real r_tmp; one_circle(Ss[i], r_tmp, centers_out[i]); r_out = std::max(r_out, r_tmp); } } PCenterResult p_center(int p, std::vector<Coord> const &S0, Real eps) { if (p != 2) throw std::invalid_argument(""); if (S0.empty()) { PCenterResult result; result.r = Real(0); Coord center(Real(0), Real(0)); for (int i = 0; i < p; i++) result.centers.push_back(center); return result; } if (S0.size() <= 2) { PCenterResult result; result.r = Real(0); result.centers.push_back(S0[0]); result.centers.push_back(S0[S0.size() - 1]); return result; } auto start = std::chrono::system_clock::now(); BoundingBox bb = BoundingBox::from_vector(S0); PCenterResult result; Real r_stop = bb.diagonal() * eps / 4; Real lo = 0; Real hi = bb.diagonal() / 2; std::vector<Coord> S; static std::default_random_engine random_engine = std::default_random_engine(0); std::uniform_real_distribution<Real> u(-r_stop, r_stop); for (Coord const &a: S0) { Real x = a.x + u(random_engine); Real y = a.y + u(random_engine); S.push_back(Coord(x, y)); } dc_case = 0; std::vector<Coord> centers; result.r = 0; while (hi - lo > r_stop) { Real mi = (lo + hi) / 2; bool affirmative = false; for (int i = 0; i < 20; i++) { std::vector<Coord> S1; if (i == 0) { affirmative = DC(mi, S, centers); } else { Real mul = pow(2, i); for (Coord const &a: S0) { Real x = a.x + u(random_engine) * mul; Real y = a.y + u(random_engine) * mul; S1.push_back(Coord(x, y)); } affirmative = DC(mi, S1, centers); } if (!affirmative) break; if (i == 0) { if (DC_check(mi + r_stop, S, centers)) break; } else { if (DC_check(mi + r_stop, S1, centers)) break; } if (i == 5) { affirmative = false; centers.clear(); break; } } std::cout << "r = " << mi << ", " << (affirmative ? "OK" : "FAIL") << std::endl; if (affirmative) { dc_case = tmp_dc_case; dc_rotate_angle = tmp_dc_rotate_angle; dc_division_left = tmp_dc_division_left; result.r = mi; result.centers = centers; hi = mi; } else { lo = mi; } } fix_circle(result.r, S0, result.centers, bb.diagonal() * 1e-6, result.r, result.centers); auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start); std::cout << "Spend " << double(duration.count()) * std::chrono::nanoseconds::period::num / std::chrono::nanoseconds::period::den << " s" << std::endl; std::cout << "K(P) tree: insert " << Kptree::get_stat_insert_called() << ", remove " << Kptree::get_stat_remove_called() << ", intersect " << Kptree::get_stat_intersect_called() << std::endl; return result; }
40.464103
172
0.445282
[ "vector" ]
5a92a81a2205e78e87284560aef9499ff521dfb9
12,240
cpp
C++
brlycmbd/CrdBrlyNav/PnlBrlyNavConnect_blks.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
brlycmbd/CrdBrlyNav/PnlBrlyNavConnect_blks.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
brlycmbd/CrdBrlyNav/PnlBrlyNavConnect_blks.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
/** * \file PnlBrlyNavConnect_blks.cpp * job handler for job PnlBrlyNavConnect (implementation of blocks) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 11 Jan 2021 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlBrlyNavConnect::VecVDo ******************************************************************************/ uint PnlBrlyNavConnect::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butconviewclick") return BUTCONVIEWCLICK; if (s == "butconnewcrdclick") return BUTCONNEWCRDCLICK; if (s == "butrlyviewclick") return BUTRLYVIEWCLICK; if (s == "butrlynewcrdclick") return BUTRLYNEWCRDCLICK; return(0); }; string PnlBrlyNavConnect::VecVDo::getSref( const uint ix ) { if (ix == BUTCONVIEWCLICK) return("ButConViewClick"); if (ix == BUTCONNEWCRDCLICK) return("ButConNewcrdClick"); if (ix == BUTRLYVIEWCLICK) return("ButRlyViewClick"); if (ix == BUTRLYNEWCRDCLICK) return("ButRlyNewcrdClick"); return(""); }; /****************************************************************************** class PnlBrlyNavConnect::ContIac ******************************************************************************/ PnlBrlyNavConnect::ContIac::ContIac( const uint numFLstCon , const uint numFLstRly ) : Block() { this->numFLstCon = numFLstCon; this->numFLstRly = numFLstRly; mask = {NUMFLSTCON, NUMFLSTRLY}; }; bool PnlBrlyNavConnect::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacBrlyNavConnect"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacBrlyNavConnect"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstCon", numFLstCon)) add(NUMFLSTCON); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstRly", numFLstRly)) add(NUMFLSTRLY); }; return basefound; }; void PnlBrlyNavConnect::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacBrlyNavConnect"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacBrlyNavConnect"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFLstCon", numFLstCon); writeUintAttr(wr, itemtag, "sref", "numFLstRly", numFLstRly); xmlTextWriterEndElement(wr); }; set<uint> PnlBrlyNavConnect::ContIac::comm( const ContIac* comp ) { set<uint> items; if (numFLstCon == comp->numFLstCon) insert(items, NUMFLSTCON); if (numFLstRly == comp->numFLstRly) insert(items, NUMFLSTRLY); return(items); }; set<uint> PnlBrlyNavConnect::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFLSTCON, NUMFLSTRLY}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlBrlyNavConnect::StatApp ******************************************************************************/ void PnlBrlyNavConnect::StatApp::writeXML( xmlTextWriter* wr , string difftag , bool shorttags , const uint ixBrlyVExpstate , const bool LstConAlt , const bool LstRlyAlt , const uint LstConNumFirstdisp , const uint LstRlyNumFirstdisp ) { if (difftag.length() == 0) difftag = "StatAppBrlyNavConnect"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemAppBrlyNavConnect"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "srefIxBrlyVExpstate", VecBrlyVExpstate::getSref(ixBrlyVExpstate)); writeBoolAttr(wr, itemtag, "sref", "LstConAlt", LstConAlt); writeBoolAttr(wr, itemtag, "sref", "LstRlyAlt", LstRlyAlt); writeUintAttr(wr, itemtag, "sref", "LstConNumFirstdisp", LstConNumFirstdisp); writeUintAttr(wr, itemtag, "sref", "LstRlyNumFirstdisp", LstRlyNumFirstdisp); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlBrlyNavConnect::StatShr ******************************************************************************/ PnlBrlyNavConnect::StatShr::StatShr( const bool LstConAvail , const bool ButConViewActive , const bool LstRlyAvail , const bool ButRlyViewActive ) : Block() { this->LstConAvail = LstConAvail; this->ButConViewActive = ButConViewActive; this->LstRlyAvail = LstRlyAvail; this->ButRlyViewActive = ButRlyViewActive; mask = {LSTCONAVAIL, BUTCONVIEWACTIVE, LSTRLYAVAIL, BUTRLYVIEWACTIVE}; }; void PnlBrlyNavConnect::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrBrlyNavConnect"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrBrlyNavConnect"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "LstConAvail", LstConAvail); writeBoolAttr(wr, itemtag, "sref", "ButConViewActive", ButConViewActive); writeBoolAttr(wr, itemtag, "sref", "LstRlyAvail", LstRlyAvail); writeBoolAttr(wr, itemtag, "sref", "ButRlyViewActive", ButRlyViewActive); xmlTextWriterEndElement(wr); }; set<uint> PnlBrlyNavConnect::StatShr::comm( const StatShr* comp ) { set<uint> items; if (LstConAvail == comp->LstConAvail) insert(items, LSTCONAVAIL); if (ButConViewActive == comp->ButConViewActive) insert(items, BUTCONVIEWACTIVE); if (LstRlyAvail == comp->LstRlyAvail) insert(items, LSTRLYAVAIL); if (ButRlyViewActive == comp->ButRlyViewActive) insert(items, BUTRLYVIEWACTIVE); return(items); }; set<uint> PnlBrlyNavConnect::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {LSTCONAVAIL, BUTCONVIEWACTIVE, LSTRLYAVAIL, BUTRLYVIEWACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlBrlyNavConnect::Tag ******************************************************************************/ void PnlBrlyNavConnect::Tag::writeXML( const uint ixBrlyVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagBrlyNavConnect"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemBrlyNavConnect"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixBrlyVLocale == VecBrlyVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Connection module"); writeStringAttr(wr, itemtag, "sref", "CptCon", "connections"); writeStringAttr(wr, itemtag, "sref", "CptRly", "relays"); } else if (ixBrlyVLocale == VecBrlyVLocale::DECH) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Verbindungsdaten"); writeStringAttr(wr, itemtag, "sref", "CptCon", "Verbindungen"); writeStringAttr(wr, itemtag, "sref", "CptRly", "Verbindungsketten"); }; xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlBrlyNavConnect::DpchAppData ******************************************************************************/ PnlBrlyNavConnect::DpchAppData::DpchAppData() : DpchAppBrly(VecBrlyVDpch::DPCHAPPBRLYNAVCONNECTDATA) { }; string PnlBrlyNavConnect::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlBrlyNavConnect::DpchAppData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppBrlyNavConnectData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); } else { contiac = ContIac(); }; }; /****************************************************************************** class PnlBrlyNavConnect::DpchAppDo ******************************************************************************/ PnlBrlyNavConnect::DpchAppDo::DpchAppDo() : DpchAppBrly(VecBrlyVDpch::DPCHAPPBRLYNAVCONNECTDO) { ixVDo = 0; }; string PnlBrlyNavConnect::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlBrlyNavConnect::DpchAppDo::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppBrlyNavConnectDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; } else { }; }; /****************************************************************************** class PnlBrlyNavConnect::DpchEngData ******************************************************************************/ PnlBrlyNavConnect::DpchEngData::DpchEngData( const ubigint jref , ContIac* contiac , Feed* feedFLstCon , Feed* feedFLstRly , StatShr* statshr , const set<uint>& mask ) : DpchEngBrly(VecBrlyVDpch::DPCHENGBRLYNAVCONNECTDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTIAC, FEEDFLSTCON, FEEDFLSTRLY, STATAPP, STATSHR, TAG}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; if (find(this->mask, FEEDFLSTCON) && feedFLstCon) this->feedFLstCon = *feedFLstCon; if (find(this->mask, FEEDFLSTRLY) && feedFLstRly) this->feedFLstRly = *feedFLstRly; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; }; string PnlBrlyNavConnect::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(FEEDFLSTCON)) ss.push_back("feedFLstCon"); if (has(FEEDFLSTRLY)) ss.push_back("feedFLstRly"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlBrlyNavConnect::DpchEngData::merge( DpchEngBrly* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);}; if (src->has(FEEDFLSTCON)) {feedFLstCon = src->feedFLstCon; add(FEEDFLSTCON);}; if (src->has(FEEDFLSTRLY)) {feedFLstRly = src->feedFLstRly; add(FEEDFLSTRLY);}; if (src->has(STATAPP)) add(STATAPP); if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(TAG)) add(TAG); }; void PnlBrlyNavConnect::DpchEngData::writeXML( const uint ixBrlyVLocale , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngBrlyNavConnectData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/brly"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref)); if (has(CONTIAC)) contiac.writeXML(wr); if (has(FEEDFLSTCON)) feedFLstCon.writeXML(wr); if (has(FEEDFLSTRLY)) feedFLstRly.writeXML(wr); if (has(STATAPP)) StatApp::writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(TAG)) Tag::writeXML(ixBrlyVLocale, wr); xmlTextWriterEndElement(wr); };
29.352518
111
0.640114
[ "vector" ]
5a9c0267993aeac7bd4943a799b598bd7a5b57f9
24,034
cxx
C++
Modules/Loadable/SubjectHierarchy/Widgets/qSlicerSubjectHierarchyScriptedPlugin.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Modules/Loadable/SubjectHierarchy/Widgets/qSlicerSubjectHierarchyScriptedPlugin.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Modules/Loadable/SubjectHierarchy/Widgets/qSlicerSubjectHierarchyScriptedPlugin.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Csaba Pinter, PerkLab, Queen's University and was supported through the Applied Cancer Research Unit program of Cancer Care Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care ==============================================================================*/ // SubjectHierarchy includes #include "qSlicerSubjectHierarchyScriptedPlugin.h" #include "qSlicerSubjectHierarchyPluginHandler.h" // Qt includes #include <QDebug> #include <QFileInfo> #include <QAction> // Slicerncludes #include "qSlicerScriptedUtils_p.h" // PythonQt includes #include <PythonQt.h> #include <PythonQtConversion.h> // VTK includes #include <vtkSmartPointer.h> #include <vtkPythonUtil.h> //----------------------------------------------------------------------------- class qSlicerSubjectHierarchyScriptedPluginPrivate { public: typedef qSlicerSubjectHierarchyScriptedPluginPrivate Self; qSlicerSubjectHierarchyScriptedPluginPrivate(); virtual ~qSlicerSubjectHierarchyScriptedPluginPrivate(); enum { CanOwnSubjectHierarchyItemMethod = 0, RoleForPluginMethod, HelpTextMethod, IconMethod, VisibilityIconMethod, EditPropertiesMethod, DisplayedItemNameMethod, TooltipMethod, SetDisplayVisibilityMethod, GetDisplayVisibilityMethod, ItemContextMenuActionsMethod, ViewContextMenuActionsMethod, SceneContextMenuActionsMethod, ShowContextMenuActionsForItemMethod, ShowViewContextMenuActionsForItemMethod, CanAddNodeToSubjectHierarchyMethod, CanReparentItemInsideSubjectHierarchyMethod, ReparentItemInsideSubjectHierarchyMethod }; mutable qSlicerPythonCppAPI PythonCppAPI; QString PythonSource; }; //----------------------------------------------------------------------------- // qSlicerSubjectHierarchyScriptedPluginPrivate methods //----------------------------------------------------------------------------- qSlicerSubjectHierarchyScriptedPluginPrivate::qSlicerSubjectHierarchyScriptedPluginPrivate() { // Role-related methods this->PythonCppAPI.declareMethod(Self::CanOwnSubjectHierarchyItemMethod, "canOwnSubjectHierarchyItem"); this->PythonCppAPI.declareMethod(Self::RoleForPluginMethod, "roleForPlugin"); this->PythonCppAPI.declareMethod(Self::HelpTextMethod, "helpText"); this->PythonCppAPI.declareMethod(Self::IconMethod, "icon"); this->PythonCppAPI.declareMethod(Self::VisibilityIconMethod, "visibilityIcon"); this->PythonCppAPI.declareMethod(Self::EditPropertiesMethod, "editProperties"); this->PythonCppAPI.declareMethod(Self::DisplayedItemNameMethod, "displayedItemName"); this->PythonCppAPI.declareMethod(Self::TooltipMethod, "tooltip"); this->PythonCppAPI.declareMethod(Self::SetDisplayVisibilityMethod, "setDisplayVisibility"); this->PythonCppAPI.declareMethod(Self::GetDisplayVisibilityMethod, "getDisplayVisibility"); // Function related methods this->PythonCppAPI.declareMethod(Self::ItemContextMenuActionsMethod, "itemContextMenuActions"); this->PythonCppAPI.declareMethod(Self::ViewContextMenuActionsMethod, "viewContextMenuActions"); this->PythonCppAPI.declareMethod(Self::SceneContextMenuActionsMethod, "sceneContextMenuActions"); this->PythonCppAPI.declareMethod(Self::ShowContextMenuActionsForItemMethod, "showContextMenuActionsForItem"); this->PythonCppAPI.declareMethod(Self::ShowViewContextMenuActionsForItemMethod, "showViewContextMenuActionsForItem"); // Parenting related methods (with default implementation) this->PythonCppAPI.declareMethod(Self::CanAddNodeToSubjectHierarchyMethod, "canAddNodeToSubjectHierarchy"); this->PythonCppAPI.declareMethod(Self::CanReparentItemInsideSubjectHierarchyMethod, "canReparentItemInsideSubjectHierarchy"); this->PythonCppAPI.declareMethod(Self::ReparentItemInsideSubjectHierarchyMethod, "reparentItemInsideSubjectHierarchy"); } //----------------------------------------------------------------------------- qSlicerSubjectHierarchyScriptedPluginPrivate::~qSlicerSubjectHierarchyScriptedPluginPrivate() = default; //----------------------------------------------------------------------------- // qSlicerSubjectHierarchyScriptedPlugin methods //----------------------------------------------------------------------------- qSlicerSubjectHierarchyScriptedPlugin::qSlicerSubjectHierarchyScriptedPlugin(QObject *parent) : Superclass(parent) , d_ptr(new qSlicerSubjectHierarchyScriptedPluginPrivate) { this->m_Name = QString("UnnamedScriptedPlugin"); } //----------------------------------------------------------------------------- qSlicerSubjectHierarchyScriptedPlugin::~qSlicerSubjectHierarchyScriptedPlugin() = default; //----------------------------------------------------------------------------- QString qSlicerSubjectHierarchyScriptedPlugin::pythonSource()const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); return d->PythonSource; } //----------------------------------------------------------------------------- bool qSlicerSubjectHierarchyScriptedPlugin::setPythonSource(const QString newPythonSource) { Q_D(qSlicerSubjectHierarchyScriptedPlugin); if (!Py_IsInitialized()) { return false; } if (!newPythonSource.endsWith(".py") && !newPythonSource.endsWith(".pyc")) { return false; } // Extract moduleName from the provided filename QString moduleName = QFileInfo(newPythonSource).baseName(); // In case the plugin is within the main module file QString className = moduleName; if (!moduleName.endsWith("SubjectHierarchyPlugin")) { className.append("SubjectHierarchyPlugin"); } // Get a reference to the main module and global dictionary PyObject * main_module = PyImport_AddModule("__main__"); PyObject * global_dict = PyModule_GetDict(main_module); // Get a reference (or create if needed) the <moduleName> python module PyObject * module = PyImport_AddModule(moduleName.toUtf8()); // Get a reference to the python module class to instantiate PythonQtObjectPtr classToInstantiate; if (PyObject_HasAttrString(module, className.toUtf8())) { classToInstantiate.setNewRef(PyObject_GetAttrString(module, className.toUtf8())); } if (!classToInstantiate) { PythonQtObjectPtr local_dict; local_dict.setNewRef(PyDict_New()); if (!qSlicerScriptedUtils::loadSourceAsModule(moduleName, newPythonSource, global_dict, local_dict)) { return false; } if (PyObject_HasAttrString(module, className.toUtf8())) { classToInstantiate.setNewRef(PyObject_GetAttrString(module, className.toUtf8())); } } if (!classToInstantiate) { PythonQt::self()->handleError(); PyErr_SetString(PyExc_RuntimeError, QString("qSlicerSubjectHierarchyScriptedPlugin::setPythonSource - " "Failed to load subject hierarchy scripted plugin: " "class %1 was not found in %2").arg(className).arg(newPythonSource).toUtf8()); PythonQt::self()->handleError(); return false; } d->PythonCppAPI.setObjectName(className); PyObject* self = d->PythonCppAPI.instantiateClass(this, className, classToInstantiate); if (!self) { return false; } d->PythonSource = newPythonSource; if (!qSlicerScriptedUtils::setModuleAttribute( "slicer", className, self)) { qCritical() << Q_FUNC_INFO << ": Failed to set" << ("slicer." + className); } return true; } //----------------------------------------------------------------------------- PyObject* qSlicerSubjectHierarchyScriptedPlugin::self() const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); return d->PythonCppAPI.pythonSelf(); } //----------------------------------------------------------------------------- void qSlicerSubjectHierarchyScriptedPlugin::setName(QString name) { this->m_Name = name; } //----------------------------------------------------------------------------- double qSlicerSubjectHierarchyScriptedPlugin::canOwnSubjectHierarchyItem(vtkIdType itemID)const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->CanOwnSubjectHierarchyItemMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::canOwnSubjectHierarchyItem(itemID); } // Parse result if (!PyFloat_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'canOwnSubjectHierarchyItem' is expected to return a floating point number!"; return this->Superclass::canOwnSubjectHierarchyItem(itemID); } return PyFloat_AsDouble(result); } //--------------------------------------------------------------------------- const QString qSlicerSubjectHierarchyScriptedPlugin::roleForPlugin()const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* result = d->PythonCppAPI.callMethod(d->RoleForPluginMethod); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::roleForPlugin(); } // Parse result if (!PyString_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'roleForPlugin' is expected to return a string!"; return this->Superclass::roleForPlugin(); } const char* role = PyString_AsString(result); return QString::fromLocal8Bit(role); } //--------------------------------------------------------------------------- const QString qSlicerSubjectHierarchyScriptedPlugin::helpText()const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* result = d->PythonCppAPI.callMethod(d->HelpTextMethod); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::helpText(); } // Parse result if (!PyString_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'helpText' is expected to return a string!"; return this->Superclass::helpText(); } const char* role = PyString_AsString(result); return QString::fromLocal8Bit(role); } //--------------------------------------------------------------------------- QIcon qSlicerSubjectHierarchyScriptedPlugin::icon(vtkIdType itemID) { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->IconMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::icon(itemID); } // Parse result QVariant resultVariant = PythonQtConv::PyObjToQVariant(result, QVariant::Icon); if (resultVariant.isNull()) { return this->Superclass::icon(itemID); } return resultVariant.value<QIcon>(); } //--------------------------------------------------------------------------- QIcon qSlicerSubjectHierarchyScriptedPlugin::visibilityIcon(int visible) { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyInt_FromLong(visible)); PyObject* result = d->PythonCppAPI.callMethod(d->VisibilityIconMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::visibilityIcon(visible); } // Parse result QVariant resultVariant = PythonQtConv::PyObjToQVariant(result, QVariant::Icon); if (resultVariant.isNull()) { return this->Superclass::visibilityIcon(visible); } return resultVariant.value<QIcon>(); } //--------------------------------------------------------------------------- void qSlicerSubjectHierarchyScriptedPlugin::editProperties(vtkIdType itemID) { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->EditPropertiesMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation this->Superclass::editProperties(itemID); } } //----------------------------------------------------------------------------- QList<QAction*> qSlicerSubjectHierarchyScriptedPlugin::itemContextMenuActions()const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* result = d->PythonCppAPI.callMethod(d->ItemContextMenuActionsMethod); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::itemContextMenuActions(); } // Parse result QVariant resultVariant = PythonQtConv::PyObjToQVariant(result, QVariant::List); if (resultVariant.isNull()) { return this->Superclass::itemContextMenuActions(); } QList<QVariant> resultVariantList = resultVariant.toList(); QList<QAction*> actionList; foreach(QVariant actionVariant, resultVariantList) { QAction* action = qobject_cast<QAction*>( actionVariant.value<QObject*>() ); actionList << action; } return actionList; } //----------------------------------------------------------------------------- QList<QAction*> qSlicerSubjectHierarchyScriptedPlugin::viewContextMenuActions()const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* result = d->PythonCppAPI.callMethod(d->ViewContextMenuActionsMethod); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::viewContextMenuActions(); } // Parse result QVariant resultVariant = PythonQtConv::PyObjToQVariant(result, QVariant::List); if (resultVariant.isNull()) { return this->Superclass::viewContextMenuActions(); } QList<QVariant> resultVariantList = resultVariant.toList(); QList<QAction*> actionList; foreach(QVariant actionVariant, resultVariantList) { QAction* action = qobject_cast<QAction*>( actionVariant.value<QObject*>() ); actionList << action; } return actionList; } //----------------------------------------------------------------------------- QList<QAction*> qSlicerSubjectHierarchyScriptedPlugin::sceneContextMenuActions()const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* result = d->PythonCppAPI.callMethod(d->SceneContextMenuActionsMethod); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::sceneContextMenuActions(); } // Parse result QVariant resultVariant = PythonQtConv::PyObjToQVariant(result, QVariant::List); if (resultVariant.isNull()) { return this->Superclass::sceneContextMenuActions(); } QList<QVariant> resultVariantList = resultVariant.toList(); QList<QAction*> actionList; foreach(QVariant actionVariant, resultVariantList) { QAction* action = qobject_cast<QAction*>( actionVariant.value<QObject*>() ); actionList << action; } return actionList; } //--------------------------------------------------------------------------- void qSlicerSubjectHierarchyScriptedPlugin::showContextMenuActionsForItem(vtkIdType itemID) { Q_D(qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->ShowContextMenuActionsForItemMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation this->Superclass::showContextMenuActionsForItem(itemID); } } //--------------------------------------------------------------------------- void qSlicerSubjectHierarchyScriptedPlugin::showViewContextMenuActionsForItem(vtkIdType itemID, QVariantMap eventData) { Q_D(qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(2); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyTuple_SET_ITEM(arguments, 1, PythonQtConv::QVariantMapToPyObject(eventData)); PyObject* result = d->PythonCppAPI.callMethod(d->ShowViewContextMenuActionsForItemMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation this->Superclass::showContextMenuActionsForItem(itemID); } } //---------------------------------------------------------------------------- double qSlicerSubjectHierarchyScriptedPlugin::canAddNodeToSubjectHierarchy( vtkMRMLNode* node, vtkIdType parentItemID/*=vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID*/)const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(2); PyTuple_SET_ITEM(arguments, 0, vtkPythonUtil::GetObjectFromPointer(node)); PyTuple_SET_ITEM(arguments, 1, PyLong_FromLongLong(parentItemID)); PyObject* result = d->PythonCppAPI.callMethod(d->CanAddNodeToSubjectHierarchyMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::canAddNodeToSubjectHierarchy(node, parentItemID); } // Parse result if (!PyFloat_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'canAddNodeToSubjectHierarchy' is expected to return a floating point number!"; return this->Superclass::canAddNodeToSubjectHierarchy(node, parentItemID); } return PyFloat_AsDouble(result); } //---------------------------------------------------------------------------- double qSlicerSubjectHierarchyScriptedPlugin::canReparentItemInsideSubjectHierarchy( vtkIdType itemID, vtkIdType parentItemID)const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(2); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyTuple_SET_ITEM(arguments, 1, PyLong_FromLongLong(parentItemID)); PyObject* result = d->PythonCppAPI.callMethod(d->CanReparentItemInsideSubjectHierarchyMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::canReparentItemInsideSubjectHierarchy(itemID, parentItemID); } // Parse result if (!PyFloat_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'canReparentItemInsideSubjectHierarchy' is expected to return a floating point number!"; return this->Superclass::canReparentItemInsideSubjectHierarchy(itemID, parentItemID); } return PyFloat_AsDouble(result); } //--------------------------------------------------------------------------- bool qSlicerSubjectHierarchyScriptedPlugin::reparentItemInsideSubjectHierarchy( vtkIdType itemID, vtkIdType parentItemID) { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(2); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyTuple_SET_ITEM(arguments, 1, PyLong_FromLongLong(parentItemID)); PyObject* result = d->PythonCppAPI.callMethod(d->ReparentItemInsideSubjectHierarchyMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::reparentItemInsideSubjectHierarchy(itemID, parentItemID); } // Parse result if (!PyBool_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'reparentItemInsideSubjectHierarchy' is expected to return a boolean!"; return this->Superclass::reparentItemInsideSubjectHierarchy(itemID, parentItemID); } return result == Py_True; } //----------------------------------------------------------------------------- QString qSlicerSubjectHierarchyScriptedPlugin::displayedItemName(vtkIdType itemID)const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->DisplayedItemNameMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::displayedItemName(itemID); } // Parse result if (!PyString_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'displayedItemName' is expected to return a string!"; return this->Superclass::displayedItemName(itemID); } return PyString_AsString(result); } //----------------------------------------------------------------------------- QString qSlicerSubjectHierarchyScriptedPlugin::tooltip(vtkIdType itemID)const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->TooltipMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::tooltip(itemID); } // Parse result if (!PyString_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'tooltip' is expected to return a string!"; return this->Superclass::tooltip(itemID); } return PyString_AsString(result); } //----------------------------------------------------------------------------- void qSlicerSubjectHierarchyScriptedPlugin::setDisplayVisibility(vtkIdType itemID, int visible) { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(2); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyTuple_SET_ITEM(arguments, 1, PyInt_FromLong(visible)); PyObject* result = d->PythonCppAPI.callMethod(d->SetDisplayVisibilityMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation this->Superclass::setDisplayVisibility(itemID, visible); } } //----------------------------------------------------------------------------- int qSlicerSubjectHierarchyScriptedPlugin::getDisplayVisibility(vtkIdType itemID)const { Q_D(const qSlicerSubjectHierarchyScriptedPlugin); PyObject* arguments = PyTuple_New(1); PyTuple_SET_ITEM(arguments, 0, PyLong_FromLongLong(itemID)); PyObject* result = d->PythonCppAPI.callMethod(d->GetDisplayVisibilityMethod, arguments); Py_DECREF(arguments); if (!result) { // Method call failed (probably an omitted function), call default implementation return this->Superclass::getDisplayVisibility(itemID); } // Parse result if (!PyInt_Check(result)) { qWarning() << d->PythonSource << ": " << Q_FUNC_INFO << ": Function 'getDisplayVisibility' is expected to return an integer!"; return this->Superclass::getDisplayVisibility(itemID); } return (int)PyInt_AsLong(result); }
37.908517
160
0.682242
[ "3d" ]
5aa51da16e001551cb53121788843cfb7053dece
6,411
cpp
C++
Chapter 2/CppPrimer_Sec2.4/CppPrimer_Sec2.4/main.cpp
toddbrentlinger/Cpp-Primer-5th-Edition
24594e1c8ae4cd5e28508d2e51f53631246efc18
[ "MIT" ]
null
null
null
Chapter 2/CppPrimer_Sec2.4/CppPrimer_Sec2.4/main.cpp
toddbrentlinger/Cpp-Primer-5th-Edition
24594e1c8ae4cd5e28508d2e51f53631246efc18
[ "MIT" ]
null
null
null
Chapter 2/CppPrimer_Sec2.4/CppPrimer_Sec2.4/main.cpp
toddbrentlinger/Cpp-Primer-5th-Edition
24594e1c8ae4cd5e28508d2e51f53631246efc18
[ "MIT" ]
null
null
null
#include <iostream> #include <string> // Function prototypes void NewSectionTitle(std::string customText = ""); void NewExerciseTitle(std::string customText = ""); int main() { // Section 2.4 - const Qualifier std::cout << "\n\tSection 2.4 - const Qualifier" << std::endl; // Exercise 2.26 std::cout << "\n\tExercise 2.26\n" << std::endl; std::cout << "See code" << std::endl; // error: buf is uninitialized const //const int buf; // legal int cnt = 0; // legal const int sz = cnt; // error: cannot assign to const object sz // ++cnt; ++sz; // Section 2.4.1 - References to const std::cout << "\n\tSection 2.4.1 - References to const" << std::endl; { int i = 42; const int &r1 = i; const int &r2 = 42; const int &r3 = r1 * 2; // error: can't initialize non-const reference, r4, to const, (i * 2) // int &r4 = i * 2; // int &r5 = r1 * 2; double dval = 3.14; const int &rd = dval; const int temp = dval; const int &rd2 = temp; } // Section 2.4.2 - Pointers and const // std::cout << "\n\tSection 2.4.2 - Pointers and const" << std::endl; NewSectionTitle("Section 2.4.2 - Pointers and const"); // Exercise 2.27 // std::cout << "\n\tExercise 2.27\n" << std::endl; NewExerciseTitle("Exercise 2.27"); std::cout << "See code" << std::endl; { // (a) // error: Non-const reference r needs to initialize to non-const object // int i = -1, &r = 0; // Correction: int ia = -1; const int &ra = 0; // (b) // legal: Constant pointer p2 initialized to i. Address stored in p2 // cannot be changed. int ib = -1; int *const p2 = &ib; // (c) // legal: Reference to a constant rc can be binded to a literal 0. const int ic = -1, &rc = 0; // (d) // legal: Constant pointer to a constant p3 can be initialized to // non-constant int ib. Address stored in p3 cannot be changed. // Cannot use pointer p3 to change int ib. const int *const p3 = &ib; // (e) // legal: Pointer to a constant p1 can be initialized to point to a // non-constant int. Can't use pointer p1 to chang int ib. const int *p1 = &ib; // (f) // error: Cannot define constant reference to a constant because // references are not objects that can be made constant. // const int &const r2; // (g) // legal: Reference to a constant r can be binded to a non-constant // or constant int. const int ig1 = ib, &r1 = ib; // ib is int const int ig2 = ic, &r2 = ic; // ic is const int } // Exercise 2.28 NewExerciseTitle("Exercise 2.28"); std::cout << "See code" << std::endl; { // (a) // error: Constant pointer cp needs to be initialized. // int i, *const cp; // Correction: Initialize constant pointer cp to address of int i. int i, *const cp = &i; // (b) // error: Constant pointer p2 needs to be initialized. // int *p1, *const p2; // Correction: Initialize pointer p1 to i and // constant pointer p2 to pointer p1 int *p1 = &i, *const p2 = p1; // (c) // error: Constant int ic needs to be initialized // const int ic, &r = ic; // Correction: Initialize constant int ic to literal int 0. const int ic = 0, &r = ic; // (d) // error: Constant pointer to a constant p3 needs to be initialized // const int *const p3; // Correction: Initialize constant pointer to a constant p3 to // address of constant int ic const int *const p3 = &ic; // (e) // legal: Pointer to a constant does not need to be initialized. // Pointer can be assigned a different address but cannot be used // to change the value that p points. const int *p; NewExerciseTitle("Exercise 2.29"); std::cout << "See code" << std::endl; // (a) // legal: i = ic; // (b) // error: Cannot assign constant pointer to a constant p3 to a // non-constant pointer p1. Pointed-to types don't match. // p1 = p3; // (c) // error: Cannot assign a const int ic to a non-constant // pointer p1 // p1 = &ic; // (d) // error: Cannot assign to constant pointer to a constant p3. Address // stored in pointer p3 cannot be changed. // p3 = &ic; // (e) // error: Cannot assign to constant pointer p2. Address stored in // pointer p2 cannot be changed. // p2 = p1; // (f) // error: Cannot assign to constant int ic. // ic = *p3; } // Section 2.4.3 - Top-Level const NewSectionTitle("Section 2.4.3 - Top-Level const"); // Exercise 2.30 NewExerciseTitle("Exercise 2.30"); { int i = 0; // Constant int v2 has top-level const const int v2 = 0; // v1 has no const and v2 has top-level const. Both have // no low-level const. Same low-level const qualifications. int v1 = v2; // p1 has no const and v1 has no const. Same low-level const // qualifications. r1 has no const as well. int *p1 = &v1, &r1 = v1; // p2 has low-level const and v2 has top-level const. p3 has // top-level const and i has no const. r2 has low-level const. // const in reference types is always low-level const int *p2 = &v2, *const p3 = &i, &r2 = v2; // Exercise 2.31 NewExerciseTitle("Exercise 2.31"); // ok: Equivalent to v1 = v2. // Reference r1 is not a constant, can be used to reassign v1. // The value in v2 is copied into v1. It doesn't matter whether // either or both of the objects are consts. r1 = v2; // error: p2 has low-level const but p1 does not // p1 = p2; // ok: can convert non-const int*(p1) to const int*(p2) p2 = p1; // error: p3 has low-level const but p1 does not // p1 = p3; // ok: p2 has same low-level const qualifications as p3 p2 = p3; } // Section 2.4.4 - constexpr and Constant Expressions NewSectionTitle("Section 2.4.4 - constexpr and Constant Expressions"); // Exercise 2.32 NewExerciseTitle("Exercise 2.32"); { // illegal: No address-of operator. Need to initialize pointer to // address of object, not the object itself. // int null = 0, *p = null; int null = 0, *p = &null; } system("pause"); return 0; } void NewSectionTitle(std::string customText) { std::cout << "\n\t" << customText << std::endl; } void NewExerciseTitle(std::string customText) { std::cout << "\n\t" << customText << "\n" << std::endl; }
25.644
74
0.603026
[ "object" ]
5aa782854969b5eea753fadc54154c07b2fdca91
793
cpp
C++
ch11/ex11_9_and_11_19.cpp
Direct-Leo/CppPrimer
9d3993c7604377abc5a925c9fe6342ad3a062983
[ "CC0-1.0" ]
null
null
null
ch11/ex11_9_and_11_19.cpp
Direct-Leo/CppPrimer
9d3993c7604377abc5a925c9fe6342ad3a062983
[ "CC0-1.0" ]
null
null
null
ch11/ex11_9_and_11_19.cpp
Direct-Leo/CppPrimer
9d3993c7604377abc5a925c9fe6342ad3a062983
[ "CC0-1.0" ]
null
null
null
/* Created by vleo on 21/10/24 * Copyright(c)2021 vleo. All rights reserved. * * ex11_3 * "word counter" practice */ #include <string> #include <iostream> #include <sstream> #include <map> #include <algorithm> #include <vector> #include <list> using std::string; using std::map; using std::vector; using std::list; using std::cout;using std::cin; using std::endl; using std::pair; vector<int> vi; int main() { //ex 11_9 map<string, list<std::size_t> > mp; //ex 11_10 map<vector<int>::iterator, int> mv; map<list<int>::iterator, int> ml; mv.insert(pair< vector<int>::iterator, int > (vi.begin(), 0)) ; //"<"operation has not been defined,so it is wrong list<int> li; ml.insert(pair<list<int>::iterator, int> (li.begin(), 0)); return 0; }
18.880952
67
0.636822
[ "vector" ]
5aac1e53b71e0bf2ca18c734fd318fb24489a04d
19,484
cpp
C++
ardupilot/libraries/AP_NavEKF2/AP_NavEKF2_Outputs.cpp
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/libraries/AP_NavEKF2/AP_NavEKF2_Outputs.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/libraries/AP_NavEKF2/AP_NavEKF2_Outputs.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include <AP_HAL/AP_HAL.h> #if HAL_CPU_CLASS >= HAL_CPU_CLASS_150 #include "AP_NavEKF2.h" #include "AP_NavEKF2_core.h" #include <AP_AHRS/AP_AHRS.h> #include <AP_Vehicle/AP_Vehicle.h> #include <stdio.h> extern const AP_HAL::HAL& hal; // Check basic filter health metrics and return a consolidated health status bool NavEKF2_core::healthy(void) const { uint8_t faultInt; getFilterFaults(faultInt); if (faultInt > 0) { return false; } if (velTestRatio > 1 && posTestRatio > 1 && hgtTestRatio > 1) { // all three metrics being above 1 means the filter is // extremely unhealthy. return false; } // Give the filter a second to settle before use if ((imuSampleTime_ms - ekfStartTime_ms) < 1000 ) { return false; } // barometer and position innovations must be within limits when on-ground float horizErrSq = sq(innovVelPos[3]) + sq(innovVelPos[4]); if (onGround && (fabsf(innovVelPos[5]) > 1.0f || horizErrSq > 1.0f)) { return false; } // all OK return true; } // return data for debugging optical flow fusion void NavEKF2_core::getFlowDebug(float &varFlow, float &gndOffset, float &flowInnovX, float &flowInnovY, float &auxInnov, float &HAGL, float &rngInnov, float &range, float &gndOffsetErr) const { varFlow = max(flowTestRatio[0],flowTestRatio[1]); gndOffset = terrainState; flowInnovX = innovOptFlow[0]; flowInnovY = innovOptFlow[1]; auxInnov = auxFlowObsInnov; HAGL = terrainState - stateStruct.position.z; rngInnov = innovRng; range = rngMea; gndOffsetErr = sqrtf(Popt); // note Popt is constrained to be non-negative in EstimateTerrainOffset() } // provides the height limit to be observed by the control loops // returns false if no height limiting is required // this is needed to ensure the vehicle does not fly too high when using optical flow navigation bool NavEKF2_core::getHeightControlLimit(float &height) const { // only ask for limiting if we are doing optical flow navigation if (frontend._fusionModeGPS == 3) { // If are doing optical flow nav, ensure the height above ground is within range finder limits after accounting for vehicle tilt and control errors height = max(float(_rng.max_distance_cm()) * 0.007f - 1.0f, 1.0f); return true; } else { return false; } } // return the Euler roll, pitch and yaw angle in radians void NavEKF2_core::getEulerAngles(Vector3f &euler) const { outputDataNew.quat.to_euler(euler.x, euler.y, euler.z); euler = euler - _ahrs->get_trim(); } // return body axis gyro bias estimates in rad/sec void NavEKF2_core::getGyroBias(Vector3f &gyroBias) const { if (dtIMUavg < 1e-6f) { gyroBias.zero(); return; } gyroBias = stateStruct.gyro_bias / dtIMUavg; } // return body axis gyro scale factor error as a percentage void NavEKF2_core::getGyroScaleErrorPercentage(Vector3f &gyroScale) const { if (!statesInitialised) { gyroScale.x = gyroScale.y = gyroScale.z = 0; return; } gyroScale.x = 100.0f/stateStruct.gyro_scale.x - 100.0f; gyroScale.y = 100.0f/stateStruct.gyro_scale.y - 100.0f; gyroScale.z = 100.0f/stateStruct.gyro_scale.z - 100.0f; } // return tilt error convergence metric void NavEKF2_core::getTiltError(float &ang) const { ang = tiltErrFilt; } // return the transformation matrix from XYZ (body) to NED axes void NavEKF2_core::getRotationBodyToNED(Matrix3f &mat) const { Vector3f trim = _ahrs->get_trim(); outputDataNew.quat.rotation_matrix(mat); mat.rotateXYinv(trim); } // return the quaternions defining the rotation from NED to XYZ (body) axes void NavEKF2_core::getQuaternion(Quaternion& ret) const { ret = outputDataNew.quat; } // return the amount of yaw angle change due to the last yaw angle reset in radians // returns the time of the last yaw angle reset or 0 if no reset has ever occurred uint32_t NavEKF2_core::getLastYawResetAngle(float &yawAng) { yawAng = yawResetAngle; return lastYawReset_ms; } // return the NED wind speed estimates in m/s (positive is air moving in the direction of the axis) void NavEKF2_core::getWind(Vector3f &wind) const { wind.x = stateStruct.wind_vel.x; wind.y = stateStruct.wind_vel.y; wind.z = 0.0f; // currently don't estimate this } // return NED velocity in m/s // void NavEKF2_core::getVelNED(Vector3f &vel) const { vel = outputDataNew.velocity; } // Return the rate of change of vertical position in the down diection (dPosD/dt) in m/s float NavEKF2_core::getPosDownDerivative(void) const { // return the value calculated from a complmentary filer applied to the EKF height and vertical acceleration return posDownDerivative; } // This returns the specific forces in the NED frame void NavEKF2_core::getAccelNED(Vector3f &accelNED) const { accelNED = velDotNED; accelNED.z -= GRAVITY_MSS; } // return the Z-accel bias estimate in m/s^2 void NavEKF2_core::getAccelZBias(float &zbias) const { if (dtIMUavg > 0) { zbias = stateStruct.accel_zbias / dtIMUavg; } else { zbias = 0; } } // Return the last calculated NED position relative to the reference point (m). // if a calculated solution is not available, use the best available data and return false bool NavEKF2_core::getPosNED(Vector3f &pos) const { // The EKF always has a height estimate regardless of mode of operation pos.z = outputDataNew.position.z; // There are three modes of operation, absolute position (GPS fusion), relative position (optical flow fusion) and constant position (no position estimate available) nav_filter_status status; getFilterStatus(status); if (PV_AidingMode != AID_NONE) { // This is the normal mode of operation where we can use the EKF position states pos.x = outputDataNew.position.x; pos.y = outputDataNew.position.y; return true; } else { // In constant position mode the EKF position states are at the origin, so we cannot use them as a position estimate if(validOrigin) { if ((_ahrs->get_gps().status() >= AP_GPS::GPS_OK_FIX_2D)) { // If the origin has been set and we have GPS, then return the GPS position relative to the origin const struct Location &gpsloc = _ahrs->get_gps().location(); Vector2f tempPosNE = location_diff(EKF_origin, gpsloc); pos.x = tempPosNE.x; pos.y = tempPosNE.y; return false; } else { // If no GPS fix is available, all we can do is provide the last known position pos.x = outputDataNew.position.x; pos.y = outputDataNew.position.y; return false; } } else { // If the origin has not been set, then we have no means of providing a relative position pos.x = 0.0f; pos.y = 0.0f; return false; } } return false; } // return the estimated height above ground level bool NavEKF2_core::getHAGL(float &HAGL) const { HAGL = terrainState - outputDataNew.position.z; // If we know the terrain offset and altitude, then we have a valid height above ground estimate return !hgtTimeout && gndOffsetValid && healthy(); } // Return the last calculated latitude, longitude and height in WGS-84 // If a calculated location isn't available, return a raw GPS measurement // The status will return true if a calculation or raw measurement is available // The getFilterStatus() function provides a more detailed description of data health and must be checked if data is to be used for flight control bool NavEKF2_core::getLLH(struct Location &loc) const { if(validOrigin) { // Altitude returned is an absolute altitude relative to the WGS-84 spherioid loc.alt = EKF_origin.alt - outputDataNew.position.z*100; loc.flags.relative_alt = 0; loc.flags.terrain_alt = 0; // there are three modes of operation, absolute position (GPS fusion), relative position (optical flow fusion) and constant position (no aiding) nav_filter_status status; getFilterStatus(status); if (status.flags.horiz_pos_abs || status.flags.horiz_pos_rel) { loc.lat = EKF_origin.lat; loc.lng = EKF_origin.lng; location_offset(loc, outputDataNew.position.x, outputDataNew.position.y); return true; } else { // we could be in constant position mode becasue the vehicle has taken off without GPS, or has lost GPS // in this mode we cannot use the EKF states to estimate position so will return the best available data if ((_ahrs->get_gps().status() >= AP_GPS::GPS_OK_FIX_2D)) { // we have a GPS position fix to return const struct Location &gpsloc = _ahrs->get_gps().location(); loc.lat = gpsloc.lat; loc.lng = gpsloc.lng; return true; } else { // if no GPS fix, provide last known position before entering the mode location_offset(loc, lastKnownPositionNE.x, lastKnownPositionNE.y); return false; } } } else { // If no origin has been defined for the EKF, then we cannot use its position states so return a raw // GPS reading if available and return false if ((_ahrs->get_gps().status() >= AP_GPS::GPS_OK_FIX_3D)) { const struct Location &gpsloc = _ahrs->get_gps().location(); loc = gpsloc; loc.flags.relative_alt = 0; loc.flags.terrain_alt = 0; } return false; } } // return the horizontal speed limit in m/s set by optical flow sensor limits // return the scale factor to be applied to navigation velocity gains to compensate for increase in velocity noise with height when using optical flow void NavEKF2_core::getEkfControlLimits(float &ekfGndSpdLimit, float &ekfNavVelGainScaler) const { if (PV_AidingMode == AID_RELATIVE) { // allow 1.0 rad/sec margin for angular motion ekfGndSpdLimit = max((frontend._maxFlowRate - 1.0f), 0.0f) * max((terrainState - stateStruct.position[2]), rngOnGnd); // use standard gains up to 5.0 metres height and reduce above that ekfNavVelGainScaler = 4.0f / max((terrainState - stateStruct.position[2]),4.0f); } else { ekfGndSpdLimit = 400.0f; //return 80% of max filter speed ekfNavVelGainScaler = 1.0f; } } // return the LLH location of the filters NED origin bool NavEKF2_core::getOriginLLH(struct Location &loc) const { if (validOrigin) { loc = EKF_origin; } return validOrigin; } // return earth magnetic field estimates in measurement units / 1000 void NavEKF2_core::getMagNED(Vector3f &magNED) const { magNED = stateStruct.earth_magfield * 1000.0f; } // return body magnetic field estimates in measurement units / 1000 void NavEKF2_core::getMagXYZ(Vector3f &magXYZ) const { magXYZ = stateStruct.body_magfield*1000.0f; } // return the innovations for the NED Pos, NED Vel, XYZ Mag and Vtas measurements void NavEKF2_core::getInnovations(Vector3f &velInnov, Vector3f &posInnov, Vector3f &magInnov, float &tasInnov, float &yawInnov) const { velInnov.x = innovVelPos[0]; velInnov.y = innovVelPos[1]; velInnov.z = innovVelPos[2]; posInnov.x = innovVelPos[3]; posInnov.y = innovVelPos[4]; posInnov.z = innovVelPos[5]; magInnov.x = 1e3f*innovMag[0]; // Convert back to sensor units magInnov.y = 1e3f*innovMag[1]; // Convert back to sensor units magInnov.z = 1e3f*innovMag[2]; // Convert back to sensor units tasInnov = innovVtas; yawInnov = innovYaw; } // return the innovation consistency test ratios for the velocity, position, magnetometer and true airspeed measurements // this indicates the amount of margin available when tuning the various error traps // also return the current offsets applied to the GPS position measurements void NavEKF2_core::getVariances(float &velVar, float &posVar, float &hgtVar, Vector3f &magVar, float &tasVar, Vector2f &offset) const { velVar = sqrtf(velTestRatio); posVar = sqrtf(posTestRatio); hgtVar = sqrtf(hgtTestRatio); magVar.x = sqrtf(magTestRatio.x); magVar.y = sqrtf(magTestRatio.y); magVar.z = sqrtf(magTestRatio.z); tasVar = sqrtf(tasTestRatio); offset = gpsPosGlitchOffsetNE; } /* return the filter fault status as a bitmasked integer 0 = quaternions are NaN 1 = velocities are NaN 2 = badly conditioned X magnetometer fusion 3 = badly conditioned Y magnetometer fusion 5 = badly conditioned Z magnetometer fusion 6 = badly conditioned airspeed fusion 7 = badly conditioned synthetic sideslip fusion 7 = filter is not initialised */ void NavEKF2_core::getFilterFaults(uint8_t &faults) const { faults = (stateStruct.quat.is_nan()<<0 | stateStruct.velocity.is_nan()<<1 | faultStatus.bad_xmag<<2 | faultStatus.bad_ymag<<3 | faultStatus.bad_zmag<<4 | faultStatus.bad_airspeed<<5 | faultStatus.bad_sideslip<<6 | !statesInitialised<<7); } /* return filter timeout status as a bitmasked integer 0 = position measurement timeout 1 = velocity measurement timeout 2 = height measurement timeout 3 = magnetometer measurement timeout 4 = true airspeed measurement timeout 5 = unassigned 6 = unassigned 7 = unassigned */ void NavEKF2_core::getFilterTimeouts(uint8_t &timeouts) const { timeouts = (posTimeout<<0 | velTimeout<<1 | hgtTimeout<<2 | magTimeout<<3 | tasTimeout<<4); } /* Return a filter function status that indicates: Which outputs are valid If the filter has detected takeoff If the filter has activated the mode that mitigates against ground effect static pressure errors If GPS data is being used */ void NavEKF2_core::getFilterStatus(nav_filter_status &status) const { // init return value status.value = 0; bool doingFlowNav = (PV_AidingMode == AID_RELATIVE) && flowDataValid; bool doingWindRelNav = !tasTimeout && assume_zero_sideslip(); bool doingNormalGpsNav = !posTimeout && (PV_AidingMode == AID_ABSOLUTE); bool someVertRefData = (!velTimeout && useGpsVertVel) || !hgtTimeout; bool someHorizRefData = !(velTimeout && posTimeout && tasTimeout) || doingFlowNav; bool optFlowNavPossible = flowDataValid && (frontend._fusionModeGPS == 3); bool gpsNavPossible = !gpsNotAvailable && (PV_AidingMode == AID_ABSOLUTE) && gpsGoodToAlign; bool filterHealthy = healthy() && tiltAlignComplete && yawAlignComplete; // set individual flags status.flags.attitude = !stateStruct.quat.is_nan() && filterHealthy; // attitude valid (we need a better check) status.flags.horiz_vel = someHorizRefData && filterHealthy; // horizontal velocity estimate valid status.flags.vert_vel = someVertRefData && filterHealthy; // vertical velocity estimate valid status.flags.horiz_pos_rel = ((doingFlowNav && gndOffsetValid) || doingWindRelNav || doingNormalGpsNav) && filterHealthy; // relative horizontal position estimate valid status.flags.horiz_pos_abs = doingNormalGpsNav && filterHealthy; // absolute horizontal position estimate valid status.flags.vert_pos = !hgtTimeout && filterHealthy; // vertical position estimate valid status.flags.terrain_alt = gndOffsetValid && filterHealthy; // terrain height estimate valid status.flags.const_pos_mode = (PV_AidingMode == AID_NONE) && filterHealthy; // constant position mode status.flags.pred_horiz_pos_rel = (optFlowNavPossible || gpsNavPossible) && filterHealthy; // we should be able to estimate a relative position when we enter flight mode status.flags.pred_horiz_pos_abs = gpsNavPossible && filterHealthy; // we should be able to estimate an absolute position when we enter flight mode status.flags.takeoff_detected = takeOffDetected; // takeoff for optical flow navigation has been detected status.flags.takeoff = expectGndEffectTakeoff; // The EKF has been told to expect takeoff and is in a ground effect mitigation mode status.flags.touchdown = expectGndEffectTouchdown; // The EKF has been told to detect touchdown and is in a ground effect mitigation mode status.flags.using_gps = (imuSampleTime_ms - lastPosPassTime_ms) < 4000; status.flags.gps_glitching = !gpsAccuracyGood; // The GPS is glitching } /* return filter gps quality check status */ void NavEKF2_core::getFilterGpsStatus(nav_gps_status &faults) const { // init return value faults.value = 0; // set individual flags faults.flags.bad_sAcc = gpsCheckStatus.bad_sAcc; // reported speed accuracy is insufficient faults.flags.bad_hAcc = gpsCheckStatus.bad_hAcc; // reported horizontal position accuracy is insufficient faults.flags.bad_yaw = gpsCheckStatus.bad_yaw; // EKF heading accuracy is too large for GPS use faults.flags.bad_sats = gpsCheckStatus.bad_sats; // reported number of satellites is insufficient faults.flags.bad_horiz_drift = gpsCheckStatus.bad_horiz_drift; // GPS horizontal drift is too large to start using GPS (check assumes vehicle is static) faults.flags.bad_hdop = gpsCheckStatus.bad_hdop; // reported HDoP is too large to start using GPS faults.flags.bad_vert_vel = gpsCheckStatus.bad_vert_vel; // GPS vertical speed is too large to start using GPS (check assumes vehicle is static) faults.flags.bad_fix = gpsCheckStatus.bad_fix; // The GPS cannot provide the 3D fix required faults.flags.bad_horiz_vel = gpsCheckStatus.bad_horiz_vel; // The GPS horizontal speed is excessive (check assumes the vehicle is static) } // send an EKF_STATUS message to GCS void NavEKF2_core::send_status_report(mavlink_channel_t chan) { // get filter status nav_filter_status filt_state; getFilterStatus(filt_state); // prepare flags uint16_t flags = 0; if (filt_state.flags.attitude) { flags |= EKF_ATTITUDE; } if (filt_state.flags.horiz_vel) { flags |= EKF_VELOCITY_HORIZ; } if (filt_state.flags.vert_vel) { flags |= EKF_VELOCITY_VERT; } if (filt_state.flags.horiz_pos_rel) { flags |= EKF_POS_HORIZ_REL; } if (filt_state.flags.horiz_pos_abs) { flags |= EKF_POS_HORIZ_ABS; } if (filt_state.flags.vert_pos) { flags |= EKF_POS_VERT_ABS; } if (filt_state.flags.terrain_alt) { flags |= EKF_POS_VERT_AGL; } if (filt_state.flags.const_pos_mode) { flags |= EKF_CONST_POS_MODE; } if (filt_state.flags.pred_horiz_pos_rel) { flags |= EKF_PRED_POS_HORIZ_REL; } if (filt_state.flags.pred_horiz_pos_abs) { flags |= EKF_PRED_POS_HORIZ_ABS; } // get variances float velVar, posVar, hgtVar, tasVar; Vector3f magVar; Vector2f offset; getVariances(velVar, posVar, hgtVar, magVar, tasVar, offset); // send message mavlink_msg_ekf_status_report_send(chan, flags, velVar, posVar, hgtVar, magVar.length(), tasVar); } #endif // HAL_CPU_CLASS
39.601626
191
0.690823
[ "3d" ]
5ab084579555c8fa0799507a8d7dea8093b32b38
885
cpp
C++
Scripts/PlayerMovement/SliceSkill.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
10
2019-02-25T11:36:23.000Z
2021-11-03T22:51:30.000Z
Scripts/PlayerMovement/SliceSkill.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
146
2019-02-05T13:57:33.000Z
2019-11-07T16:21:31.000Z
Scripts/PlayerMovement/SliceSkill.cpp
FractalPuppy/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
3
2019-11-17T20:49:12.000Z
2020-04-19T17:28:28.000Z
#include "SliceSkill.h" #include "ComponentTransform.h" #include "ComponentBoxTrigger.h" #include "PlayerMovement.h" #include "PlayerStateAttack.h" #include "GameObject.h" #include "imgui.h" #include "JSON.h" SliceSkill::SliceSkill(PlayerMovement* PM, const char* trigger, ComponentBoxTrigger* attackBox) : MeleeSkill(PM, trigger, attackBox) { } SliceSkill::~SliceSkill() { } void SliceSkill::Start() { MeleeSkill::Start(); player->gameobject->transform->LookAtMouse(); // Create the hitbox boxSize = math::float3(150.f, 100.f, 100.f); // Set delay for hit hitDelay = 0.4f; } void SliceSkill::UseSkill() { if (attackBoxTrigger != nullptr) { // Update the hitbox boxPosition = player->transform->up *100.f; //this front stuff isnt working well when rotating the chicken attackBoxTrigger->SetBoxPosition(boxPosition.x, boxPosition.y, boxPosition.z + 100.f); } }
20.581395
108
0.726554
[ "transform" ]
5ab6978ff1a7168ba95970b1c3fc326d55faac6e
7,849
cpp
C++
types/mesh.cpp
LAK132/laklib
25d1f28fceb0ef4d72f6182e0859418f95350db1
[ "MIT" ]
null
null
null
types/mesh.cpp
LAK132/laklib
25d1f28fceb0ef4d72f6182e0859418f95350db1
[ "MIT" ]
null
null
null
types/mesh.cpp
LAK132/laklib
25d1f28fceb0ef4d72f6182e0859418f95350db1
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2018 LAK132 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 "types/mesh.h" namespace lak { // // vertexBuffer_t // vertexBuffer_t::vertexBuffer_t() {} vertexBuffer_t::~vertexBuffer_t() { if (init) glDeleteBuffers(1, &buffer); } void vertexBuffer_t::bind() { if (!init) { glGenBuffers(1, &buffer); init = true; } #ifdef LTEST LASSERT(init, "Buffer not initialised"); #endif // LTEST GLint current; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &current); if (current != buffer) glBindBuffer(GL_ARRAY_BUFFER, buffer); #ifdef LTEST glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &current); LASSERT(current == buffer, "Buffer bind failed"); #endif } bool vertexBuffer_t::update() { bind(); vector<stride_vector*> groupElems = {}; size_t groupStride = 0; bool dirty = false; for (auto &elem : elements) if (elem.second.dirty) { dirty = true; break; } if (dirty) { groupElems.reserve(elements.size()); for (auto &elem : elements) { if (!elem.second.active || !elem.second.data.stride) continue; elem.second.dirty = false; elem.second.offset = groupStride; groupElems.push_back(&(elem.second.data)); groupStride += elem.second.data.stride; } for (auto &elem : elements) elem.second.interlacedStride = groupStride; stride_vector interlaced = stride_vector::interleave(groupElems); if (size && interlaced.size() == size) { glBufferSubData(GL_ARRAY_BUFFER, 0, size, &interlaced.data[0]); } else { size = interlaced.size(); glBufferData(GL_ARRAY_BUFFER, size, &interlaced.data[0], usage); } #ifdef LTEST if (!size) { LDEBUG("Buffer empty"); LDEBUG("Interlaced Size: " << interlaced.size()); } decltype(interlaced.data) check; check.resize(size); glGetBufferSubData(GL_ARRAY_BUFFER, 0, size, &check[0]); if (check != interlaced.data) { LDEBUG("Check size: " << check.size()); LDEBUG("Interlaced size: " << interlaced.data.size()); } LASSERT(check == interlaced.data, "Incorrect buffer data"); #endif // LTEST } return dirty; } // // vertexArray_t // vertexArray_t::~vertexArray_t() { if (!vertArray) return; glDeleteVertexArrays(1, &vertArray); glDeleteBuffers(1, &indexBuffer); } void vertexArray_t::init() { if (vertArray) return; glGenVertexArrays(1, &vertArray); glGenBuffers(1, &indexBuffer); } void vertexArray_t::bind() { GLint current; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &current); if (current != vertArray) glBindVertexArray(vertArray); glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &current); if (current != indexBuffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); #ifdef LTEST glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &current); LASSERT(current == vertArray, "Failed to bind vertex array"); glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &current); LASSERT(current == indexBuffer, "Failed to bind index buffer"); #endif // LTEST } // // mesh_t // void mesh_t::update() { if (!vertArray.vertArray) vertArray.init(); vertArray.bind(); #ifdef LTEST if (shader.use_count() == 0) LDEBUG("No shader"); #endif // LTEST for (auto &buffer : vertArray.buffers) { if (buffer.update()) if (shader.use_count() > 0) for (auto &element : buffer.elements) { const auto &attribute = shader->attributes.find(element.first); if (attribute != shader->attributes.end()) { if (element.second.active) { glEnableVertexAttribArray(attribute->second.position); glVertexAttribDivisor(attribute->second.position, element.second.divisor); glVertexAttribPointer(attribute->second.position, element.second.size, element.second.type, element.second.normalised, element.second.interlacedStride, (GLvoid*)element.second.offset); attribute->second.active = true; #ifdef LTEST LASSERT(attribute->second.size == element.second.size, "Shader and buffer type size don't match"); LASSERT(attribute->second.type == element.second.type, "Shader and buffer type don't match"); #endif // LTEST } else { glDisableVertexAttribArray(attribute->second.position); attribute->second.active = false; } } } } if (index.size() > 0) { indexCount = index.size(); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(GLuint), &(index[0]), GL_STATIC_DRAW); #ifdef LTEST vector<GLuint> check; check.resize(indexCount); glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * sizeof(GLuint), &check[0]); LASSERT(check == index, "Incorrect index buffer data"); #endif // LTEST } #ifdef LTEST else LDEBUG("No indices"); #endif // LTEST dirty = false; } void mesh_t::draw(GLsizei count, const void *indexOffset) { if (!count) return; if (dirty) update(); else vertArray.bind(); #ifdef LTEST if (dirty) LERROR("Dirty"); LASSERT(shader.use_count(), "No shader"); if (!index.size()) LDEBUG("Index vector empty"); LASSERT(indexCount, "No indices"); #endif // LTEST if (shader.use_count() > 0) shader->enable(); for (auto &texture : textures) if (texture.second.use_count() > 0) texture.second->bind(); if (index.size() > 0) glDrawElementsInstanced(drawMode, indexCount, GL_UNSIGNED_INT, indexOffset, count); else glDrawArraysInstanced(drawMode, 0, indexCount, count); } }
32.433884
208
0.568353
[ "mesh", "vector" ]
5abc484e0254e1bea5377c7127f3166c20c46240
1,627
cpp
C++
SPOJ/ABCDEF(Math, logic, Vector upper lower bound).cpp
abusomani/DS-Algo
b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba
[ "Unlicense" ]
null
null
null
SPOJ/ABCDEF(Math, logic, Vector upper lower bound).cpp
abusomani/DS-Algo
b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba
[ "Unlicense" ]
null
null
null
SPOJ/ABCDEF(Math, logic, Vector upper lower bound).cpp
abusomani/DS-Algo
b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba
[ "Unlicense" ]
null
null
null
//Sometimes I feel like giving up, then I remember I have a lot of motherfuckers to prove wrong! //@BEGIN OF SOURCE CODE ( By Abhishek Somani) /* (axb) + c = d x (e+f) // Both sides can be computed in O(n^3) Now as numbers as distinct, for each occurence of LHS, find all occurence in RHS. summation of these is answer. */ #include <bits/stdc++.h> using namespace std; #define fastio \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) typedef long long ll; const ll MOD = 1000000007; int main() { fastio; //freopen('input.txt','r',stdin); //freopen('output.txt','w',stdout); ll N, K, x; cin >> N; ll arr[N]; vector<ll> LHS, RHS; for (int i = 0; i < N; i++) cin >> arr[i]; // all possible (a x b) + c == LHS for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) LHS.push_back((arr[i] * arr[j]) + arr[k]); // all possible d x (e + f) == RHS ( d != 0) for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) if (arr[k] != 0) RHS.push_back((arr[i] + arr[j]) * arr[k]); sort(LHS.begin(), LHS.end()); sort(RHS.begin(), RHS.end()); ll ans = 0; for (int i = 0; i < LHS.size(); i++) { ll low = lower_bound(RHS.begin(), RHS.end(), LHS[i]) - RHS.begin(); ll high = upper_bound(RHS.begin(), RHS.end(), LHS[i]) - RHS.begin(); ans += (high - low); } cout << ans << endl; return 0; } // END OF SOURCE CODE
28.051724
115
0.492932
[ "vector" ]
5abd75aeb3a012dd08fca1d750db886bb25f49f1
10,526
hpp
C++
SDK/ARKSurvivalEvolved_WeapTekSniper_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_WeapTekSniper_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_WeapTekSniper_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_WeapTekSniper_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function WeapTekSniper.WeapTekSniper_C.BPShouldDealDamage struct AWeapTekSniper_C_BPShouldDealDamage_Params { class AActor** TestActor; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.Try Enable XRay struct AWeapTekSniper_C_Try_Enable_XRay_Params { }; // Function WeapTekSniper.WeapTekSniper_C.Get Overheat Duration struct AWeapTekSniper_C_Get_Overheat_Duration_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPStopPenetratingAtHit struct AWeapTekSniper_C_BPStopPenetratingAtHit_Params { struct FHitResult CurrentHit; // (Parm, OutParm, ReferenceParm) bool* bIsEntryHit; // (Parm, ZeroConstructor, IsPlainOldData) float* CurrentDistance; // (Parm, ZeroConstructor, IsPlainOldData) float* CurrentMaxDistance; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPWeaponDealDamage struct AWeapTekSniper_C_BPWeaponDealDamage_Params { struct FHitResult Impact; // (Parm, OutParm, ReferenceParm) struct FVector ShootDir; // (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) int* DamageAmount; // (Parm, ZeroConstructor, IsPlainOldData) class UClass** DamageType; // (Parm, ZeroConstructor, IsPlainOldData) float* Impulse; // (Parm, ZeroConstructor, IsPlainOldData) int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPAdjustAmmoPerShot struct AWeapTekSniper_C_BPAdjustAmmoPerShot_Params { int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPToggleAccessory struct AWeapTekSniper_C_BPToggleAccessory_Params { }; // Function WeapTekSniper.WeapTekSniper_C.AllowTargeting struct AWeapTekSniper_C_AllowTargeting_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPSpawnImpactEffects struct AWeapTekSniper_C_BPSpawnImpactEffects_Params { struct FHitResult Impact; // (Parm, OutParm, ReferenceParm) struct FVector ShootDir; // (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) bool* bIsEntryHit; // (Parm, ZeroConstructor, IsPlainOldData) float* WeaponMaxRange; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPOnScoped struct AWeapTekSniper_C_BPOnScoped_Params { }; // Function WeapTekSniper.WeapTekSniper_C.BPAppliedPrimalItemToWeapon struct AWeapTekSniper_C_BPAppliedPrimalItemToWeapon_Params { }; // Function WeapTekSniper.WeapTekSniper_C.ReceiveDestroyed struct AWeapTekSniper_C_ReceiveDestroyed_Params { }; // Function WeapTekSniper.WeapTekSniper_C.Has Ammo struct AWeapTekSniper_C_Has_Ammo_Params { int MinAmount; // (Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPToggleAccessoryFailed struct AWeapTekSniper_C_BPToggleAccessoryFailed_Params { }; // Function WeapTekSniper.WeapTekSniper_C.BPCanToggleAccessory struct AWeapTekSniper_C_BPCanToggleAccessory_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.UpdateMeshOverheat Effect struct AWeapTekSniper_C_UpdateMeshOverheat_Effect_Params { class USkeletalMeshComponent* Mesh; // (Parm, ZeroConstructor, IsPlainOldData) float amount; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.Tick X-Ray Sound struct AWeapTekSniper_C_Tick_X_Ray_Sound_Params { }; // Function WeapTekSniper.WeapTekSniper_C.Is X-Ray Active struct AWeapTekSniper_C_Is_X_Ray_Active_Params { bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.Show X-Ray Enabled Message struct AWeapTekSniper_C_Show_X_Ray_Enabled_Message_Params { bool Enabled; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.SniperMessage struct AWeapTekSniper_C_SniperMessage_Params { class FString Message; // (Parm, ZeroConstructor) }; // Function WeapTekSniper.WeapTekSniper_C.GetOwnerCharacter struct AWeapTekSniper_C_GetOwnerCharacter_Params { class AShooterCharacter* AsShooterCharacter; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPWeaponZoom struct AWeapTekSniper_C_BPWeaponZoom_Params { bool* bZoomingIn; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPWeaponCanFire struct AWeapTekSniper_C_BPWeaponCanFire_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.BPFireWeapon struct AWeapTekSniper_C_BPFireWeapon_Params { }; // Function WeapTekSniper.WeapTekSniper_C.ReceiveTick struct AWeapTekSniper_C_ReceiveTick_Params { float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.GetIs Overheated struct AWeapTekSniper_C_GetIs_Overheated_Params { bool bRetOverheated; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.UserConstructionScript struct AWeapTekSniper_C_UserConstructionScript_Params { }; // Function WeapTekSniper.WeapTekSniper_C.FadeOutOverheatParticles__FinishedFunc struct AWeapTekSniper_C_FadeOutOverheatParticles__FinishedFunc_Params { }; // Function WeapTekSniper.WeapTekSniper_C.FadeOutOverheatParticles__UpdateFunc struct AWeapTekSniper_C_FadeOutOverheatParticles__UpdateFunc_Params { }; // Function WeapTekSniper.WeapTekSniper_C.Overheated struct AWeapTekSniper_C_Overheated_Params { bool JustFired; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.AddHeat struct AWeapTekSniper_C_AddHeat_Params { bool JustFired; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.NotOverheated struct AWeapTekSniper_C_NotOverheated_Params { }; // Function WeapTekSniper.WeapTekSniper_C.SetScoped struct AWeapTekSniper_C_SetScoped_Params { bool Scoped; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function WeapTekSniper.WeapTekSniper_C.ClearHitPrimalCharacterAlready struct AWeapTekSniper_C_ClearHitPrimalCharacterAlready_Params { }; // Function WeapTekSniper.WeapTekSniper_C.ClearHitPrimalStructureAlready struct AWeapTekSniper_C_ClearHitPrimalStructureAlready_Params { }; // Function WeapTekSniper.WeapTekSniper_C.ExecuteUbergraph_WeapTekSniper struct AWeapTekSniper_C_ExecuteUbergraph_WeapTekSniper_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
44.041841
176
0.561087
[ "mesh" ]
62bf7c696dddca0bbc3d534169a5855d1a33b18b
691
cpp
C++
Online-Judges/CodeForces/1100/1288B.Yet_Another_Meme_Problem.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/CodeForces/1100/1288B.Yet_Another_Meme_Problem.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/CodeForces/1100/1288B.Yet_Another_Meme_Problem.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int llint; typedef unsigned long long int ullint; typedef short int sint; #define endn "\n" #define umap unordered_map #define uset unordered_set #define pb push_back template<typename tem> void print_vector(vector<tem> &vec) { for (auto &ele : vec) cout<<ele<<" "; cout << "\n";} int test() { int A, B; cin >> A >> B; cout << (A * 1LL * (to_string(B+1).length() - 1)) << endn; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; while (n--) { test(); } } // Solved By: shihab4t // Monday, August 02, 2021 | 10:22:13 AM (BST)
20.323529
62
0.612156
[ "vector" ]
62c381273e08a5bed92a8d7b8d8a49f6460f0e2e
638
cpp
C++
acmicpc/13334.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/13334.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/13334.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> #include <functional> #include <algorithm> #include <vector> #include <queue> using namespace std; int n, l, x, y, ans; vector<pair<int, int>> vec; priority_queue<int, vector<int>, greater<int>> que; int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); cin >> n; for (int i=0; i<n; ++i) { cin >> x >> y; vec.push_back({max(x, y), min(x, y)}); } cin >> l; sort(vec.begin(), vec.end()); for (int i=0; i<n; ++i) { auto [y, x] = vec[i]; que.push(x); while (!que.empty() && que.top() < y - l) que.pop(); ans = max(ans, (int)que.size()); } cout << ans << '\n'; return 0; }
15.560976
51
0.561129
[ "vector" ]
62cc7378127d2e6dbd6dce5b5025a0c0bb81e804
23,731
cpp
C++
tools/extractors/extract_battlescape_map.cpp
trevortomesh/OpenApoc
53cd163889fbfd21a9c128183427dad4255ac1a3
[ "MIT" ]
1
2020-11-10T18:31:44.000Z
2020-11-10T18:31:44.000Z
tools/extractors/extract_battlescape_map.cpp
trevortomesh/OpenApoc
53cd163889fbfd21a9c128183427dad4255ac1a3
[ "MIT" ]
null
null
null
tools/extractors/extract_battlescape_map.cpp
trevortomesh/OpenApoc
53cd163889fbfd21a9c128183427dad4255ac1a3
[ "MIT" ]
null
null
null
#include "framework/data.h" #include "framework/framework.h" #include "game/state/battle/battle.h" #include "game/state/gamestate.h" #include "game/state/rules/battle/battlemap.h" #include "library/strings_format.h" #include "tools/extractors/common/battlemap.h" #include "tools/extractors/extractors.h" #include <unordered_map> #include <map> namespace OpenApoc { void InitialGameStateExtractor::extractBattlescapeMapFromPath(GameState &state, const UString dirName, const int index) const { UString tilePrefix = format("%s_", dirName); UString map_prefix = "xcom3/maps/"; UString mapunits_suffix = "/mapunits/"; bool baseMap = dirName == "37base"; BuildingDatStructure bdata; { auto fileName = dirName + UString("/building.dat"); auto datFileName = map_prefix + fileName; auto inFile = fw().data->fs.open(datFileName); if (!inFile) { LogError("Failed to open \"%s\"", fileName); return; } inFile.read((char *)&bdata, sizeof(bdata)); if (!inFile) { LogError("Failed to read entry in \"%s\"", fileName); return; } } RubbleDatStructure rdata; { auto fileName = dirName + mapunits_suffix + UString("rubble.dat"); auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (!inFile) { LogError("Failed to open \"%s\"", fileName); return; } inFile.read((char *)&rdata, sizeof(rdata)); if (!inFile) { LogError("Failed to read entry in \"%s\"", fileName); return; } } int firstExitIdx = 0; { auto fileName = dirName + mapunits_suffix + UString("grounmap.dat"); auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (!inFile) { LogError("Failed to open \"%s\"", fileName); return; } auto fileSize = inFile.size(); auto objectCount = fileSize / sizeof(struct BattleMapPartEntry); firstExitIdx = objectCount - 4; } auto m = mksp<BattleMap>(); UString id = format("%s%s", BattleMap::getPrefix(), this->battleMapPaths[index]); m->id = id; m->chunk_size = {bdata.chunk_x, bdata.chunk_y, bdata.chunk_z}; m->max_battle_size = {bdata.battle_x, bdata.battle_y, bdata.battle_z}; uint8_t north_flag = 0b0001; uint8_t east_flag = 0b0010; uint8_t south_flag = 0b0100; uint8_t west_flag = 0b1000; m->allow_entrance[MapDirection::North] = bdata.allow_entrance_from & north_flag; m->allow_entrance[MapDirection::East] = bdata.allow_entrance_from & east_flag; m->allow_entrance[MapDirection::South] = bdata.allow_entrance_from & south_flag; m->allow_entrance[MapDirection::West] = bdata.allow_entrance_from & west_flag; m->allow_exit[MapDirection::North] = bdata.allow_exit_from & north_flag; m->allow_exit[MapDirection::East] = bdata.allow_exit_from & east_flag; m->allow_exit[MapDirection::South] = bdata.allow_exit_from & south_flag; m->allow_exit[MapDirection::West] = bdata.allow_exit_from & west_flag; m->entrance_level_min = bdata.entrance_min_level; m->entrance_level_max = bdata.entrance_max_level; m->exit_level_min = bdata.exit_min_level; m->exit_level_max = bdata.exit_max_level; m->tilesets.emplace_back(tilePrefix.substr(0, tilePrefix.length() - 1)); // Side 0 = exits by X axis, Side 1 = exits by Y axis for (int l = 0; l < 15; l++) { for (int e = 0; e < 14; e++) { /* As the exits array isn't uint32_t aligned, pull it out rather than passing a * reference directly to the Vec3<> constructor * Copying it out to the stack here allows the compiler to do whatever lowering is * necessary to realign the reads*/ uint32_t val = bdata.exits[0][l].exits[e]; if (val != 0xffffffff) m->exitsX.emplace(val, 0, l); val = bdata.exits[1][l].exits[e]; if (val != 0xffffffff) m->exitsY.emplace(0, val, l); } } if (bdata.destroyed_ground_idx != 0) m->destroyed_ground_tile = {&state, format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "GD_", (unsigned)bdata.destroyed_ground_idx)}; for (int i = 0; i < 5; i++) { if (rdata.left_wall[i] != 0) { m->rubble_left_wall.emplace_back( &state, format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "LW_", (unsigned)rdata.left_wall[i])); } if (rdata.right_wall[i] != 0) { m->rubble_right_wall.emplace_back( &state, format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "RW_", (unsigned)rdata.right_wall[i])); } if (rdata.feature[i] != 0) { m->rubble_feature.emplace_back(&state, format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "FT_", (unsigned)rdata.feature[i])); } } for (int i = 0; i < 4; i++) { m->exit_grounds.emplace_back(&state, format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "GD_", (unsigned)firstExitIdx + i)); } if (reinforcementTimers.find(dirName) != reinforcementTimers.end()) { m->reinforcementsInterval = reinforcementTimers.at(dirName); } // Trying all possible names, because game actually has some maps missing sectors in the middle // (like, 05RESCUE has no SEC04 but has SEC05 and on) auto sdtFiles = fw().data->fs.enumerateDirectory(map_prefix + "/" + dirName, ".sdt"); int fileCounter = -1; for (const auto &sdtFile : sdtFiles) { fileCounter++; LogInfo("Reading map %s", sdtFile); /* Trim off '.sdt' to get the base map name */ LogAssert(sdtFile.length() >= 4); auto secName = sdtFile.substr(0, sdtFile.length() - 4); auto sector = secName.substr(secName.length() - 2); int groundCounter = 0; do { UString tilesName; UString secID; if (baseMap) { if (fileCounter == 0) { tilesName = format("%s_%02d", dirName, groundCounter); secID = format("SEC%02d", groundCounter); } else { tilesName = format("%s_%02d", dirName, fileCounter + 15); secID = format("SEC%02d", fileCounter + 15); } } else { tilesName = format("%s_%s", dirName, sector); secID = format("SEC%s", sector); } SecSdtStructure sdata; { auto fileName = dirName + UString("/") + sdtFile; auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (!inFile) { LogInfo("Sector %s not present for map %d", sector, index); continue; } inFile.read((char *)&sdata, sizeof(sdata)); if (!inFile) { LogError("Failed to read entry in \"%s\"", fileName); return; } } auto s = mksp<BattleMapSector>(); s->size = {sdata.chunks_x, sdata.chunks_y, sdata.chunks_z}; s->occurrence_min = sdata.occurrence_min; s->occurrence_max = sdata.occurrence_max; s->sectorTilesName = tilesName; if (tilesName == "40spawn_01") { s->spawnLocations[{&state, "AGENTTYPE_QUEENSPAWN"}].push_back({22, 15, 2}); for (int x = 23; x < 28; x++) { for (int y = 13; y < 18; y++) { s->spawnLocations[{&state, "AGENTTYPE_MULTIWORM_EGG"}].push_back({x, y, 2}); } } for (int x = 16; x < 21; x++) { for (int y = 12; y < 18; y++) { s->spawnLocations[{&state, "AGENTTYPE_MULTIWORM_EGG"}].push_back({x, y, 2}); } } } m->sectors[secID] = s; } while (baseMap && ++groundCounter < 16); } if (bdata.destroyed_ground_idx != 0) m->destroyed_ground_tile = {&state, format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "GD_", (unsigned)bdata.destroyed_ground_idx)}; state.battle_maps[id] = m; } std::map<UString, up<BattleMapSectorTiles>> InitialGameStateExtractor::extractMapSectors(GameState &state, const UString &mapRootName) const { std::map<UString, up<BattleMapSectorTiles>> sectors; UString map_prefix = "xcom3/maps/"; UString dirName = mapRootName; UString tilePrefix = format("%s_", dirName); bool baseMap = mapRootName == "37base"; BuildingDatStructure bdata; { auto fileName = dirName + UString("/building.dat"); auto datFileName = map_prefix + fileName; auto inFile = fw().data->fs.open(datFileName); if (!inFile) { LogError("Failed to open \"%s\"", fileName); return {}; } inFile.read((char *)&bdata, sizeof(bdata)); if (!inFile) { LogError("Failed to read entry in \"%s\"", fileName); return {}; } } auto sdtFiles = fw().data->fs.enumerateDirectory(map_prefix + "/" + dirName, ".sdt"); int fileCounter = -1; for (const auto &sdtFile : sdtFiles) { fileCounter++; LogInfo("Reading map %s", sdtFile); /* Trim off '.sdt' to get the base map name */ LogAssert(sdtFile.length() >= 4); auto secName = sdtFile.substr(0, sdtFile.length() - 4); auto sector = secName.substr(secName.length() - 2); // We will make 16 total grounds int groundCounter = 0; do { UString tilesName; if (baseMap) { if (fileCounter == 0) { tilesName = format("%s_%02d", dirName, groundCounter); } else { tilesName = format("%s_%02d", dirName, fileCounter + 15); } } else { tilesName = format("%s_%s", dirName, sector); } up<BattleMapSectorTiles> tiles(new BattleMapSectorTiles()); SecSdtStructure sdata; { auto fileName = dirName + UString("/") + secName + UString(".sdt"); auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (!inFile) { LogInfo("Sector %s not present for map %s", sector, mapRootName); continue; } inFile.read((char *)&sdata, sizeof(sdata)); if (!inFile) { LogError("Failed to read entry in \"%s\"", fileName); return {}; } } // Read LOS blocks { auto fileName = dirName + UString("/") + secName + UString(".sls"); auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (!inFile) { LogError("Failed to open \"%s\"", fileName); return {}; } auto fileSize = inFile.size(); auto objectCount = fileSize / sizeof(struct LineOfSightData); for (unsigned i = 0; i < objectCount; i++) { LineOfSightData ldata; inFile.read((char *)&ldata, sizeof(ldata)); if (!inFile) { LogError("Failed to read entry %d in \"%s\"", i, fileName); return {}; } auto los_block = mksp<BattleMapSector::LineOfSightBlock>(); // Vanilla had inclusive boundaries, and they can go both ways, but we must make // them exclusive int x_min = std::min(ldata.begin_x, ldata.end_x); int x_max = std::max(ldata.begin_x, ldata.end_x); int y_min = std::min(ldata.begin_y, ldata.end_y); int y_max = std::max(ldata.begin_y, ldata.end_y); int z_min = std::min(ldata.begin_z, ldata.end_z); int z_max = std::max(ldata.begin_z, ldata.end_z); los_block->start = {x_min, y_min, z_min}; los_block->end = {x_max + 1, y_max + 1, z_max + 1}; los_block->ai_patrol_priority = ldata.ai_patrol_priority; los_block->ai_target_priority = ldata.ai_target_priority; // If this is alien map, then up the spawn priority for player spawns if (ldata.spawn_priority == 0 && ldata.spawn_type == SPAWN_TYPE_PLAYER) { for (auto &entry : missionObjectives) { if (entry.first == mapRootName) { ldata.spawn_priority = 1; break; } } } los_block->spawn_priority = ldata.spawn_priority; // It only matters if spawn priority is >0, so don't bother bloating xml with // unused // values if (los_block->spawn_priority > 0) { los_block->spawn_large_units = ldata.spawn_large == 1 && z_min != z_max; los_block->spawn_walking_units = ldata.spawn_walkers == 1; // Bases are special // Enemy and player spawn spots are different. // - Player spawns at Civilian (2) // - Enemy spawns at Player (0) // Priority 4 seems to mean noncombatants and priority 2 seems to mean // agents // For enemy spawns, priority 4 is encountered in hangars and 2 in lifts if (baseMap) { switch (ldata.spawn_type) { case SPAWN_TYPE_PLAYER: los_block->spawn_type = SpawnType::Enemy; // Fix this otherwise noone spawns in the lift // since there's so much more spawns in the repair bays los_block->spawn_priority = 2; break; case SPAWN_TYPE_CIVILIAN: if (los_block->spawn_priority == 4) { los_block->spawn_type = SpawnType::Civilian; } else { los_block->spawn_type = SpawnType::Player; } break; case SPAWN_TYPE_ENEMY: los_block->spawn_priority = 0; break; default: // Disable spawning and leave the type to its default value los_block->spawn_priority = 0; break; } } else { switch (ldata.spawn_type) { case SPAWN_TYPE_PLAYER: los_block->spawn_type = SpawnType::Player; break; case SPAWN_TYPE_ENEMY: los_block->spawn_type = SpawnType::Enemy; if (mapRootName == "41food") { los_block->also_allow_civilians = true; } break; case SPAWN_TYPE_CIVILIAN: los_block->spawn_type = SpawnType::Civilian; // Prevent civ spawn on spawn map, this was used to spawn queen if (mapRootName == "40spawn" && (los_block->spawn_priority == 4 || los_block->spawn_priority == 1)) { los_block->spawn_priority = 0; } break; // TacEdit (map editor from vanilla creators) allows values up to 8, // but // they are unused, so we should accommodate for that default: // Disable spawning and leave the type to its default value los_block->spawn_priority = 0; break; } } } tiles->losBlocks.push_back(los_block); } } // Read Loot locations { auto fileName = dirName + UString("/") + secName + UString(".sob"); auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (inFile) { auto fileSize = inFile.size(); auto objectCount = fileSize / sizeof(struct LootLocationData); for (unsigned i = 0; i < objectCount; i++) { LootLocationData ldata; inFile.read((char *)&ldata, sizeof(ldata)); if (!inFile) { LogError("Failed to read entry %d in \"%s\"", i, fileName); return {}; } if (ldata.priority == 0) continue; Organisation::LootPriority lp; switch (ldata.priority) { case 1: lp = Organisation::LootPriority::A; break; case 2: lp = Organisation::LootPriority::B; break; case 3: lp = Organisation::LootPriority::C; break; default: LogError("Encountered invalid loot priority in %d for sector %d", i, sector); return {}; } tiles->loot_locations[{ldata.x, ldata.y, ldata.z}] = lp; } } } // Read sector map { auto fileName = dirName + UString("/") + secName + UString(".smp"); auto expectedFileSize = bdata.chunk_x * bdata.chunk_y * bdata.chunk_z * sdata.chunks_x * sdata.chunks_y * sdata.chunks_z * 4; auto fullPath = map_prefix + fileName; auto inFile = fw().data->fs.open(fullPath); if (!inFile) { LogError("Failed to open \"%s\"", fileName); } auto fileSize = inFile.size(); if (fileSize != expectedFileSize) { LogError("Unexpected filesize %zu - expected %u", fileSize, expectedFileSize); } for (unsigned int z = 0; z < bdata.chunk_z * sdata.chunks_z; z++) { for (unsigned int y = 0; y < bdata.chunk_y * sdata.chunks_y; y++) { for (unsigned int x = 0; x < bdata.chunk_x * sdata.chunks_x; x++) { SmpData tdata; inFile.read((char *)&tdata, sizeof(tdata)); if (!inFile) { LogError("Failed to read entry %d,%d,%d in \"%s\"", x, y, z, fileName); return {}; } // read ground if (tdata.GD != 0) { auto tileName = format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "GD_", (unsigned)tdata.GD); tiles->initial_grounds[Vec3<int>{x, y, z}] = {&state, tileName}; } // read left wall if (tdata.LW != 0) { auto tileName = format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "LW_", (unsigned)tdata.LW); tiles->initial_left_walls[Vec3<int>{x, y, z}] = {&state, tileName}; } // read right wall if (tdata.RW != 0) { auto tileName = format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "RW_", (unsigned)tdata.RW); tiles->initial_right_walls[Vec3<int>{x, y, z}] = {&state, tileName}; } // read scenery if (tdata.FT != 0) { if (baseMap && tdata.FT >= 230 && tdata.FT <= 237) { if (sector == "23") { tiles ->guardianLocations[{ &state, "AGENTTYPE_X-COM_BASE_TURRET_LASER"}] .push_back(Vec3<int>{x, y, z}); } else if (sector == "24") { tiles ->guardianLocations[{ &state, "AGENTTYPE_X-COM_BASE_TURRET_DISRUPTOR"}] .push_back(Vec3<int>{x, y, z}); } else { LogError("Encountered gun emplacement %d in sector %s", tdata.FT, sector); } } else { auto tileName = format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "FT_", (unsigned)tdata.FT); tiles->initial_features[Vec3<int>{x, y, z}] = {&state, tileName}; } } } } } } // Manipulate sector map if (baseMap && fileCounter == 0 && groundCounter != 15) { auto tileName = format("%s%s%s%u", BattleMapPartType::getPrefix(), tilePrefix, "FT_", 78); // key is North South West East (true = occupied, false = vacant) const std::unordered_map<int, std::vector<bool>> PRESENT_ROOMS = { {0, {false, false, false, false}}, {1, {true, false, false, false}}, {2, {false, false, false, true}}, {3, {true, false, false, true}}, {4, {false, true, false, false}}, {5, {true, true, false, false}}, {6, {false, true, false, true}}, {7, {true, true, false, true}}, {8, {false, false, true, false}}, {9, {true, false, true, false}}, {10, {false, false, true, true}}, {11, {true, false, true, true}}, {12, {false, true, true, false}}, {13, {true, true, true, false}}, {14, {false, true, true, true}}}; // Wipe north if (!PRESENT_ROOMS.at(groundCounter).at(0)) { // y=0,y=1 for (int x = 0; x < bdata.chunk_x * sdata.chunks_x; x++) { for (int y = 0; y < 2; y++) { for (int z = 2; z < bdata.chunk_z * sdata.chunks_z; z++) { if (tiles->initial_left_walls.find(Vec3<int>{x, y, z}) != tiles->initial_left_walls.end()) { tiles->initial_left_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_right_walls.find(Vec3<int>{x, y, z}) != tiles->initial_right_walls.end()) { tiles->initial_right_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_grounds.find(Vec3<int>{x, y, z}) != tiles->initial_grounds.end()) { tiles->initial_grounds.erase(Vec3<int>{x, y, z}); } tiles->initial_features[Vec3<int>{x, y, z}] = tiles->initial_features[Vec3<int>{x, y, 0}]; } } } } // Wipe south if (!PRESENT_ROOMS.at(groundCounter).at(1)) { // y = max-1 for (int x = 0; x < bdata.chunk_x * sdata.chunks_x; x++) { for (int y = bdata.chunk_y * sdata.chunks_y - 1; y < bdata.chunk_y * sdata.chunks_y; y++) { for (int z = 2; z < bdata.chunk_z * sdata.chunks_z; z++) { if (tiles->initial_left_walls.find(Vec3<int>{x, y, z}) != tiles->initial_left_walls.end()) { tiles->initial_left_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_right_walls.find(Vec3<int>{x, y, z}) != tiles->initial_right_walls.end()) { tiles->initial_right_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_grounds.find(Vec3<int>{x, y, z}) != tiles->initial_grounds.end()) { tiles->initial_grounds.erase(Vec3<int>{x, y, z}); } tiles->initial_features[Vec3<int>{x, y, z}] = tiles->initial_features[Vec3<int>{x, y, 0}]; } } } } // Wipe west if (!PRESENT_ROOMS.at(groundCounter).at(2)) { // x=0,x=1 for (int x = 0; x < 2; x++) { for (int y = 0; y < bdata.chunk_y * sdata.chunks_y; y++) { for (int z = 2; z < bdata.chunk_z * sdata.chunks_z; z++) { if (tiles->initial_left_walls.find(Vec3<int>{x, y, z}) != tiles->initial_left_walls.end()) { tiles->initial_left_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_right_walls.find(Vec3<int>{x, y, z}) != tiles->initial_right_walls.end()) { tiles->initial_right_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_grounds.find(Vec3<int>{x, y, z}) != tiles->initial_grounds.end()) { tiles->initial_grounds.erase(Vec3<int>{x, y, z}); } tiles->initial_features[Vec3<int>{x, y, z}] = tiles->initial_features[Vec3<int>{x, y, 0}]; } } } } // Wipe east if (!PRESENT_ROOMS.at(groundCounter).at(3)) { // x = max-1 for (int x = bdata.chunk_x * sdata.chunks_x - 1; x < bdata.chunk_x * sdata.chunks_x; x++) { for (int y = 0; y < bdata.chunk_y * sdata.chunks_y; y++) { for (int z = 2; z < bdata.chunk_z * sdata.chunks_z; z++) { if (tiles->initial_left_walls.find(Vec3<int>{x, y, z}) != tiles->initial_left_walls.end()) { tiles->initial_left_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_right_walls.find(Vec3<int>{x, y, z}) != tiles->initial_right_walls.end()) { tiles->initial_right_walls.erase(Vec3<int>{x, y, z}); } if (tiles->initial_grounds.find(Vec3<int>{x, y, z}) != tiles->initial_grounds.end()) { tiles->initial_grounds.erase(Vec3<int>{x, y, z}); } tiles->initial_features[Vec3<int>{x, y, z}] = tiles->initial_features[Vec3<int>{x, y, 0}]; } } } } } sectors[tilesName] = std::move(tiles); } while (baseMap && ++groundCounter < 16); } return sectors; } void InitialGameStateExtractor::extractBattlescapeMap( GameState &state, const std::vector<OpenApoc::UString> &paths) const { for (unsigned i = 0; i < paths.size(); i++) { if (paths[i].length() > 0) { extractBattlescapeMapFromPath(state, paths[i], i); } } } } // namespace OpenApoc
30.269133
96
0.572837
[ "vector" ]
62ccd5ea1ad0aae5352e11f2ccb70e42a818cc43
672
hpp
C++
model/tests/mock/IoDeviceMock.hpp
benvenutti/core8
6677f509d309ec2d0bdbe360165429d664811177
[ "MIT" ]
2
2017-12-09T02:09:17.000Z
2018-10-20T03:59:40.000Z
model/tests/mock/IoDeviceMock.hpp
benvenutti/core8
6677f509d309ec2d0bdbe360165429d664811177
[ "MIT" ]
45
2016-11-07T23:13:29.000Z
2018-12-26T16:02:58.000Z
model/tests/mock/IoDeviceMock.hpp
benvenutti/core8
6677f509d309ec2d0bdbe360165429d664811177
[ "MIT" ]
null
null
null
#pragma once #include "model/Chip8.hpp" #include "model/IoDevice.hpp" namespace Mock { class IoDeviceMock : public model::IoDevice { public: ~IoDeviceMock() override = default; bool isKeyPressed( model::chip8::key key ) const override { if ( m_pressedKey ) { return key == m_pressedKey.get(); } return false; } boost::optional<model::chip8::key> pressedKey() const override { return m_pressedKey; } void pressedKey( model::chip8::key key ) { m_pressedKey = key; } private: boost::optional<model::chip8::key> m_pressedKey = boost::none; }; } // namespace Mock
17.230769
66
0.607143
[ "model" ]
62d4de48d5526441ddf539e370b3e4090294c6c8
1,130
cpp
C++
2016/Day17/main.cpp
marcuskrahl/AdventOfCode
0148d9a01a565aac1a6104a6001478fab3b6d4f8
[ "MIT" ]
null
null
null
2016/Day17/main.cpp
marcuskrahl/AdventOfCode
0148d9a01a565aac1a6104a6001478fab3b6d4f8
[ "MIT" ]
null
null
null
2016/Day17/main.cpp
marcuskrahl/AdventOfCode
0148d9a01a565aac1a6104a6001478fab3b6d4f8
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "Containers.hpp" #include <vector> void run_part_one() { std::vector<unsigned int> containers; unsigned int container_value; while (std::cin >> container_value) { containers.push_back(container_value); } std::cout << get_number_of_combinations(containers, 150) << std::endl; } void run_part_two() { std::vector<unsigned int> containers; unsigned int container_value; while (std::cin >> container_value) { containers.push_back(container_value); } unsigned int combination_count = 0; int target_depth = 1; do { combination_count = get_number_of_combinations_with_depth(containers,150,target_depth); target_depth++; } while (combination_count == 0); std::cout << combination_count << std::endl; } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day17 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } }
26.27907
95
0.614159
[ "vector" ]
62df28d10e249c3ada6dadb97f92f63500acd012
1,767
cpp
C++
test/main.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2021-12-25T16:37:53.000Z
2021-12-25T16:37:53.000Z
test/main.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2022-03-07T11:46:27.000Z
2022-03-07T11:46:27.000Z
test/main.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
null
null
null
/* * SPDX-License-Identifier: MIT * Copyright (c) 2022 Jai Bellare * See <https://opensource.org/licenses/MIT/> or LICENSE.md * Project homepage: https://github.com/strangeQuark1041/samarium */ // Based on: https://youtu.be/EK32jo7i5LQ #include "samarium/graphics/colors.hpp" #include "samarium/samarium.hpp" static constexpr auto scale = 80.0; using namespace sm; using namespace sm::literals; auto is_prime(i32 n) { for (auto i = 2; i <= n / 2; ++i) { if (n % i == 0) { return false; } } return true; } int main() { auto app = App{{.dims = {1000, 1000}}}; app.transform.scale /= scale; // zoom out const auto count = i32(app.transform.apply_inverse(Vector2{}) .length()); // roughly ensure numbers fill up screen by getting // distance from centre to corner print("Count: ", count); auto numbers = std::vector<i32>(); for (auto i = 1; i32(numbers.size()) < count; i++) { if (is_prime(i)) { numbers.push_back(i); } } const auto draw = [&] { app.fill("#06060c"_c); if (app.mouse.left) { app.transform.pos += app.mouse.pos.now - app.mouse.pos.prev; } // translate const auto factor = 1.0 + 0.1 * app.mouse.scroll_amount; app.transform.scale *= Vector2::combine(factor); app.transform.pos = app.mouse.pos.now + factor * (app.transform.pos - app.mouse.pos.now); for (auto i : numbers) { app.draw(Circle{.centre = Vector2::from_polar({f64(i), f64(i)}), .radius = 4.0 / std::sqrt(app.transform.scale.x)}, colors::aquamarine); } }; app.run(draw); }
27.184615
97
0.55631
[ "vector", "transform" ]
62ef0c96252ad0038a4321d7c8819efa48a089b3
3,788
cpp
C++
tests/test_qp.cpp
vkotaru/nonlinear_controls
fbb32195924d810605cab90ea75308e878532e70
[ "BSD-3-Clause" ]
5
2020-12-22T02:27:27.000Z
2022-02-04T15:46:34.000Z
tests/test_qp.cpp
vkotaru/nonlinear_controls
fbb32195924d810605cab90ea75308e878532e70
[ "BSD-3-Clause" ]
null
null
null
tests/test_qp.cpp
vkotaru/nonlinear_controls
fbb32195924d810605cab90ea75308e878532e70
[ "BSD-3-Clause" ]
4
2021-04-30T12:32:36.000Z
2021-08-18T22:33:18.000Z
#include "common/qpoases_eigen.hpp" #include "controls/clf_qp.h" #include "quadprog/qpswift_eigen.h" #include <chrono> #include <eigen3/Eigen/Dense> #include <iostream> #include <qpOASES.hpp> namespace nlc = nonlinear_controls; #define nlc_real double int main() { USING_NAMESPACE_QPOASES ////////////////////////////////////////////////////////////////// nlc::QPOasesEigen example2(3, 1); example2.data_.H = 2 * Eigen::Matrix<real_t, 3, 3>::Identity(); example2.data_.g = Eigen::Matrix<real_t, 3, 1>::Zero(); example2.data_.A << 1, 3, 4; example2.data_.lbA = -100 * Eigen::Matrix<real_t, 1, 1>::Ones(); example2.data_.ubA = -3 * Eigen::Matrix<real_t, 1, 1>::Ones(); example2.data_.lb = -100 * Eigen::Matrix<real_t, 3, 1>::Ones(); example2.data_.ub = 100 * Eigen::Matrix<real_t, 3, 1>::Ones(); example2.setup(); example2.solve(); std::cout << "nlc::QPOasesEigen" << std::endl; std::cout << example2.getOptimizer().transpose() << std::endl; nlc::QPSwiftEigen ex_swft(3, 8, 0); ex_swft.H = example2.data_.H; ex_swft.f = example2.data_.g; ex_swft.c = 0; ex_swft.A << Eigen::Matrix3d::Identity(), -Eigen::Matrix3d::Identity(), example2.data_.A, -example2.data_.A; ex_swft.b << example2.data_.ub, -example2.data_.lb, example2.data_.ubA, -example2.data_.lbA; std::cout << "Ax<=b\nA:\n" << ex_swft.A << "\nb:\n" << ex_swft.b << "\n"; ex_swft.solve(); ////////////////////////////////////////////////////////////////// printf("...............................\n" "test case 3\n"); printf("QPOases: \n"); /* Setup data of first QP. */ real_t H[2 * 2] = {1.0, 0.0, 0.0, 0.5}; real_t A[1 * 2] = {1.0, 1.0}; real_t g[2] = {1.5, 1.0}; real_t lb[2] = {0.5, -2.0}; real_t ub[2] = {5.0, 2.0}; real_t lbA[1] = {-1.0}; real_t ubA[1] = {2.0}; /* Setting up QProblem object. */ QProblem example(2, 1); Options options; options.printLevel = PL_LOW; example.setOptions(options); /* Solve first QP. */ int_t nWSR = 10; example.init(H, g, A, lb, ub, lbA, ubA, nWSR); /* Get and print solution of first QP. */ real_t xOpt[2]; real_t yOpt[2 + 1]; example.getPrimalSolution(xOpt); example.getDualSolution(yOpt); printf("\nxOpt = [ %e, %e ];\n yOpt = [ %e, %e, %e ]; objVal = %e\n\n", xOpt[0], xOpt[1], yOpt[0], yOpt[1], yOpt[2], example.getObjVal()); nlc::QPOasesEigen ex3a(2, 1); ex3a.data_.H << 1.0, 0.0, 0.0, 0.5; ex3a.data_.g << 1.5, 1.0; ex3a.data_.A << 1, 1; ex3a.data_.lbA << -1.0; ex3a.data_.ubA << 2.0; ex3a.data_.lb << 0.5, -2.0; ex3a.data_.ub << 5.0, 2.0; ex3a.options.setToFast(); ex3a.options.printLevel = qpOASES::PL_LOW; ex3a.setup(); auto start = std::chrono::high_resolution_clock::now(); ex3a.solve(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); std::cout << "Time taken by qpoases: " << duration.count() << " microseconds" << std::endl; std::cout << "nlc::QPOasesEigen: xOpt: "; std::cout << ex3a.getOptimizer().transpose() << std::endl; nlc::QPSwiftEigen ex3s(2, 6, 0); ex3s.H = ex3a.data_.H; ex3s.f = ex3a.data_.g; ex3s.c = 0; ex3s.A << Eigen::Matrix2d::Identity(), -Eigen::Matrix2d::Identity(), ex3a.data_.A, -ex3a.data_.A; ex3s.b << ex3a.data_.ub, -ex3a.data_.lb, ex3a.data_.ubA, -ex3a.data_.lbA; std::cout << "Ax<=b\nA:\n" << ex_swft.A << "\nb:\n" << ex_swft.b << "\n"; start = std::chrono::high_resolution_clock::now(); ex3s.solve(); stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); std::cout << "Time taken by qpswift: " << duration.count() << " microseconds" << std::endl; }
35.401869
79
0.587381
[ "object" ]
62f3600703d2d6101254311e7f196b9d1862aaeb
4,716
cpp
C++
elements/rendering/techniques/lpp_lighting_process.cpp
fromasmtodisasm/elements
31574ee5423b291d58b1169fa84f27938ce9666b
[ "MIT" ]
55
2016-06-13T07:26:22.000Z
2021-06-12T17:42:52.000Z
elements/rendering/techniques/lpp_lighting_process.cpp
fromasmtodisasm/elements
31574ee5423b291d58b1169fa84f27938ce9666b
[ "MIT" ]
22
2016-06-14T01:40:40.000Z
2017-01-03T23:26:20.000Z
elements/rendering/techniques/lpp_lighting_process.cpp
PkXwmpgN/elements
31574ee5423b291d58b1169fa84f27938ce9666b
[ "MIT" ]
7
2016-06-13T18:59:31.000Z
2019-08-14T16:36:55.000Z
/* The MIT License (MIT) Copyright (c) 2016 Alexey Yegorov 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 "lpp_lighting_process.h" #include "rendering/state/state_macro.h" #include "rendering/utils/program_loader.h" #include "utils/std/enum.h" #include "math/transform.h" #include "math/trigonometry.h" namespace eps { namespace rendering { enum class program_enum : short { // attributes a_vertex_pos = 0, // uniforms u_matrix_mvp = 0, u_camera_view_param = 1, u_camera_near = 2, u_camera_far = 3, u_map_geometry = 4, u_map_depth = 5, u_light_pos = 6, u_light_intensity = 7, u_light_inv_range_square = 8, }; enum class program_stencil_enum : short { // attributes a_vertex_pos = 0, // uniforms u_matrix_mvp = 0 }; lpp_lighting_process::lpp_lighting_process() : sphere_(2) {} bool lpp_lighting_process::initialize() { return load_program("assets/shaders/techniques/lpp_lighting.prog", program_) && load_program("assets/shaders/techniques/lpp_lighting_stencil.prog", program_stencil_); } void lpp_lighting_process::process() { if(scene_) scene_->process_lights(*this); } void lpp_lighting_process::stencil(const math::mat4 & mvp) { EPS_STATE_DEPTH_TEST(); EPS_STATE_COLOR_READONLY(); // TODO: stencil settings wrapper glClear(GL_STENCIL_BUFFER_BIT); glStencilFunc(GL_ALWAYS, 0, 0); glStencilOpSeparate(GL_BACK, GL_KEEP, GL_INCR_WRAP, GL_KEEP); glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_DECR_WRAP, GL_KEEP); EPS_STATE_PROGRAM(program_stencil_.get_product()); program_stencil_.uniform_value(utils::to_int(program_stencil_enum::u_matrix_mvp), mvp); sphere_.render(program_stencil_, utils::to_int(program_stencil_enum::a_vertex_pos)); glStencilFunc(GL_NOTEQUAL, 0, 0xFF); } void lpp_lighting_process::visit(const scene::light_point & light) { assert(scene_); auto node = light.get_node().lock(); assert(node); auto camera = scene_->get_camera().lock(); assert(camera); math::mat4 transform = camera->get_projection() * camera->get_view() * node->get_world_matrix() * math::scale(light.get_range(), light.get_range(), light.get_range()); stencil(transform); EPS_STATE_CULLFACE(); EPS_STATE_CULLFACE_MODE(GL_FRONT); EPS_STATE_BLEND(GL_ONE, GL_ONE); EPS_STATE_PROGRAM(program_.get_product()); EPS_STATE_SAMPLER_0(map_geometry_); EPS_STATE_SAMPLER_1(map_depth_); program_.uniform_value(utils::to_int(program_enum::u_map_geometry), 0); program_.uniform_value(utils::to_int(program_enum::u_map_depth), 1); program_.uniform_value(utils::to_int(program_enum::u_matrix_mvp), transform); const float tan_half_fov = math::tan(camera->get_fov() / 2.0f); math::vec2 camera_view_param = math::vec2(tan_half_fov * camera->get_aspect(), tan_half_fov); program_.uniform_value(utils::to_int(program_enum::u_camera_view_param), camera_view_param); program_.uniform_value(utils::to_int(program_enum::u_camera_near), camera->get_near()); program_.uniform_value(utils::to_int(program_enum::u_camera_far), camera->get_far()); const float inv_range_square = 1.0f / (light.get_range() * light.get_range()); math::vec3 light_pos(camera->get_view() * math::vec4(scene::get_position(light.get_node()), 1.0f)); program_.uniform_value(utils::to_int(program_enum::u_light_pos), light_pos); program_.uniform_value(utils::to_int(program_enum::u_light_intensity), light.get_intensity()); program_.uniform_value(utils::to_int(program_enum::u_light_inv_range_square), inv_range_square); sphere_.render(program_, utils::to_int(program_enum::a_vertex_pos)); } } /* rendering */ } /* eps */
34.173913
103
0.745123
[ "render", "transform" ]
62f5b23479c6d9e9763de5acd0cc460912e62d0d
139,534
cpp
C++
digitanks/src/digitanks/ui/hud.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
5
2015-07-03T18:42:32.000Z
2017-08-25T10:28:12.000Z
digitanks/src/digitanks/ui/hud.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
digitanks/src/digitanks/ui/hud.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
#include "hud.h" #include <geometry.h> #include <strutils.h> #include <tinker/cvar.h> #include <glgui/rootpanel.h> #include <tinker/profiler.h> #include <sound/sound.h> #include <renderer/game_renderer.h> #include <renderer/game_renderingcontext.h> #include <game/cameramanager.h> #include "digitankswindow.h" #include "digitanksgame.h" #include <structures/cpu.h> #include <weapons/projectile.h> #include <structures/loader.h> #include <structures/props.h> #include <structures/collector.h> #include <structures/autoturret.h> #include <units/mobilecpu.h> #include <units/scout.h> #include <units/artillery.h> #include <units/mechinf.h> #include <units/maintank.h> #include <dt_camera.h> #include <weapons/cameraguided.h> #include <campaign/userfile.h> #include "weaponpanel.h" #include "scenetree.h" using namespace glgui; #define _T(x) x CVar hud_enable("hud_enable", "on"); CPowerBar::CPowerBar(powerbar_type_t ePowerbarType) : CLabel(0, 0, 100, 100, "", "text") { m_ePowerbarType = ePowerbarType; } void CPowerBar::Think() { if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelection()) return; CSelectable* pSelection = DigitanksGame()->GetPrimarySelection(); char szLabel[100]; if (m_ePowerbarType == POWERBAR_SHIELD) { CDigitank* pTank = dynamic_cast<CDigitank*>(pSelection); if (pTank && pTank->GetShieldMaxStrength() && pTank->TakesDamage()) { sprintf(szLabel, "Shield Strength: %d/%d", (int)(pTank->GetShieldStrength() * pTank->GetShieldMaxStrength()), (int)(pTank->GetShieldMaxStrength() * pTank->GetDefenseScale(true))); SetText(szLabel); } else SetText(""); } else if (m_ePowerbarType == POWERBAR_HEALTH) { if (pSelection->TakesDamage()) { sprintf(szLabel, "Hull Strength: %d/%d", (int)pSelection->GetHealth(), (int)pSelection->GetTotalHealth()); SetText(szLabel); } else SetText(""); } else if (m_ePowerbarType == POWERBAR_ATTACK) { if (strlen(pSelection->GetPowerBar1Text()) && pSelection->GetPlayerOwner() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) { sprintf(szLabel, "%s: %d%%", pSelection->GetPowerBar1Text(), (int)(pSelection->GetPowerBar1Value()*100)); SetText(szLabel); } else SetText(""); } else if (m_ePowerbarType == POWERBAR_DEFENSE) { if (strlen(pSelection->GetPowerBar2Text()) && pSelection->GetPlayerOwner() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) { sprintf(szLabel, "%s: %d%%", pSelection->GetPowerBar2Text(), (int)(pSelection->GetPowerBar2Value()*100)); SetText(szLabel); } else SetText(""); } else { if (strlen(pSelection->GetPowerBar3Text()) && pSelection->GetPlayerOwner() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) { sprintf(szLabel, "%s: %d%%", pSelection->GetPowerBar3Text(), (int)(pSelection->GetPowerBar3Value()*100)); SetText(szLabel); } else SetText(""); } int iSize = 13; if (m_ePowerbarType == POWERBAR_SHIELD) iSize = 10; SetFont("text", iSize); while (iSize > 0 && GetTextWidth() > GetWidth()-1) SetFont("text", --iSize); } void CPowerBar::Paint(float x, float y, float w, float h) { if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelection()) return; CSelectable* pSelection = DigitanksGame()->GetPrimarySelection(); if (m_ePowerbarType == POWERBAR_SHIELD) { CDigitank* pTank = dynamic_cast<CDigitank*>(pSelection); if (pTank && pTank->GetShieldMaxStrength() && pTank->TakesDamage()) { float flShield = pTank->GetShieldStrength() * pTank->GetShieldMaxStrength(); float flShieldMax = pTank->GetShieldMaxStrength() * pTank->GetDefenseScale(true); CRootPanel::PaintRect(x+1, y+1, (int)(w * flShield / flShieldMax)-2, h-2, Color(80, 80, 80)); } } else if (m_ePowerbarType == POWERBAR_HEALTH) { CDigitank* pTank = dynamic_cast<CDigitank*>(pSelection); if (!pTank || pTank->TakesDamage()) CRootPanel::PaintRect(x+1, y+1, (int)(w * pSelection->GetHealth() / pSelection->GetTotalHealth())-2, h-2, Color(0, 150, 0)); } else if (m_ePowerbarType == POWERBAR_ATTACK) { if (pSelection->GetPlayerOwner() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) CRootPanel::PaintRect(x+1, y+1, (int)(w * pSelection->GetPowerBar1Size())-2, h-2, Color(150, 0, 0)); } else if (m_ePowerbarType == POWERBAR_DEFENSE) { if (pSelection->GetPlayerOwner() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) CRootPanel::PaintRect(x+1, y+1, (int)(w * pSelection->GetPowerBar2Size())-2, h-2, Color(0, 0, 150)); } else { if (pSelection->GetPlayerOwner() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) CRootPanel::PaintRect(x+1, y+1, (int)(w * pSelection->GetPowerBar3Size())-2, h-2, Color(100, 100, 0)); } BaseClass::Paint(x, y, w, h); } CHUD::CHUD() : CHUDViewport(), m_HUDSheet("textures/hud/hud-sheet.txt"), m_UnitsSheet("textures/hud/units-sheet.txt"), m_WeaponsSheet("textures/hud/hud-weapons-01.txt"), m_ButtonSheet("textures/hud/hud-menu-sheet-01.txt"), m_DownloadSheet("textures/hud/hud-download-sheet-01.txt"), m_KeysSheet("textures/hud/keys.txt"), m_ActionSignsSheet("textures/hud/actionsigns/signs.txt"), m_PowerupsSheet("textures/hud/powerups-sheet.txt") { m_bNeedsUpdate = false; m_pShieldBar = AddControl(new CPowerBar(POWERBAR_SHIELD)); m_pHealthBar = AddControl(new CPowerBar(POWERBAR_HEALTH)); m_pAttackPower = AddControl(new CPowerBar(POWERBAR_ATTACK)); m_pDefensePower = AddControl(new CPowerBar(POWERBAR_DEFENSE)); m_pMovementPower = AddControl(new CPowerBar(POWERBAR_MOVEMENT)); m_hActionTanksSheet = CMaterialLibrary::AddMaterial(_T("textures/hud/actionsigns/tanks.mat")); m_hPurchasePanel = CMaterialLibrary::AddMaterial(_T("textures/purchasepanel.mat")); m_hShieldTexture = CMaterialLibrary::AddMaterial(_T("textures/hud/hud-shield.mat")); m_hSelectorMedalTexture = CMaterialLibrary::AddMaterial(_T("textures/hud/selector-medal.mat")); m_eActionSign = ACTIONSIGN_NONE; m_pActionItem = AddControl(new CLabel(0, 0, 10, 10, _T(""))); m_pActionItem->SetFont(_T("text")); m_pCloseActionItems = AddControl(new CButton(0, 0, 100, 50, _T("Close"))); m_pCloseActionItems->SetFont(_T("header")); m_flActionItemsLerp = m_flActionItemsLerpGoal = 0; m_flActionItemsWidth = 280; m_flSmallActionItemLerp = m_flSmallActionItemLerpGoal = 0; m_iCurrentSmallActionItem = ~0; m_pButtonPanel = AddControl(new CMouseCapturePanel()); for (size_t i = 0; i < NUM_BUTTONS; i++) { m_apButtons[i] = m_pButtonPanel->AddControl(new CPictureButton(_T(""))); m_apButtons[i]->SetCursorOutListener(this, ButtonCursorOut); } m_apButtons[0]->SetCursorInListener(this, ButtonCursorIn0); m_apButtons[1]->SetCursorInListener(this, ButtonCursorIn1); m_apButtons[2]->SetCursorInListener(this, ButtonCursorIn2); m_apButtons[3]->SetCursorInListener(this, ButtonCursorIn3); m_apButtons[4]->SetCursorInListener(this, ButtonCursorIn4); m_apButtons[5]->SetCursorInListener(this, ButtonCursorIn5); m_apButtons[6]->SetCursorInListener(this, ButtonCursorIn6); m_apButtons[7]->SetCursorInListener(this, ButtonCursorIn7); m_apButtons[8]->SetCursorInListener(this, ButtonCursorIn8); m_apButtons[9]->SetCursorInListener(this, ButtonCursorIn9); m_pAttackInfo = AddControl(new CLabel(0, 0, 100, 150, _T(""))); m_pAttackInfo->SetWrap(false); m_pAttackInfo->SetAlign(glgui::CLabel::TA_TOPLEFT); m_pAttackInfo->SetFont(_T("text")); m_pScoreboard = AddControl(new CLabel(0, 0, 100, 150, _T(""))); m_pScoreboard->SetWrap(false); m_pScoreboard->SetAlign(glgui::CLabel::TA_TOPLEFT); m_pScoreboard->SetFont(_T("text"), 10); m_pTankInfo = AddControl(new CLabel(0, 0, 100, 100, _T(""))); m_pTankInfo->SetFont(_T("text"), 10); m_pTurnInfo = AddControl(new CLabel(0, 0, 100, 100, _T(""))); m_pTurnInfo->SetFont(_T("text"), 10); m_pResearchInfo = AddControl(new CLabel(0, 0, 100, 100, _T(""))); m_pResearchInfo->SetFont(_T("text")); m_pButtonInfo = AddControl(new CLabel(0, 0, 100, 100, _T(""))); m_pButtonInfo->SetFont(_T("text")); m_pPressEnter = AddControl(new CLabel(0, 0, 100, 100, _T(""))); m_pPressEnter->SetFont(_T("text")); SetupMenu(MENUMODE_MAIN); m_pDemoNotice = AddControl(new CLabel(0, 0, 100, 20, _T(""))); m_pDemoNotice->SetFont(_T("text")); m_pDemoNotice->SetAlign(CLabel::TA_TOPLEFT); m_pDemoNotice->SetPos(20, 20); m_pDemoNotice->SetText(""); m_pPowerInfo = AddControl(new CLabel(0, 0, 200, 20, _T(""))); m_pPowerInfo->SetAlign(CLabel::TA_TOPCENTER); m_pPowerInfo->SetPos(200, 20); m_pPowerInfo->SetTextColor(Color(220, 220, 255)); m_pPowerInfo->SetFont(_T("text")); m_pPowerInfo->SetCursorInListener(this, ShowPowerInfo); m_pPowerInfo->SetCursorOutListener(this, HideTeamInfo); m_pFleetInfo = AddControl(new CLabel(0, 0, 200, 20, _T(""))); m_pFleetInfo->SetAlign(CLabel::TA_TOPCENTER); m_pFleetInfo->SetPos(200, 20); m_pFleetInfo->SetTextColor(Color(220, 220, 255)); m_pFleetInfo->SetFont(_T("text")); m_pFleetInfo->SetCursorInListener(this, ShowFleetInfo); m_pFleetInfo->SetCursorOutListener(this, HideTeamInfo); m_pBandwidthInfo = AddControl(new CLabel(0, 0, 200, 20, _T(""))); m_pBandwidthInfo->SetAlign(CLabel::TA_TOPCENTER); m_pBandwidthInfo->SetPos(200, 20); m_pBandwidthInfo->SetTextColor(Color(220, 220, 255)); m_pBandwidthInfo->SetFont(_T("text")); m_pBandwidthInfo->SetCursorInListener(this, ShowBandwidthInfo); m_pBandwidthInfo->SetCursorOutListener(this, HideTeamInfo); m_pTeamInfo = AddControl(new CLabel(0, 0, 200, 20, _T(""))); m_pTeamInfo->SetAlign(CLabel::TA_TOPLEFT); m_pTeamInfo->SetPos(200, 20); m_pTeamInfo->SetTextColor(Color(255, 255, 255)); m_pTeamInfo->SetFont(_T("text")); m_pUpdatesButton = AddControl(new CPictureButton(_T("Download Grid"))); m_pUpdatesButton->SetClickedListener(this, OpenUpdates); m_pUpdatesButton->ShowBackground(false); m_pUpdatesButton->SetTooltip(_T("Download Grid")); m_pUpdatesPanel = AddControl(new CUpdatesPanel()); m_pUpdatesPanel->SetVisible(false); m_flUpdateIconSlide = 0; m_pWeaponPanel = AddControl(new CWeaponPanel()); m_pWeaponPanel->SetVisible(false); m_pSceneTree = AddControl(new CSceneTree()); m_pTurnButton = AddControl(new CPictureButton(_T("TURN"))); SetButtonSheetTexture(m_pTurnButton, &m_HUDSheet, "EndTurn"); m_pTurnButton->SetClickedListener(this, EndTurn); m_pTurnButton->ShowBackground(false); m_pTurnButton->SetBorder(BT_NONE); m_pTurnButton->SetCursorInListener(this, CursorInTurnButton); m_pTurnButton->SetCursorOutListener(this, CursorOutTurnButton); m_pTurnWarning = AddControl(new CLabel(0, 0, 100, 100, _T(""))); m_pTurnWarning->SetAlign(CLabel::TA_TOPLEFT); m_pTurnWarning->SetTextColor(Color(255, 255, 255)); m_pTurnWarning->SetFont(_T("text")); m_flTurnWarningGoal = 0; m_flTurnWarningLerp = 0; m_flAttackInfoAlpha = m_flAttackInfoAlphaGoal = 0; m_flTurnInfoLerp = m_flTurnInfoLerpGoal = 0; m_flTurnInfoHeight = m_flTurnInfoHeightGoal = 0; m_flSelectorMedalStart = 0; m_flFileRescueStart = 0; m_iTurnSound = CSoundLibrary::Get()->AddSound(_T("sound/turn.wav")); m_pSpacebarHint = AddControl(new CLabel(0, 0, 200, 20, _T(""))); m_pSpacebarHint->SetAlign(CLabel::TA_MIDDLECENTER); m_pSpacebarHint->SetFont(_T("text")); m_pHowToPlayPanel = AddControl(new CHowToPlayPanel()); #ifdef DT_COMPETITION m_iCompetitionWatermark = CTextureLibrary::AddTextureID(_T("textures/competition.png")); #endif } void CHUD::Layout() { if (!DigitanksGame()) return; BaseClass::Layout(); int iWidth = RootPanel()->GetWidth(); int iHeight = RootPanel()->GetHeight(); m_pAttackInfo->SetPos(iWidth - 165, iHeight - 150 - 90 - 10); m_pAttackInfo->SetSize(165, 90); m_pShieldBar->SetPos(iWidth/2 - 720/2 + 170, iHeight - 142); m_pShieldBar->SetSize(200, 15); m_pHealthBar->SetPos(iWidth/2 - 720/2 + 170, iHeight - 124); m_pHealthBar->SetSize(200, 20); m_pAttackPower->SetPos(iWidth/2 - 720/2 + 170, iHeight - 90); m_pAttackPower->SetSize(200, 20); m_pDefensePower->SetPos(iWidth/2 - 720/2 + 170, iHeight - 60); m_pDefensePower->SetSize(200, 20); m_pMovementPower->SetPos(iWidth/2 - 720/2 + 170, iHeight - 30); m_pMovementPower->SetSize(200, 20); bool bShowCPUStuff = false; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetPrimaryCPU()) bShowCPUStuff = true; m_pActionItem->SetPos(iWidth - 280, 70); m_pActionItem->SetSize(220, 250); m_pActionItem->SetAlign(CLabel::TA_TOPLEFT); m_pCloseActionItems->SetSize(130, 25); m_pCloseActionItems->SetPos(iWidth - 225, 398); m_pCloseActionItems->SetClickedListener(this, CloseActionItems); m_pActionItem->SetVisible(bShowCPUStuff); m_pCloseActionItems->SetVisible(bShowCPUStuff); for (size_t i = 0; i < m_apActionItemButtons.size(); i++) RemoveControl(m_apActionItemButtons[i]); m_apActionItemButtons.clear(); CDigitanksPlayer* pLocalCurrentTeam = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); if (pLocalCurrentTeam && bShowCPUStuff) { size_t iItemButtonSize = 30; for (size_t i = 0; i < pLocalCurrentTeam->GetNumActionItems(); i++) { CControl<CPictureButton> pButton = AddControl(new CPictureButton(tsprintf(tstring("%d"), i))); pButton->SetSize(iItemButtonSize, iItemButtonSize); pButton->SetPos(iWidth - iItemButtonSize - 10, 120 + (iItemButtonSize+10)*i); pButton->SetClickedListener(this, ChooseActionItem); pButton->SetCursorInListener(this, ShowSmallActionItem); pButton->SetCursorOutListener(this, HideSmallActionItem); CEntityHandle<CDigitanksEntity> hUnit(pLocalCurrentTeam->GetActionItem(i)->iUnit); switch (pLocalCurrentTeam->GetActionItem(i)->eActionType) { case ACTIONTYPE_WELCOME: // Use the fleet logo, which is also the digitanks logo, for the welcome icon. SetButtonSheetTexture(pButton, &m_HUDSheet, "FleetPointsIcon"); pButton->SetTooltip(_T("Intro")); break; case ACTIONTYPE_CONTROLS: // Use the fleet logo, which is also the digitanks logo, for the welcome icon. SetButtonSheetTexture(pButton, &m_HUDSheet, "FleetPointsIcon"); pButton->SetTooltip(_T("Controls")); break; case ACTIONTYPE_NEWSTRUCTURE: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Structure Complete")); } break; case ACTIONTYPE_AUTOMOVECANCELED: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Move Canceled")); } break; case ACTIONTYPE_AUTOMOVEENEMY: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Enemy Sighted")); } break; case ACTIONTYPE_UNITDAMAGED: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Unit Damaged")); } break; case ACTIONTYPE_FORTIFIEDENEMY: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Enemy Sighted")); } break; case ACTIONTYPE_UNITAUTOMOVE: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Move Completed")); } break; case ACTIONTYPE_UNITORDERS: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Orders Needed")); } break; case ACTIONTYPE_UPGRADE: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Upgrade Compeleted")); } break; case ACTIONTYPE_UNITREADY: if (hUnit != NULL) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(hUnit->GetUnitType(), hSheet, sx, sy, sw, sh, tw, th); pButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); pButton->SetTooltip(_T("Unit Ready")); } break; case ACTIONTYPE_DOWNLOADUPDATES: SetButtonSheetTexture(pButton, &m_HUDSheet, "BandwidthIcon"); pButton->SetTooltip(_T("Download Grid")); break; case ACTIONTYPE_DOWNLOADCOMPLETE: SetButtonSheetTexture(pButton, &m_HUDSheet, "BandwidthIcon"); pButton->SetTooltip(_T("Download Complete")); break; } m_apActionItemButtons.push_back(pButton); } } m_pButtonPanel->SetPos(iWidth/2 - 720/2 + 380, iHeight - 140); m_pButtonPanel->SetRight(m_pButtonPanel->GetLeft() + 330); m_pButtonPanel->SetBottom(iHeight - 10); m_pHowToPlayPanel->Layout(); for (size_t i = 0; i < NUM_BUTTONS; i++) { m_apButtons[i]->SetSize(50, 50); m_apButtons[i]->SetPos(20 + 60*(i%5), 10 + 60*(i/5)); } m_pTankInfo->SetSize(140, 240); m_pTankInfo->SetPos(10, iHeight - m_pTankInfo->GetHeight() + 10 + 7); m_pTankInfo->SetAlign(glgui::CLabel::TA_TOPLEFT); m_pTankInfo->SetWrap(true); m_pTurnInfo->SetSize(248, 150); m_pTurnInfo->SetPos(iWidth/2 - m_pTurnInfo->GetWidth()/2, 36); m_pTurnInfo->SetAlign(glgui::CLabel::TA_TOPLEFT); m_pTurnInfo->SetWrap(true); if (pLocalCurrentTeam) m_pTurnInfo->SetText(pLocalCurrentTeam->GetTurnInfo()); else m_pTurnInfo->SetText(_T("")); m_pResearchInfo->SetSize(640, 25); m_pResearchInfo->SetPos(iWidth/2 - m_pResearchInfo->GetWidth()/2, 0); m_pResearchInfo->SetAlign(glgui::CLabel::TA_MIDDLECENTER); m_pResearchInfo->SetWrap(false); if (pLocalCurrentTeam) { CUpdateItem* pItem = pLocalCurrentTeam->GetUpdateDownloading(); if (pItem) { if (pLocalCurrentTeam->GetBandwidth() == 0) m_pResearchInfo->SetText(pItem->GetName()); else { tstring s; s = tsprintf((pItem->GetName() + _T(" (%d)")).c_str(), pLocalCurrentTeam->GetTurnsToDownload()); m_pResearchInfo->SetText(s); } } else m_pResearchInfo->SetText(""); } m_pButtonInfo->SetSize(250, 250); m_pButtonInfo->SetPos(iWidth/2, iHeight - 400); m_pButtonInfo->SetAlign(glgui::CLabel::TA_TOPLEFT); m_pButtonInfo->SetWrap(true); m_pUpdatesButton->SetSize(35, 35); m_pUpdatesButton->SetPos(iWidth/2 - 617/2 - 35, 0); m_pUpdatesButton->SetAlign(glgui::CLabel::TA_MIDDLECENTER); m_pUpdatesButton->SetWrap(false); m_pUpdatesButton->SetVisible(bShowCPUStuff); m_pUpdatesPanel->Layout(); m_pWeaponPanel->Layout(); m_pSceneTree->Layout(); m_pPressEnter->SetDimensions(iWidth/2 - 100/2, iHeight*2/3, 100, 50); m_pPressEnter->SetAlign(glgui::CLabel::TA_MIDDLECENTER); m_pPressEnter->SetWrap(false); m_pTurnWarning->SetPos(iWidth - 165, iHeight - 150 - 90 - 10); m_pTurnWarning->SetSize(165, 90); m_pPowerInfo->SetAlign(CLabel::TA_LEFTCENTER); m_pPowerInfo->SetPos(iWidth - 160, 12); m_pPowerInfo->SetSize(80, 15); m_pPowerInfo->SetWrap(false); m_pPowerInfo->SetVisible(bShowCPUStuff); m_pFleetInfo->SetAlign(CLabel::TA_LEFTCENTER); m_pFleetInfo->SetPos(iWidth - 160, 42); m_pFleetInfo->SetSize(30, 15); m_pFleetInfo->SetWrap(false); m_pFleetInfo->SetVisible(bShowCPUStuff); m_pBandwidthInfo->SetAlign(CLabel::TA_LEFTCENTER); m_pBandwidthInfo->SetPos(iWidth - 160, 72); m_pBandwidthInfo->SetSize(150, 15); m_pBandwidthInfo->SetWrap(false); m_pBandwidthInfo->SetVisible(bShowCPUStuff); m_pTurnButton->SetPos(iWidth - 140, iHeight - 105); m_pTurnButton->SetSize(140, 105); if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; m_pUpdatesPanel->GetTextureForUpdateItem(DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetUpdateDownloading(), hSheet, sx, sy, sw, sh, tw, th); m_pUpdatesButton->SetSheetTexture(hSheet, sx, sy, sw, sh, tw, th); } if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY) { // Don't clear it in the start, we want dead tanks to remain in the list so we can mark them asploded. m_ahScoreboardTanks.resize(DigitanksGame()->GetNumPlayers()); for (size_t i = 0; i < DigitanksGame()->GetNumPlayers(); i++) { const CDigitanksPlayer* pTeam = DigitanksGame()->GetDigitanksPlayer(i); tmap<size_t, CEntityHandle<CDigitank> >& ahTeamTanks = m_ahScoreboardTanks[i]; for (size_t j = 0; j < pTeam->GetNumTanks(); j++) { const CDigitank* pTank = pTeam->GetTank(j); ahTeamTanks[pTank->GetHandle()] = pTank; } } } UpdateTurnButton(); UpdateScoreboard(); UpdateTeamInfo(); UpdateInfo(); SetupMenu(); } void CHUD::Think() { if (GameServer()->IsLoading()) return; if (!DigitanksGame()) return; if (!IsVisible()) return; BaseClass::Think(); CDigitank* pCurrentTank = DigitanksGame()->GetPrimarySelectionTank(); Vector vecTerrainPoint, vecEntityPoint; bool bMouseOnGrid = false; CBaseEntity* pHit = NULL; #ifndef T_PLATFORM_TOUCH if (DigitanksGame()->GetControlMode() == MODE_NONE) { if (!CVar::GetCVarBool("m_emulate_touch")) bMouseOnGrid = DigitanksWindow()->GetMouseGridPosition(vecEntityPoint, &pHit); bool bSpotVisible = false; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()) bSpotVisible = DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetVisibilityAtPoint(vecEntityPoint) > 0.2f; if (pHit && dynamic_cast<CSelectable*>(pHit) && bSpotVisible && !DigitanksGame()->IsFeatureDisabled(DISABLE_SELECT)) DigitanksWindow()->SetMouseCursor(MOUSECURSOR_SELECT); if (bSpotVisible) { CDigitanksEntity* pDTHit = dynamic_cast<CDigitanksEntity*>(pHit); if (pDTHit) SetTooltip(pDTHit->GetEntityName()); else { if (DigitanksGame()->GetTerrain()->IsPointInTrees(vecEntityPoint)) SetTooltip(_T("Trees")); else if (DigitanksGame()->GetTerrain()->IsPointOverWater(vecEntityPoint)) SetTooltip(_T("Interference")); else if (DigitanksGame()->GetTerrain()->IsPointOverLava(vecEntityPoint)) SetTooltip(_T("Lava")); else SetTooltip(_T("")); } } else SetTooltip(_T("")); } else if (!CVar::GetCVarBool("m_emulate_touch")) { bMouseOnGrid = DigitanksWindow()->GetMouseGridPosition(vecEntityPoint, &pHit); bMouseOnGrid = DigitanksWindow()->GetMouseGridPosition(vecTerrainPoint, NULL, true); SetTooltip(_T("")); } #endif if (pCurrentTank) { if (DigitanksGame()->GetControlMode() == MODE_MOVE) { float flMoveDistance = pCurrentTank->GetRemainingMovementDistance(); if ((vecTerrainPoint - pCurrentTank->GetGlobalOrigin()).LengthSqr() > flMoveDistance*flMoveDistance) DigitanksWindow()->SetMouseCursor(MOUSECURSOR_MOVEAUTO); else DigitanksWindow()->SetMouseCursor(MOUSECURSOR_MOVE); } else if (DigitanksGame()->GetControlMode() == MODE_AIM) { CDigitanksEntity* pDTHit = dynamic_cast<CDigitanksEntity*>(pHit); CStaticProp* pSPHit = dynamic_cast<CStaticProp*>(pHit); if (pDTHit && pDTHit->TakesDamage() && pDTHit->GetPlayerOwner() != pCurrentTank->GetPlayerOwner() && pDTHit->GetVisibility() > 0.5f && !pSPHit) { if (pDTHit->GetUnitType() == UNIT_SCOUT && pCurrentTank->GetCurrentWeapon() != WEAPON_INFANTRYLASER) DigitanksWindow()->SetMouseCursor(MOUSECURSOR_AIM); else if (pCurrentTank->IsInsideMaxRange(pDTHit->GetGlobalOrigin())) DigitanksWindow()->SetMouseCursor(MOUSECURSOR_AIMENEMY); else DigitanksWindow()->SetMouseCursor(MOUSECURSOR_AIM); } else DigitanksWindow()->SetMouseCursor(MOUSECURSOR_AIM); } else if (DigitanksGame()->GetControlMode() == MODE_TURN) { DigitanksWindow()->SetMouseCursor(MOUSECURSOR_ROTATE); } } if (m_pUpdatesPanel->IsVisible()) { DigitanksWindow()->SetMouseCursor(MOUSECURSOR_NONE); } bool bShowCPUStuff = false; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetPrimaryCPU()) bShowCPUStuff = true; if (!bShowCPUStuff) m_flActionItemsLerp = m_flActionItemsLerpGoal = 0; m_flActionItemsLerp = Approach(m_flActionItemsLerpGoal, m_flActionItemsLerp, GameServer()->GetFrameTime()); m_flSmallActionItemLerp = Approach(m_flSmallActionItemLerpGoal, m_flSmallActionItemLerp, GameServer()->GetFrameTime() * 4); int iWidth = RootPanel()->GetWidth(); m_pActionItem->SetPos(iWidth - 300 + (int)(Bias(1-m_flActionItemsLerp, 0.2f) * m_flActionItemsWidth), 130); m_pActionItem->SetAlpha((int)(m_flActionItemsLerp*255)); m_pCloseActionItems->SetPos(iWidth - 255 + (int)(Bias(1-m_flActionItemsLerp, 0.2f) * m_flActionItemsWidth), m_pCloseActionItems->GetTop()); if (m_bHUDActive && bMouseOnGrid && pCurrentTank) { if (DigitanksGame()->GetControlMode() == MODE_MOVE || DigitanksGame()->GetControlMode() == MODE_TURN || DigitanksGame()->GetControlMode() == MODE_AIM) UpdateInfo(); if (DigitanksGame()->GetControlMode() == MODE_MOVE) { Vector vecMove = vecTerrainPoint; vecMove.z = pCurrentTank->FindHoverHeight(vecMove); pCurrentTank->SetPreviewMove(vecMove); } if (DigitanksGame()->GetControlMode() == MODE_TURN) { if ((vecTerrainPoint - pCurrentTank->GetGlobalOrigin()).LengthSqr() > 4*4) { Vector vecTurn = vecTerrainPoint - pCurrentTank->GetGlobalOrigin(); vecTurn.Normalize(); float flTurn = atan2(vecTurn.y, vecTurn.x) * 180/M_PI; pCurrentTank->SetPreviewTurn(flTurn); } else pCurrentTank->SetPreviewTurn(pCurrentTank->GetGlobalAngles().y); } if (DigitanksGame()->GetControlMode() == MODE_AIM) { Vector vecPreviewAim; CDigitanksEntity* pDTHit = dynamic_cast<CDigitanksEntity*>(pHit); CStaticProp* pSPHit = dynamic_cast<CStaticProp*>(pHit); CDigitank* pDigitankHit = dynamic_cast<CDigitank*>(pHit); if (pDTHit && pDTHit->GetVisibility() <= 0.1f) vecPreviewAim = vecTerrainPoint; else if (pDigitankHit && pDigitankHit->IsScout()) { // Scouts are hard to hit by projectiles because they float so far above the surface. if (pCurrentTank->GetCurrentWeapon() == WEAPON_INFANTRYLASER) vecPreviewAim = DigitanksGame()->GetTerrain()->GetPointHeight(pDigitankHit->GetGlobalOrigin()); else vecPreviewAim = vecTerrainPoint; } else if (pDTHit && !pSPHit && pDTHit->GetVisibility() > 0) vecPreviewAim = pDTHit->GetGlobalOrigin(); else vecPreviewAim = vecEntityPoint; for (size_t i = 0; i < DigitanksGame()->GetCurrentPlayer()->GetNumTanks(); i++) { CDigitank* pTank = DigitanksGame()->GetCurrentPlayer()->GetTank(i); if (!pTank) continue; if (DigitanksGame()->GetCurrentPlayer()->IsSelected(pTank)) { if (pTank->GetCurrentWeapon() == WEAPON_CHARGERAM) pTank->SetPreviewCharge(pHit); else if (pTank->GetCurrentWeapon() == PROJECTILE_AIRSTRIKE) pTank->SetPreviewAim(vecTerrainPoint); else pTank->SetPreviewAim(vecPreviewAim); } } } } if (m_bHUDActive && bMouseOnGrid && DigitanksGame()->GetCurrentLocalDigitanksPlayer()) { if (DigitanksGame()->GetControlMode() == MODE_BUILD) { if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetPrimaryCPU()) DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetPrimaryCPU()->SetPreviewBuild(vecEntityPoint); } } if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() && m_apActionItemButtons.size()) { for (size_t i = 0; i < DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems(); i++) { if (i >= m_apActionItemButtons.size()) break; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(i)->bHandled) m_apActionItemButtons[i]->SetAlpha(50); else m_apActionItemButtons[i]->SetAlpha((int)RemapVal(Oscillate(GameServer()->GetGameTime(), 1), 0, 1, 100, 255)); } } if (m_eMenuMode == MENUMODE_MAIN && m_bHUDActive) { CLesson* pLesson = NULL; if (DigitanksWindow()->GetInstructor() && DigitanksWindow()->GetInstructor()->GetCurrentLesson()) pLesson = DigitanksWindow()->GetInstructor()->GetCurrentLesson(); tstring sLessonName; if (DigitanksWindow()->GetInstructor() && DigitanksWindow()->GetInstructor()->GetCurrentLesson()) sLessonName = DigitanksWindow()->GetInstructor()->GetCurrentLesson()->m_sLessonName; if (pLesson && !!pLesson->m_hPointAt.Downcast<CPictureButton>() && DigitanksWindow()->GetInstructor() && DigitanksWindow()->GetInstructor()->GetCurrentPanel() && DigitanksWindow()->GetInstructor()->GetCurrentPanel()->IsVisible()) { float flRamp = Oscillate(GameServer()->GetGameTime(), 1); int iColor = (int)RemapVal(flRamp, 0, 1, 0, 150); pLesson->m_hPointAt.DowncastStatic<CPictureButton>()->SetButtonColor(Color(iColor, 0, 0)); } else if (pCurrentTank && pCurrentTank->GetDigitanksPlayer() == DigitanksGame()->GetCurrentLocalDigitanksPlayer() && sLessonName == "artillery-aim") { float flRamp = Oscillate(GameServer()->GetGameTime(), 1); int iColor = (int)RemapVal(flRamp, 0, 1, 0, 150); m_apButtons[7]->SetButtonColor(Color(iColor, 0, 0)); } else if (pCurrentTank && pCurrentTank->GetDigitanksPlayer() == DigitanksGame()->GetCurrentLocalDigitanksPlayer() && sLessonName == "strategy-deploy" && dynamic_cast<CMobileCPU*>(pCurrentTank)) { float flRamp = Oscillate(GameServer()->GetGameTime(), 1); m_apButtons[8]->SetButtonColor(Color(0, 0, (int)RemapVal(flRamp, 0, 1, 0, 250))); } // Don't blink other buttons if we're trying to blink this one. else { if (pCurrentTank && pCurrentTank->GetDigitanksPlayer() == DigitanksGame()->GetCurrentLocalDigitanksPlayer() && pCurrentTank->HasBonusPoints()) { float flRamp = Oscillate(GameServer()->GetGameTime(), 1); m_apButtons[4]->SetButtonColor(Color((int)RemapVal(flRamp, 0, 1, 0, 250), (int)RemapVal(flRamp, 0, 1, 0, 200), 0)); } if (pCurrentTank && pCurrentTank->GetDigitanksPlayer() == DigitanksGame()->GetCurrentLocalDigitanksPlayer() && pCurrentTank->HasSpecialWeapons()) { float flRamp = Oscillate(GameServer()->GetGameTime(), 1); m_apButtons[9]->SetButtonColor(Color((int)RemapVal(flRamp, 0, 1, 0, 250), (int)RemapVal(flRamp, 0, 1, 0, 200), 0)); } } } if (m_pAttackInfo->GetText().length() && DigitanksGame()->GetControlMode() == MODE_AIM) { m_flAttackInfoAlphaGoal = 1.0f; m_pAttackInfo->SetVisible(true); } else { m_flAttackInfoAlphaGoal = 0.0f; m_pAttackInfo->SetVisible(false); } m_flAttackInfoAlpha = Approach(m_flAttackInfoAlphaGoal, m_flAttackInfoAlpha, GameServer()->GetFrameTime()); m_flTurnWarningLerp = Approach(m_flTurnWarningGoal, m_flTurnWarningLerp, GameServer()->GetFrameTime()*5); m_flTurnInfoHeightGoal = m_pTurnInfo->GetTextHeight(); m_flTurnInfoLerp = Approach(m_flTurnInfoLerpGoal, m_flTurnInfoLerp, GameServer()->GetFrameTime()); m_flTurnInfoHeight = Approach(m_flTurnInfoHeightGoal, m_flTurnInfoHeight, GameServer()->GetFrameTime()*100); float flTurnInfoHeight = m_flTurnInfoHeight+10; m_pTurnInfo->SetSize(m_pTurnInfo->GetWidth(), (int)flTurnInfoHeight); m_pTurnInfo->SetPos(m_pTurnInfo->GetLeft(), 36 + 10 - (int)(Bias(1.0f-m_flTurnInfoLerp, 0.2f)*flTurnInfoHeight)); m_pUpdatesButton->SetVisible(bShowCPUStuff && !!DigitanksGame()->GetUpdateGrid()); if (DigitanksWindow()->GetInstructor()->GetActive()) m_bUpdatesBlinking = false; if (m_bUpdatesBlinking) m_pUpdatesButton->SetAlpha((int)(RemapVal(Oscillate(GameServer()->GetGameTime(), 1), 0, 1, 0.5f, 1)*255)); else m_pUpdatesButton->SetAlpha(255); m_pScoreboard->SetVisible(DigitanksGame()->ShouldShowScores()); if (m_bNeedsUpdate) { glgui::CRootPanel::Get()->Layout(); m_bNeedsUpdate = false; } CControlHandle pMouseControl = glgui::CRootPanel::Get()->GetHasCursor(); if (DigitanksGame()->GetOverheadCamera()->HasCameraGuidedMissile()) { DigitanksWindow()->SetMouseCursor(MOUSECURSOR_NONE); SetTooltip(_T("")); } else if (pMouseControl) { if (pMouseControl.Downcast<CHUD>()) { // Nothing. } else if (pMouseControl->GetTooltip().length() > 0) { DigitanksWindow()->SetMouseCursor(MOUSECURSOR_NONE); SetTooltip(_T("")); } else if (pMouseControl.Downcast<CButton>()) { DigitanksWindow()->SetMouseCursor(MOUSECURSOR_NONE); SetTooltip(_T("")); } } if (m_bBlinkTurnButton) m_pTurnButton->SetAlpha(Bias(Oscillate(GameServer()->GetGameTime(), 1.0f), 0.8f)); else m_pTurnButton->SetAlpha(1.0f); SetVisible(hud_enable.GetBool() || DigitanksGame()->GetOverheadCamera()->HasCameraGuidedMissile()); } #ifdef _DEBUG #define SHOW_FPS "1" #else #define SHOW_FPS "0" #endif CVar show_fps("show_fps", SHOW_FPS); void CHUD::Paint(float x, float y, float w, float h) { TPROF("CHUD::Paint()"); if (!DigitanksGame()) return; if (GameServer()->IsLoading()) return; if (DigitanksGame()->GetGameType() == GAMETYPE_MENU) return; #ifdef DT_COMPETITION if (true) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); CRootPanel::PaintTexture(m_iCompetitionWatermark, 70, 20, 128/2, 128/2); } #endif if (show_fps.GetBool()) { float flFontHeight = glgui::RootPanel()->GetFontHeight(_T("text"), 10); tstring sFPS = tsprintf(tstring("Time: %.2f"), GameServer()->GetGameTime()); glgui::CLabel::PaintText(sFPS, sFPS.length(), _T("text"), 10, 125, flFontHeight + 50); sFPS = tsprintf(tstring("FPS: %d"), (int)(1 / GameServer()->GetFrameTime())); glgui::CLabel::PaintText(sFPS, sFPS.length(), _T("text"), 10, 125, flFontHeight*2 + 50); #ifndef T_PLATFORM_TOUCH Vector vecTerrainPoint; if (DigitanksWindow()->GetMouseGridPosition(vecTerrainPoint, NULL, true)) { sFPS = tsprintf(tstring("%.2f, %.2f"), vecTerrainPoint.x, vecTerrainPoint.y); glgui::CLabel::PaintText(sFPS, sFPS.length(), _T("text"), 10, 125, flFontHeight*3 + 50); } #endif } if (DigitanksGame()->GetOverheadCamera()->HasCameraGuidedMissile()) { PaintCameraGuidedMissile(x, y, w, h); return; } int iWidth = RootPanel()->GetWidth(); int iHeight = RootPanel()->GetHeight(); CDigitanksPlayer* pCurrentLocalPlayer = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); int iMouseX = 0, iMouseY = 0; if (pCurrentLocalPlayer) { iMouseX = pCurrentLocalPlayer->GetMouseCurrentX(); iMouseY = pCurrentLocalPlayer->GetMouseCurrentY(); } if ((DigitanksGame()->GetGameType() == GAMETYPE_STANDARD || DigitanksGame()->GetGameType() == GAMETYPE_CAMPAIGN) && pCurrentLocalPlayer && pCurrentLocalPlayer->GetPrimaryCPU()) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); PaintHUDSheet("TeamInfoBackground", iWidth - 208, 0, 208, 341); } for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); CDigitanksEntity* pDTEntity = dynamic_cast<CDigitanksEntity*>(pEntity); if (!pDTEntity) continue; Vector vecOrigin = pEntity->GetGlobalOrigin(); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(vecOrigin); float flRadius = pDTEntity->GetBoundingRadius(); Vector vecUp; Vector vecForward; GameServer()->GetRenderer()->GetCameraVectors(&vecForward, NULL, &vecUp); // Cull tanks behind the camera if (vecForward.Dot((vecOrigin-GameServer()->GetCameraManager()->GetCameraPosition()).Normalized()) < 0) continue; if (pDTEntity->IsObjective() && pDTEntity->IsActive()) { tstring sText = tsprintf(tstring("Objective: %s"), pDTEntity->GetEntityName().c_str()); float flWidth = RootPanel()->GetTextWidth(sText, sText.length(), _T("text"), 13); CLabel::PaintText(sText, sText.length(), _T("text"), 13, vecScreen.x - flWidth/2, vecScreen.y + 60); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ADDITIVE); PaintSheet(&m_HUDSheet, "Objective", (int)vecScreen.x - 50, (int)vecScreen.y - 50, 100, 100); } if (pDTEntity->GetVisibility() == 0) continue; CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity); if (!pSelectable) continue; CDigitank* pTank = dynamic_cast<CDigitank*>(pEntity); CStructure* pStructure = dynamic_cast<CStructure*>(pEntity); Vector vecTop = GameServer()->GetRenderer()->ScreenPosition(vecOrigin + vecUp*flRadius); float flWidth = (vecTop - vecScreen).Length()*2 + 10; bool bMouseOver = false; if (fabs(vecScreen.x - iMouseX) < flWidth/2 && fabs(vecScreen.y - iMouseY) < flWidth/2) bMouseOver = true; bool bShowBox = false; if (pCurrentLocalPlayer && pCurrentLocalPlayer->IsSelected(pSelectable)) bShowBox = true; if (bMouseOver) bShowBox = true; if (IsUpdatesPanelOpen()) bShowBox = false; if (bShowBox) { Color clrSelection(255, 255, 255, 128); if (pCurrentLocalPlayer && pCurrentLocalPlayer->IsPrimarySelection(pSelectable)) clrSelection = Color(255, 255, 255, 255); else if (pCurrentLocalPlayer && !pCurrentLocalPlayer->IsSelected(pSelectable) && bMouseOver) clrSelection = Color(255, 255, 255, 50); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y - flWidth/2), (int)flWidth, 1, clrSelection); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y - flWidth/2), 1, (int)flWidth, clrSelection); CRootPanel::PaintRect((int)(vecScreen.x + flWidth/2), (int)(vecScreen.y - flWidth/2), 1, (int)flWidth, clrSelection); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y + flWidth/2), (int)flWidth, 1, clrSelection); if (pTank && pTank->GetPlayerOwner() == pCurrentLocalPlayer) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); int iSize = 20; PaintWeaponSheet(pTank->GetCurrentWeapon(), (int)(vecScreen.x - flWidth/2) - 2, (int)(vecScreen.y + flWidth/2) - iSize + 2, iSize, iSize, Color(255, 255, 255, 255)); } } bool bShowHealth = false; if (pCurrentLocalPlayer && (pEntity->GetOwner() == pCurrentLocalPlayer || pCurrentLocalPlayer->IsSelected(pSelectable))) bShowHealth = true; if (bMouseOver) bShowHealth = true; if (DigitanksWindow()->IsAltDown()) bShowHealth = true; if (!pSelectable->ShowHealthBar()) bShowHealth = false; if (bShowHealth) { CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2 - 1), (int)(vecScreen.y - flWidth/2 - 11), (int)flWidth + 2, 5, Color(255, 255, 255, 128)); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y - flWidth/2 - 10), (int)(flWidth*pEntity->GetHealth()/pEntity->GetTotalHealth()), 3, Color(100, 255, 100)); } bool bShowPower = bMouseOver; if (DigitanksWindow()->IsAltDown()) bShowPower = true; if (pEntity->GetOwner() != pCurrentLocalPlayer) bShowPower = false; if (!pTank) bShowPower = false; if (bShowPower) { float flAttackPower = pTank->GetBaseAttackPower(true); float flDefensePower = pTank->GetBaseDefensePower(true); float flMovementPower = pTank->GetUsedMovementEnergy(true); float flTotalPower = pTank->GetStartingPower(); flAttackPower = flAttackPower/flTotalPower; flDefensePower = flDefensePower/flTotalPower; flMovementPower = flMovementPower/pTank->GetMaxMovementEnergy(); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2 - 1), (int)(vecScreen.y - flWidth/2 - 7), (int)(flWidth + 2), 5, Color(255, 255, 255, 128)); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y - flWidth/2 - 6), (int)(flWidth*flAttackPower), 3, Color(255, 0, 0)); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2 + flWidth*flAttackPower), (int)(vecScreen.y - flWidth/2 - 6), (int)(flWidth*flDefensePower), 3, Color(0, 0, 255)); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2 - 1), (int)(vecScreen.y - flWidth/2 - 3), (int)(flWidth + 2), 5, Color(255, 255, 255, 128)); CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y - flWidth/2 - 2), (int)(flWidth*flMovementPower), 3, Color(255, 255, 0)); } bool bShowGoalMove = pTank && pTank->GetPlayerOwner() == pCurrentLocalPlayer && pTank->HasGoalMovePosition(); if (bShowGoalMove) { float flDistance = (pTank->GetRealOrigin() - pTank->GetGoalMovePosition()).Length(); int iTurns = (int)(flDistance/pTank->GetMaxMovementDistance())+1; tstring sTurns = tsprintf(tstring(":%d"), iTurns); CLabel::PaintText(sTurns, sTurns.length(), _T("text"), 10, vecScreen.x + flWidth / 2 - 10, vecScreen.y - flWidth / 2 + RootPanel()->GetFontHeight(_T("text"), 10) - 2); } bool bShowFortify = pTank && (pTank->IsFortified() || pTank->IsFortifying()); if (pEntity->GetOwner() != pCurrentLocalPlayer) bShowFortify = false; if (bShowFortify) { tstring sTurns = tsprintf(tstring("+%d"), pTank->GetFortifyLevel()); float flYPosition = vecScreen.y + flWidth/2; float flXPosition = vecScreen.x + flWidth/2; float flIconSize = 10; CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); Rect rArea = m_ButtonSheet.GetArea("Fortify"); CBaseControl::PaintSheet(m_ButtonSheet.GetSheet("Fortify"), (int)(flXPosition - 14 - flIconSize), (int)(flYPosition - flIconSize)-1, (int)flIconSize, (int)flIconSize, rArea.x, rArea.y, rArea.w, rArea.y, m_ButtonSheet.GetSheetWidth("Fortify"), m_ButtonSheet.GetSheetHeight("Fortify")); CLabel::PaintText(sTurns, sTurns.length(), _T("text"), 10, flXPosition - 13, flYPosition - 3); } if (pStructure) { int iTurnsProgressed = 0; int iTotalTurns = 0; if (pStructure->IsConstructing()) { iTotalTurns = pStructure->GetTurnsToConstruct(pStructure->GetGlobalOrigin()); iTurnsProgressed = iTotalTurns-pStructure->GetTurnsRemainingToConstruct(); } else if (pStructure->IsUpgrading()) { iTotalTurns = pStructure->GetTurnsToUpgrade(); iTurnsProgressed = iTotalTurns-pStructure->GetTurnsRemainingToUpgrade(); } iTurnsProgressed++; iTotalTurns++; if (pStructure->IsConstructing() || pStructure->IsUpgrading()) CRootPanel::PaintRect((int)(vecScreen.x - flWidth/2), (int)(vecScreen.y - flWidth/2 - 2), (int)(flWidth*iTurnsProgressed/iTotalTurns), 3, Color(255, 255, 0)); if (pStructure->IsConstructing()) { tstring sTurns = tsprintf(tstring(":%d"), pStructure->GetTurnsRemainingToConstruct()); CLabel::PaintText(sTurns, sTurns.length(), _T("text"), 10, vecScreen.x + flWidth / 2 - 10, vecScreen.y - flWidth / 2 + RootPanel()->GetFontHeight(_T("text"), 10) - 2); } else if (pStructure->IsUpgrading()) { tstring sTurns = tsprintf(tstring(":%d"), pStructure->GetTurnsRemainingToUpgrade()); CLabel::PaintText(sTurns, sTurns.length(), _T("text"), 10, vecScreen.x + flWidth / 2 - 10, vecScreen.y - flWidth / 2 + RootPanel()->GetFontHeight(_T("text"), 10) - 2); } if (pStructure->GetUnitType() == STRUCTURE_CPU) { CCPU* pCPU = static_cast<CCPU*>(pStructure); if (pCPU->IsProducing()) { tstring sTurns = _T(":1"); // It only ever takes one turn to make a rogue. CLabel::PaintText(sTurns, sTurns.length(), _T("text"), 10, vecScreen.x + flWidth / 2 - 10, vecScreen.y - flWidth / 2 + RootPanel()->GetFontHeight(_T("text"), 10) - 2); } } if (pStructure->GetUnitType() == STRUCTURE_TANKLOADER || pStructure->GetUnitType() == STRUCTURE_INFANTRYLOADER || pStructure->GetUnitType() == STRUCTURE_ARTILLERYLOADER) { CLoader* pLoader = static_cast<CLoader*>(pStructure); if (pLoader->IsProducing()) { tstring sTurns = tsprintf(tstring(":%d"), pLoader->GetTurnsRemainingToProduce()); CLabel::PaintText(sTurns, sTurns.length(), _T("text"), 10, vecScreen.x + flWidth / 2 - 10, vecScreen.y - flWidth / 2 + RootPanel()->GetFontHeight(_T("text"), 10) - 2); } } } if (pTank && pTank->IsDisabled()) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); int iWidth = 77*2/3; int iHeight = 39*2/3; CHUD::PaintHUDSheet("TankDisabled", (int)(vecScreen.x + flWidth/2), (int)(vecScreen.y - flWidth + 2), iWidth, iHeight, Color(255, 255, 255, 255)); int iFontSize = 17; tstring sZZZ = _T("zzz"); float flTextWidth = RootPanel()->GetTextWidth(sZZZ, sZZZ.length(), _T("smileys"), iFontSize); float flTextHeight = RootPanel()->GetFontHeight(_T("smileys"), iFontSize); float flLerp = fmod(GameServer()->GetGameTime(), 2.0); if (flLerp < 0.5f) sZZZ = _T("z"); else if (flLerp < 1.0f) sZZZ = _T("zz"); CLabel::PaintText(sZZZ, sZZZ.length(), _T("smileys"), iFontSize, vecScreen.x + flWidth/2 + iWidth/2 - flTextWidth/2, vecScreen.y - flWidth + iHeight/2 + 3); } if (m_bHUDActive && pTank && DigitanksGame()->GetCurrentPlayer()->IsPrimarySelection(pTank) && DigitanksGame()->GetControlMode() == MODE_AIM) UpdateInfo(); } bool bShowCPUStuff = false; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetPrimaryCPU()) bShowCPUStuff = true; if (bShowCPUStuff) m_pCloseActionItems->Paint(); do { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); // Main control pannel PaintHUDSheet("MainControlPanel", iWidth/2 - 720/2, iHeight-160, 720, 160); if (bShowCPUStuff && (DigitanksGame()->GetGameType() == GAMETYPE_STANDARD || DigitanksGame()->GetGameType() == GAMETYPE_CAMPAIGN)) { if (m_bUpdatesBlinking) { int iArrowWidth = 50; int iArrowHeight = 82; PaintHUDSheet("HintArrow", m_pUpdatesButton->GetLeft() + m_pUpdatesButton->GetWidth()/2 - iArrowWidth/2, 40 + (int)(Bias(Oscillate(GameServer()->GetGameTime(), 1), 0.8f)*20), iArrowWidth, iArrowHeight); } PaintHUDSheet("PowerIcon", iWidth - 190, 10, 20, 20); PaintHUDSheet("FleetPointsIcon", iWidth - 190, 40, 20, 20); PaintHUDSheet("BandwidthIcon", iWidth - 190, 70, 20, 20); PaintHUDSheet("TurnReport", m_pTurnInfo->GetLeft()-15, m_pTurnInfo->GetBottom()-585, 278, 600); int iResearchWidth = 617; PaintHUDSheet("ResearchBar", iWidth/2 - iResearchWidth/2, 0, iResearchWidth, 35); CRootPanel::PaintRect(iWidth/2 - iResearchWidth/2 - 34, 0, 34, 35, Color(0, 0, 0, 150)); if (pCurrentLocalPlayer && pCurrentLocalPlayer->GetUpdateDownloading()) { CUpdateItem* pItem = pCurrentLocalPlayer->GetUpdateDownloading(); int iDownloadedWidth = 580; float flUpdateDownloaded = pCurrentLocalPlayer->GetUpdateDownloaded(); if (flUpdateDownloaded > pItem->m_flSize) flUpdateDownloaded = pItem->m_flSize; int iResearchCompleted = (int)(iDownloadedWidth*(flUpdateDownloaded/pItem->m_flSize)); int iResearchDue = (int)(iDownloadedWidth*(pCurrentLocalPlayer->GetBandwidth()/pItem->m_flSize)); if (iResearchCompleted + iResearchDue > iDownloadedWidth) iResearchDue -= (iResearchCompleted + iResearchDue) - iDownloadedWidth; CRootPanel::PaintRect(iWidth/2 - iDownloadedWidth/2, 3, iResearchCompleted, 20, Color(0, 200, 100, 255)); CRootPanel::PaintRect(iWidth/2 - iDownloadedWidth/2 + iResearchCompleted, 3, iResearchDue, 20, Color(0, 200, 100, 100)); CMaterialHandle hItemSheet; int sx, sy, sw, sh, tw, th; m_pUpdatesPanel->GetTextureForUpdateItem(pItem, hItemSheet, sx, sy, sw, sh, tw, th); float flSlideTime = 0.8f; if (hItemSheet && GameServer()->GetGameTime() - m_flUpdateIconSlide < flSlideTime) { float flSlideLerp = Bias((GameServer()->GetGameTime() - m_flUpdateIconSlide)/flSlideTime, 0.7f); int iIconX = (int)RemapValClamped(flSlideLerp, 0.0f, 1.0f, (float)m_iUpdateIconSlideStartX, (float)(iWidth/2 - iResearchWidth/2 - 35)); int iIconY = (int)RemapValClamped(flSlideLerp, 0.0f, 1.0f, (float)m_iUpdateIconSlideStartY, 0.0f); int iButtonSize = (int)RemapValClamped(flSlideLerp, 0.0f, 1.0f, (float)m_pUpdatesPanel->GetButtonSize(), 35.0f); CRootPanel::PaintSheet(hItemSheet, iIconX, iIconY, iButtonSize, iButtonSize, sx, sy, sw, sh, tw, th); } } } if (m_flAttackInfoAlpha > 0) PaintHUDSheet("AttackInfo", iWidth-175, m_pAttackInfo->GetTop()-15, 175, 110, Color(255, 255, 255, (int)(255*m_flAttackInfoAlpha))); if (m_flTurnWarningLerp > 0) { float flWarningLerp = Bias(m_flTurnWarningLerp, 0.7f); m_pTurnWarning->SetText(_T("WARNING!\n \nSome tanks still need orders. Ending the turn will forfeit their moves or attacks.")); m_pTurnWarning->SetSize(220, 75); m_pTurnWarning->SetPos(iWidth - (int)(220*flWarningLerp), iHeight - 75 - 90 - 10); m_pTurnWarning->SetAlpha(m_flTurnWarningLerp); CRootPanel::PaintRect(m_pTurnWarning->GetLeft()-3, m_pTurnWarning->GetTop()-9, m_pTurnWarning->GetWidth()+6, m_pTurnWarning->GetHeight()+6); } else { m_pTurnWarning->SetAlpha(0); } if (bShowCPUStuff && m_flActionItemsLerp > 0) PaintHUDSheet("ActionItemPanel", m_pActionItem->GetLeft()-30, m_pActionItem->GetTop()-30, (int)m_flActionItemsWidth, 340, Color(255, 255, 255, (int)(255*m_flActionItemsLerp))); // Tank info PaintHUDSheet("TankInfo", 0, iHeight-250, 150, 250); } while (false); if (DigitanksGame()->GetGameType() == GAMETYPE_STANDARD) CRootPanel::PaintRect(m_pScoreboard->GetLeft()-3, m_pScoreboard->GetTop()-9, m_pScoreboard->GetWidth()+6, m_pScoreboard->GetHeight()+6, Color(0, 0, 0, 100)); size_t iX, iY, iX2, iY2; if (pCurrentLocalPlayer && pCurrentLocalPlayer->GetBoxSelection(iX, iY, iX2, iY2)) { Color clrSelection(255, 255, 255, 255); size_t iWidth = iX2 - iX; size_t iHeight = iY2 - iY; CRootPanel::PaintRect(iX, iY, iWidth, 1, clrSelection); CRootPanel::PaintRect(iX, iY, 1, iHeight, clrSelection); CRootPanel::PaintRect(iX + iWidth, iY, 1, iHeight, clrSelection); CRootPanel::PaintRect(iX, iY + iHeight, iWidth, 1, clrSelection); } if (pCurrentLocalPlayer && !m_hHintWeapon) { for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); if (!pEntity) continue; CDigitanksWeapon* pWeapon = dynamic_cast<CDigitanksWeapon*>(pEntity); if (!pWeapon) continue; if (pWeapon->HasExploded()) continue; if (!pWeapon->UsesSpecialCommand()) continue; if (pWeapon->HasFragmented()) continue; if (!pWeapon->GetOwner()) continue; if (pWeapon->GetOwner()->GetPlayerOwner() != pCurrentLocalPlayer) continue; if (pWeapon->GetBonusDamage() > 0) continue; m_hHintWeapon = pWeapon; break; } } if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY && m_hHintWeapon != NULL) { int iX = GetWidth()/2 - 75; int iY = GetHeight()/2 + 50; CRootPanel::PaintRect(iX, iY, 150, 85, Color(0, 0, 0, 150)); m_pSpacebarHint->SetVisible(true); m_pSpacebarHint->SetText(m_hHintWeapon->SpecialCommandHint()); m_pSpacebarHint->SetSize(150, 25); m_pSpacebarHint->SetPos(iX, iY + 50); m_pSpacebarHint->SetWrap(false); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); iY -= (int)(Bias(Oscillate(GameServer()->GetGameTime(), 0.5f), 0.2f) * 10); PaintSheet(&m_KeysSheet, "SpaceBar", iX+45, iY, 60, 60); } else { m_pSpacebarHint->SetVisible(false); } if (DigitanksGame()->GetPrimarySelectionTank() && DigitanksGame()->GetControlMode() == MODE_AIM) { if (DigitanksGame()->GetAimType() == AIM_NORMAL) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); int iX = GetWidth()/2 - 150; int iY = GetHeight()/2 - 150; bool bObstruction = false; CDigitank* pDigitank = DigitanksGame()->GetPrimarySelectionTank(); Vector vecTankOrigin = pDigitank->GetGlobalOrigin() + Vector(0, 0, 1); float flGravity = DigitanksGame()->GetGravity(); float flTime; Vector vecForce; FindLaunchVelocity(vecTankOrigin, pDigitank->GetPreviewAim(), flGravity, vecForce, flTime, pDigitank->ProjectileCurve()); size_t iLinks = 10; float flTimePerLink = flTime/iLinks; Vector vecLastOrigin = vecTankOrigin; Vector vecPoint; for (size_t i = 1; i < iLinks; i++) { float flCurrentTime = flTimePerLink*i; Vector vecCurrentOrigin = vecTankOrigin + vecForce*flCurrentTime + Vector(0, 0, flGravity*flCurrentTime*flCurrentTime/2); if (DigitanksGame()->TraceLine(vecLastOrigin, vecCurrentOrigin, vecPoint, nullptr, true)) { bObstruction = true; break; } vecLastOrigin = vecCurrentOrigin; } weapon_t eWeapon = DigitanksGame()->GetPrimarySelectionTank()->GetCurrentWeapon(); if (eWeapon == WEAPON_LASER || eWeapon == WEAPON_INFANTRYLASER || eWeapon == PROJECTILE_TORPEDO) bObstruction = false; if (bObstruction) PaintHUDSheet("Obstruction", iX, iY, 124, 68, Color(255, 255, 255, (int)RemapVal(Oscillate(GameServer()->GetGameTime(), 0.8f), 0, 1, 150, 255))); } } bool bCloseVisible = m_pCloseActionItems->IsVisible(); m_pCloseActionItems->SetVisible(false); m_pButtonInfo->SetVisible(false); m_pTeamInfo->SetVisible(false); CPanel::Paint(x, y, w, h); m_pCloseActionItems->SetVisible(bCloseVisible); if (m_pButtonInfo->GetText()[0] != _T('\0')) { CRootPanel::PaintRect(m_pButtonInfo->GetLeft()-3, m_pButtonInfo->GetTop()-9, m_pButtonInfo->GetWidth()+6, m_pButtonInfo->GetHeight()+6, Color(0, 0, 0)); m_pButtonInfo->SetVisible(true); m_pButtonInfo->Paint(); } CSelectable* pSelection = DigitanksGame()->GetPrimarySelection(); if (pSelection) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); int iSize = 100; CDigitank* pTank = DigitanksGame()->GetPrimarySelectionTank(); if (pTank) iSize = 50; Color clrTeam(255, 255, 255, 255); if (pSelection->GetPlayerOwner()) clrTeam = pSelection->GetPlayerOwner()->GetColor(); PaintUnitSheet(pSelection->GetUnitType(), iWidth/2 - 720/2 + 10 + 150/2 - iSize/2, iHeight - 150 + 10 + 130/2 - iSize/2, iSize, iSize, clrTeam); pSelection->DrawSchema(iWidth/2 - 720/2 + 10 + 150/2 - 100/2, iHeight - 150 + 10 + 130/2 - 100/2, 100, 100); pSelection->DrawQueue(iWidth/2 - 720/2 + 162, iHeight - 90, 216, 84); } CDigitank* pTank = DigitanksGame()->GetPrimarySelectionTank(); if (pTank) { if (pTank->GetShieldValue() > 5) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ADDITIVE); float flFlicker = 1; if (pTank->GetShieldValue() < pTank->GetShieldMaxStrength()*3/4) flFlicker = Flicker("zzzzmmzzztzzzzzznzzz", GameServer()->GetGameTime() + ((float)pTank->GetSpawnSeed()/100), 1.0f); int iShield = (int)(255*flFlicker*pTank->GetDefensePower(true)/pTank->GetStartingPower()); if (iShield > 255) iShield = 255; int iSize = 100; glgui::CBaseControl::PaintTexture(m_hShieldTexture, iWidth/2 - 720/2 + 10 + 150/2 - iSize/2, iHeight - 150 + 10 + 130/2 - iSize/2, iSize, iSize, Color(255, 255, 255, iShield)); } } if (m_eActionSign) { float flAnimationTime = GameServer()->GetGameTime() - m_flActionSignStart; if (flAnimationTime > 2.0f) m_eActionSign = ACTIONSIGN_NONE; else { float flWarpIn = RemapValClamped(flAnimationTime, 0, 0.5f, 0, 1); float flAlpha = RemapValClamped(flAnimationTime, 1.3f, 1.8f, 1, 0); size_t iTotalWidth = RootPanel()->GetWidth(); size_t iTotalHeight = RootPanel()->GetHeight(); size_t iTankWidth = iTotalWidth/4; size_t iTankHeight = iTankWidth/2; size_t iTankOffset = (size_t)(Bias(1-flWarpIn, 0.2f) * iTankWidth*2); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); PaintSheet(m_hActionTanksSheet, iTotalWidth-iTankWidth*3/2 + iTankOffset, iTotalHeight/2-iTankHeight/2, iTankWidth, iTankHeight, 0, 0, 512, 256, 512, 512, Color(255, 255, 255, (int)(flAlpha*255))); PaintSheet(m_hActionTanksSheet, iTankWidth/2 - iTankOffset, iTotalHeight/2-iTankHeight/2, iTankWidth, iTankHeight, 0, 256, 512, 256, 512, 512, Color(255, 255, 255, (int)(flAlpha*255))); size_t iSignWidth = (size_t)(iTotalWidth/2 * Bias(flWarpIn, 0.2f)); size_t iSignHeight = (size_t)(iSignWidth*0.32f); if (m_eActionSign == ACTIONSIGN_FIGHT) PaintSheet(&m_ActionSignsSheet, "Fight", iTotalWidth/2-iSignWidth/2, iTotalHeight/2-iSignHeight/2, iSignWidth, iSignHeight, Color(255, 255, 255, (int)(flAlpha*255))); else if (m_eActionSign == ACTIONSIGN_SHOWDOWN) PaintSheet(&m_ActionSignsSheet, "Showdown", iTotalWidth/2-iSignWidth/2, iTotalHeight/2-iSignHeight/2, iSignWidth, iSignHeight, Color(255, 255, 255, (int)(flAlpha*255))); else if (m_eActionSign == ACTIONSIGN_NEWTURN) PaintSheet(&m_ActionSignsSheet, "NewTurn", iTotalWidth/2-iSignWidth/2, iTotalHeight/2-iSignHeight/2, iSignWidth, iSignHeight, Color(255, 255, 255, (int)(flAlpha*255))); } } if (m_pTeamInfo->GetText().length() > 0) CRootPanel::PaintRect(m_pTeamInfo->GetLeft()-3, m_pTeamInfo->GetTop()-9, m_pTeamInfo->GetWidth()+6, m_pTeamInfo->GetHeight()+6, Color(0, 0, 0, 220)); m_pTeamInfo->SetVisible(true); m_pTeamInfo->Paint(); if (m_iCurrentSmallActionItem < m_apActionItemButtons.size() && m_flSmallActionItemLerp > 0) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); CPictureButton* pActionItem = m_apActionItemButtons[m_iCurrentSmallActionItem]; int iLeft = pActionItem->GetLeft(); int iTop = pActionItem->GetTop(); int iTextureLeft = iLeft - 243; PaintHUDSheet("SmallActionItem", iTextureLeft - 10, iTop, 243, 40, Color(255, 255, 255, (int)(255*m_flSmallActionItemLerp))); c.SetColor(Color(255, 255, 255, (int)(255*m_flSmallActionItemLerp))); float flWidth = RootPanel()->GetTextWidth(m_sSmallActionItem, m_sSmallActionItem.length(), _T("text"), 13); float flHeight = RootPanel()->GetFontHeight(_T("text"), 13); CLabel::PaintText(m_sSmallActionItem, m_sSmallActionItem.length(), _T("text"), 13, (float)(iLeft - flWidth) - 25, iTop + flHeight + 5); } for (size_t i = 0; i < m_apActionItemButtons.size(); i++) { if (i >= m_apActionItemButtons.size() || i >= DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems()) break; CPictureButton* pButton = m_apActionItemButtons[i]; if (!pButton) continue; if (!DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(i)) continue; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(i)->bHandled) { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); PaintHUDSheet("CheckMark", pButton->GetLeft(), pButton->GetTop(), pButton->GetWidth(), pButton->GetHeight(), Color(255, 255, 255)); } } if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY) { // Don't clear it in the start, we want dead tanks to remain in the list so we can mark them asploded. CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); for (size_t i = 0; i < DigitanksGame()->GetNumPlayers(); i++) { const CDigitanksPlayer* pTeam = DigitanksGame()->GetDigitanksPlayer(i); if (!pTeam) continue; if (i >= m_ahScoreboardTanks.size()) continue; tmap<size_t, CEntityHandle<CDigitank> >& ahTeamTanks = m_ahScoreboardTanks[i]; Color clrTeam = pTeam->GetColor(); if (DigitanksGame()->GetCurrentPlayer() == pTeam) clrTeam.SetAlpha((int)(255 * Oscillate(GameServer()->GetGameTime(), 1))); c.SetColor(clrTeam); if (DigitanksGame()->GetCurrentPlayer() == pTeam) CBaseControl::PaintRect(w - ahTeamTanks.size() * 30 - 20, 35 + i*40, ahTeamTanks.size()*30+10, 45, Color(0, 0, 0, 150)); tstring sTeamName = pTeam->GetPlayerName(); if (pTeam->IsHumanControlled()) sTeamName = tstring(_T("[")) + sTeamName + _T("]"); CLabel::PaintText(sTeamName, sTeamName.length(), _T("text"), 13, (float)w - RootPanel()->GetTextWidth(sTeamName, sTeamName.length(), _T("text"), 13) - 20, 50 - RootPanel()->GetFontHeight("text", 13) + (float)i * 40, clrTeam); int iTank = 0; for (tmap<size_t, CEntityHandle<CDigitank> >::iterator it = ahTeamTanks.begin(); it != ahTeamTanks.end(); it++) { CDigitank* pTank = it->second; Color clrTank = pTeam->GetColor(); if (!pTank || !pTank->IsAlive()) clrTank.SetAlpha(100); PaintUnitSheet(UNIT_TANK, w - (iTank+1)*30 - 10, 50 + i*40, 20, 20, clrTank); if (!pTank || !pTank->IsAlive()) PaintHUDSheet("DeadTank", w - (iTank+1)*30 - 10, 50 + i*40, 20, 20); iTank++; } } } int iNotificationHeight = 40; int iFirstNotificationHeight = glgui::CRootPanel::Get()->GetHeight()/3 - 50; int iNotificationX = glgui::CRootPanel::Get()->GetWidth()/6; for (size_t i = 0; i < m_aPowerupNotifications.size(); i++) { powerup_notification_t* pNotification = &m_aPowerupNotifications[i]; if (!pNotification->bActive) continue; if (!pNotification->hEntity || GameServer()->GetGameTime() - pNotification->flTime > 3) { pNotification->bActive = false; continue; } if (pNotification->hEntity->GetPlayerOwner() != DigitanksGame()->GetCurrentLocalDigitanksPlayer()) continue; float flLerpIn = Bias(RemapValClamped(GameServer()->GetGameTime() - pNotification->flTime, 0, 0.5, 0.0, 1), 0.2f); int iX = (int)RemapValClamped(flLerpIn, 0, 1, -350, (float)iNotificationX); int iY = iFirstNotificationHeight - (iNotificationHeight+10)*i; Color clrBox = glgui::g_clrBox; clrBox.SetAlpha((float)RemapValClamped(GameServer()->GetGameTime() - pNotification->flTime, 1.5, 2, 1.0, 0)); glgui::CRootPanel::PaintRect(iX, iY, 350, iNotificationHeight, clrBox); if (GameServer()->GetGameTime() - pNotification->flTime < 2) { tstring sText; if (pNotification->ePowerupType == POWERUP_TANK) { if (dynamic_cast<CDigitank*>(pNotification->hEntity.GetPointer())) sText = _T("Bonus Tank Received!"); else sText = _T("Structure Rescued!"); } else if (pNotification->ePowerupType == POWERUP_MISSILEDEFENSE) sText = _T("Missile Defense Received!"); else if (pNotification->ePowerupType == POWERUP_AIRSTRIKE) sText = _T("Airstrike Received!"); else sText = _T("Tank Upgrade Received!"); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetAlpha(RemapValClamped(GameServer()->GetGameTime() - pNotification->flTime, 1.5, 2, 1.0, 0)); c.SetColor(Color(255, 255, 255, 255)); glgui::CLabel::PaintText(sText, sText.length(), _T("header"), 18, (float)(iX + iNotificationHeight + 20), (float)(iY + iNotificationHeight - 15)); } float iSceneX, iSceneY, iSceneW, iSceneH; m_pSceneTree->GetUnitDimensions(pNotification->hEntity, iSceneX, iSceneY, iSceneW, iSceneH); int iIconX, iIconY, iIconW, iIconH; int iSpacing = 3; float flMoveLerp = Gain(RemapValClamped(GameServer()->GetGameTime() - pNotification->flTime, 2.0, 2.5, 0.0, 1), 0.1f); iIconX = (int)RemapValClamped(flMoveLerp, 0, 1, (float)iX+iSpacing, (float)iSceneX); iIconY = (int)RemapValClamped(flMoveLerp, 0, 1, (float)iY+iSpacing, (float)iSceneY); iIconW = (int)RemapValClamped(flMoveLerp, 0, 1, (float)iNotificationHeight-iSpacing*2, (float)iSceneH); iIconH = (int)RemapValClamped(flMoveLerp, 0, 1, (float)iNotificationHeight-iSpacing*2, (float)iSceneH); tstring sArea; if (pNotification->ePowerupType == POWERUP_AIRSTRIKE) sArea = "Airstrike"; else if (pNotification->ePowerupType == POWERUP_TANK) { if (pNotification->hEntity->GetUnitType() == STRUCTURE_CPU) sArea = "NewCPU"; else if (pNotification->hEntity->GetUnitType() == UNIT_SCOUT) sArea = "NewRogue"; else if (pNotification->hEntity->GetUnitType() == UNIT_INFANTRY) sArea = "NewResistor"; else sArea = "NewDigitank"; } else sArea = "Upgrade"; CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ADDITIVE); Color clrPowerup(255, 255, 255, 255); clrPowerup.SetAlpha((float)RemapValClamped(GameServer()->GetGameTime() - pNotification->flTime, 2.5, 3.0, 1.0, 0)); PaintSheet(&m_PowerupsSheet, sArea, iIconX, iIconY, iIconW, iIconH, clrPowerup); } if (m_flSelectorMedalStart > 0 && GameServer()->GetGameTime() > m_flSelectorMedalStart) { double flMedalDisplayTime = 5; if (GameServer()->GetGameTime() > m_flSelectorMedalStart + flMedalDisplayTime) m_flSelectorMedalStart = 0; float flAlpha = RemapValClamped(GameServer()->GetGameTime(), m_flSelectorMedalStart, m_flSelectorMedalStart+0.5, 0.0, 1); if (GameServer()->GetGameTime() - m_flSelectorMedalStart > flMedalDisplayTime-1) flAlpha = RemapValClamped(GameServer()->GetGameTime(), m_flSelectorMedalStart+flMedalDisplayTime-1, m_flSelectorMedalStart+flMedalDisplayTime, 1.0, 0); Color clrMedal = Color(255, 255, 255, (int)(255*flAlpha)); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); glgui::CBaseControl::PaintTexture(m_hSelectorMedalTexture, w/2-128, h/2-128, 256, 256, clrMedal); c.SetColor(clrMedal); tstring sMedal = _T("YOU RECEIVED A MEDAL"); float flMedalWidth = glgui::RootPanel()->GetTextWidth(sMedal, sMedal.length(), _T("header"), 18); glgui::CLabel::PaintText(sMedal, sMedal.length(), _T("header"), 18, w/2-flMedalWidth/2, h/2 + (float)120); } if (m_flFileRescueStart > 0 && GameServer()->GetGameTime() > m_flFileRescueStart) { double flFileRescueTime = 5; if (GameServer()->GetGameTime() > m_flFileRescueStart + flFileRescueTime) m_flFileRescueStart = 0; float flAlpha = RemapValClamped(GameServer()->GetGameTime(), m_flFileRescueStart, m_flFileRescueStart+0.5, 0.0, 1); if (GameServer()->GetGameTime() - m_flFileRescueStart > flFileRescueTime-1) flAlpha = RemapValClamped(GameServer()->GetGameTime(), m_flFileRescueStart+flFileRescueTime-1, m_flFileRescueStart+flFileRescueTime, 1.0, 0); Color clrFile = Color(255, 255, 255, (int)(255*flAlpha)); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); glgui::CBaseControl::PaintTexture(CMaterialLibrary::FindAsset(m_sFileRescueTexture), w/2-128, h/2-128, 256, 256, clrFile); c.SetColor(clrFile); tstring sText = _T("FILE RETRIEVED"); float flTextWidth = glgui::RootPanel()->GetTextWidth(sText, sText.length(), _T("header"), 18); glgui::CLabel::PaintText(sText, sText.length(), _T("header"), 18, w/2-flTextWidth/2, h/2 + (float)150); } if (m_eMenuMode == MENUMODE_PROMOTE) { tstring sChooseHint = _T("Choose a promotion for this unit below."); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); c.SetColor(Color(255, 255, 255, (int)(255*RemapVal(Oscillate(GameServer()->GetGameTime(), 1), 0, 1, 0.5f, 1)))); float flHintWidth = glgui::RootPanel()->GetTextWidth(sChooseHint, sChooseHint.length(), _T("text"), 9); glgui::CLabel::PaintText(sChooseHint, sChooseHint.length(), _T("text"), 9, (float)(m_pButtonPanel->GetLeft() + m_pButtonPanel->GetWidth()/2) - flHintWidth/2, (float)(m_pButtonPanel->GetTop() - 12)); } CRenderingContext::DebugFinish(); } void CHUD::PaintCameraGuidedMissile(float x, float y, float w, float h) { CCameraGuidedMissile* pMissile = DigitanksGame()->GetOverheadCamera()->GetCameraGuidedMissile(); if (!pMissile->GetOwner()) return; Color clrWhite = Color(255, 255, 255, 120); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ADDITIVE); c.SetColor(clrWhite); if (!pMissile->IsBoosting() && GameServer()->GetGameTime() - pMissile->GetSpawnTime() < 3) { tstring sLaunch = _T("LAUNCH IN"); float flLaunchWidth = glgui::RootPanel()->GetTextWidth(sLaunch, sLaunch.length(), _T("cameramissile"), 40); glgui::CLabel::PaintText(sLaunch, sLaunch.length(), _T("cameramissile"), 40, w/2-flLaunchWidth/2, 150); sLaunch = tsprintf(tstring("%.1f"), 3 - (GameServer()->GetGameTime() - pMissile->GetSpawnTime())); flLaunchWidth = glgui::RootPanel()->GetTextWidth(sLaunch, sLaunch.length(), _T("cameramissile"), 40); glgui::CLabel::PaintText(sLaunch, sLaunch.length(), _T("cameramissile"), 40, w/2-flLaunchWidth/2, 200); } CDigitank* pOwner = dynamic_cast<CDigitank*>(pMissile->GetOwner()); if (!pOwner) return; tstring sRange = tsprintf(tstring("RANGE %.2f"), (pOwner->GetLastAim() - pMissile->GetGlobalOrigin()).Length()); glgui::CLabel::PaintText(sRange, sRange.length(), _T("cameramissile"), 20, 10, 100); Vector vecHit; CBaseEntity* pHit; bool bHit = DigitanksGame()->TraceLine(pOwner->GetLastAim() + Vector(0, 0, 1), pMissile->GetGlobalOrigin(), vecHit, &pHit, true); tstring sClear; if (bHit) sClear = _T("OBSTRUCTION"); else sClear = _T("CLEAR"); glgui::CLabel::PaintText(sClear, sClear.length(), _T("cameramissile"), 20, 10, 200); tstring sAltitude = tsprintf(tstring("ALT %.2f"), pMissile->GetGlobalOrigin().z - DigitanksGame()->GetTerrain()->GetHeight(pMissile->GetGlobalOrigin().x, pMissile->GetGlobalOrigin().y)); glgui::CLabel::PaintText(sAltitude, sAltitude.length(), _T("cameramissile"), 20, 10, 300); tstring sFuel = tsprintf(tstring("FUEL %.2f"), 13 - (GameServer()->GetGameTime() - pMissile->GetSpawnTime())); glgui::CLabel::PaintText(sFuel, sFuel.length(), _T("cameramissile"), 20, 10, 400); if (pMissile->IsBoosting() && Oscillate(GameServer()->GetGameTime(), 0.3f) > 0.1f) { tstring sBoost = _T("BOOST"); float flBoostWidth = glgui::RootPanel()->GetTextWidth(sBoost, sBoost.length(), _T("cameramissile"), 40); glgui::CLabel::PaintText(sBoost, sBoost.length(), _T("cameramissile"), 40, w/2-flBoostWidth/2, h - 200.0f); } int iBoxWidth = 300; glgui::CRootPanel::PaintRect(w/2-iBoxWidth/2, h/2-iBoxWidth/2, 1, iBoxWidth, clrWhite); glgui::CRootPanel::PaintRect(w/2-iBoxWidth/2, h/2-iBoxWidth/2, iBoxWidth, 1, clrWhite); glgui::CRootPanel::PaintRect(w/2+iBoxWidth/2, h/2-iBoxWidth/2, 1, iBoxWidth, clrWhite); glgui::CRootPanel::PaintRect(w/2-iBoxWidth/2, h/2+iBoxWidth/2, 300, 1, clrWhite); int iTrackingWidth = 500; glgui::CRootPanel::PaintRect(w/2-iTrackingWidth/2, h/2-iTrackingWidth/2-50, iTrackingWidth, 1, clrWhite); glgui::CRootPanel::PaintRect(w/2-iTrackingWidth/2, h/2+iTrackingWidth/2+50, iTrackingWidth, 1, clrWhite); EAngle angCamera = pMissile->GetGlobalAngles(); int iTicks = 10; int iPixelsPerTick = iTrackingWidth/iTicks; for (int i = 0; i <= 10; i++) { int iOffset = iPixelsPerTick*i; int iXPosition = w/2-iTrackingWidth/2 + iOffset + (int)fmod(-angCamera.y*1.5f, (float)iPixelsPerTick); if (iXPosition < w/2-iTrackingWidth/2) continue; if (iXPosition > w/2+iTrackingWidth/2) continue; glgui::CRootPanel::PaintRect(iXPosition, h/2-iTrackingWidth/2-50+1, 1, 8, clrWhite); glgui::CRootPanel::PaintRect(iXPosition, h/2+iTrackingWidth/2+50-8, 1, 8, clrWhite); } glgui::CRootPanel::PaintRect(w/2-iTrackingWidth/2-50, h/2-iTrackingWidth/2, 1, iTrackingWidth, clrWhite); glgui::CRootPanel::PaintRect(w/2+iTrackingWidth/2+50, h/2-iTrackingWidth/2, 1, iTrackingWidth, clrWhite); for (int i = 0; i <= 10; i++) { int iOffset = iPixelsPerTick*i; int iYPosition = h/2-iTrackingWidth/2 + iOffset + (int)fmod(-angCamera.p*1.5f, (float)iPixelsPerTick); if (iYPosition < h/2-iTrackingWidth/2) continue; if (iYPosition > h/2+iTrackingWidth/2) continue; glgui::CRootPanel::PaintRect(w/2-iTrackingWidth/2-50+1, iYPosition, 8, 1, clrWhite); glgui::CRootPanel::PaintRect(w/2+iTrackingWidth/2+50-8, iYPosition, 8, 1, clrWhite); } Vector vecUp; Vector vecForward; GameServer()->GetRenderer()->GetCameraVectors(&vecForward, NULL, &vecUp); for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); CDigitanksEntity* pDTEntity = dynamic_cast<CDigitanksEntity*>(pEntity); if (!pDTEntity) continue; if (pDTEntity->GetVisibility() == 0) continue; CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity); if (!pSelectable) continue; CDigitank* pTank = dynamic_cast<CDigitank*>(pEntity); if (!pTank) continue; Vector vecOrigin = pEntity->GetGlobalOrigin(); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(vecOrigin); float flRadius = pDTEntity->GetBoundingRadius(); // Cull tanks behind the camera if (vecForward.Dot((vecOrigin-GameServer()->GetCameraManager()->GetCameraPosition()).Normalized()) < 0) continue; Vector vecTop = GameServer()->GetRenderer()->ScreenPosition(vecOrigin + vecUp*flRadius); float flWidth = (vecTop - vecScreen).Length()*2 + 10; if (vecScreen.x < w/2-iBoxWidth) continue; if (vecScreen.y < h/2-iBoxWidth) continue; if (vecScreen.x > w/2+iBoxWidth) continue; if (vecScreen.y > h/2+iBoxWidth) continue; Color clrTeam = Color(255, 255, 255); if (pTank->GetPlayerOwner()) clrTeam = pTank->GetPlayerOwner()->GetColor(); clrTeam.SetAlpha(clrWhite.a()); float flHole = 5; CRootPanel::PaintRect((int)(vecScreen.x - flWidth), (int)(vecScreen.y), (int)(flWidth - flHole), 1, clrTeam); CRootPanel::PaintRect((int)(vecScreen.x + flHole), (int)(vecScreen.y), (int)(flWidth - flHole), 1, clrTeam); CRootPanel::PaintRect((int)(vecScreen.x), (int)(vecScreen.y - flWidth), 1, (int)(flWidth - flHole), clrTeam); CRootPanel::PaintRect((int)(vecScreen.x), (int)(vecScreen.y + flHole), 1, (int)(flWidth - flHole), clrTeam); } if (Oscillate(GameServer()->GetGameTime(), 0.5f) > 0.3f) { if (vecForward.Dot((pOwner->GetLastAim()-GameServer()->GetCameraManager()->GetCameraPosition()).Normalized()) > 0) { Vector vecTarget = GameServer()->GetRenderer()->ScreenPosition(pOwner->GetLastAim()); float flWidth = 40; CRootPanel::PaintRect((int)(vecTarget.x - flWidth/2), (int)(vecTarget.y - flWidth/2), (int)flWidth, 1, clrWhite); CRootPanel::PaintRect((int)(vecTarget.x - flWidth/2), (int)(vecTarget.y - flWidth/2), 1, (int)flWidth, clrWhite); CRootPanel::PaintRect((int)(vecTarget.x + flWidth/2), (int)(vecTarget.y - flWidth/2), 1, (int)flWidth, clrWhite); CRootPanel::PaintRect((int)(vecTarget.x - flWidth/2), (int)(vecTarget.y + flWidth/2), (int)flWidth, 1, clrWhite); c.SetBlend(BLEND_NONE); CRootPanel::PaintRect((int)(vecTarget.x - flWidth/2) - 1, (int)(vecTarget.y - flWidth/2) - 1, (int)flWidth + 2, 1, Color(0, 0, 0)); CRootPanel::PaintRect((int)(vecTarget.x - flWidth/2) - 1, (int)(vecTarget.y - flWidth/2) - 1, 1, (int)flWidth + 2, Color(0, 0, 0)); CRootPanel::PaintRect((int)(vecTarget.x + flWidth/2) + 1, (int)(vecTarget.y - flWidth/2) - 1, 1, (int)flWidth + 2, Color(0, 0, 0)); CRootPanel::PaintRect((int)(vecTarget.x - flWidth/2) - 1, (int)(vecTarget.y + flWidth/2) + 1, (int)flWidth + 2, 1, Color(0, 0, 0)); } } m_hHintWeapon = pMissile; if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY && m_hHintWeapon != NULL && !pMissile->IsBoosting() && hud_enable.GetBool()) { int iX = GetWidth()/2 - 75; int iY = GetHeight()/2 + 50; CRootPanel::PaintRect(iX, iY, 150, 85, Color(0, 0, 0, 150)); m_pSpacebarHint->SetVisible(true); m_pSpacebarHint->SetText(m_hHintWeapon->SpecialCommandHint()); m_pSpacebarHint->SetSize(150, 25); m_pSpacebarHint->SetPos(iX, iY + 50); m_pSpacebarHint->SetWrap(false); CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); iY -= (int)(Bias(Oscillate(GameServer()->GetGameTime(), 0.5f), 0.2f) * 10); PaintSheet(&m_KeysSheet, "SpaceBar", iX+45, iY, 60, 60); m_pSpacebarHint->Paint(); } else { m_pSpacebarHint->SetVisible(false); } } // Let's phase this one out in favor of the below. void CHUD::PaintSheet(CMaterialHandle& hSheet, float x, float y, float w, float h, int sx, int sy, int sw, int sh, int tw, int th, const Color& c) { glgui::CBaseControl::PaintSheet(hSheet, x, y, w, h, sx, sy, sw, sh, tw, th, c); } void CHUD::PaintSheet(const CTextureSheet* pSheet, const tstring& sArea, float x, float y, float w, float h, const Color& c) { const Rect& rArea = pSheet->GetArea(sArea); glgui::CBaseControl::PaintSheet(pSheet->GetSheet(sArea), x, y, w, h, rArea.x, rArea.y, rArea.w, rArea.h, pSheet->GetSheetWidth(sArea), pSheet->GetSheetHeight(sArea), c); } void CHUD::PaintHUDSheet(const tstring& sArea, float x, float y, float w, float h, const Color& c) { CHUD* pHUD = DigitanksWindow()->GetHUD(); TAssert(pHUD); if (!pHUD) return; const Rect* pRect = &pHUD->m_HUDSheet.GetArea(sArea); CMaterialHandle hSheet = pHUD->m_HUDSheet.GetSheet(sArea); PaintSheet(hSheet, x, y, w, h, pRect->x, pRect->y, pRect->w, pRect->h, pHUD->m_HUDSheet.GetSheetWidth(sArea), pHUD->m_HUDSheet.GetSheetHeight(sArea), c); } const CTextureSheet& CHUD::GetHUDSheet() { return DigitanksWindow()->GetHUD()->m_HUDSheet; } void CHUD::GetUnitSheet(unittype_t eUnit, CMaterialHandle& hSheet, int& sx, int& sy, int& sw, int& sh, int& tw, int& th) { CTextureSheet* pUnits = &DigitanksWindow()->GetHUD()->m_UnitsSheet; tstring sArea; if (eUnit == UNIT_TANK) sArea = "Digitank"; else if (eUnit == UNIT_SCOUT) sArea = "Rogue"; else if (eUnit == UNIT_ARTILLERY) sArea = "Artillery"; else if (eUnit == UNIT_INFANTRY) sArea = "Resistor"; else if (eUnit == UNIT_MOBILECPU) sArea = "MobileCPU"; else if (eUnit == UNIT_GRIDBUG) sArea = "GridBug"; else if (eUnit == UNIT_BUGTURRET) sArea = "BugTurret"; else if (eUnit == STRUCTURE_MINIBUFFER) sArea = "Buffer"; else if (eUnit == STRUCTURE_BUFFER) sArea = "MacroBuffer"; else if (eUnit == STRUCTURE_BATTERY) sArea = "Capacitor"; else if (eUnit == STRUCTURE_PSU) sArea = "PSU"; else if (eUnit == STRUCTURE_INFANTRYLOADER) sArea = "ResistorFactory"; else if (eUnit == STRUCTURE_TANKLOADER) sArea = "DigitankFactory"; else if (eUnit == STRUCTURE_ARTILLERYLOADER) sArea = "ArtilleryFactory"; else if (eUnit == STRUCTURE_CPU) sArea = "CPU"; else if (eUnit == STRUCTURE_ELECTRONODE) sArea = "Electronode"; else if (eUnit == STRUCTURE_FIREWALL) sArea = "Firewall"; Rect rUnit = pUnits->GetArea(sArea); hSheet = pUnits->GetSheet(sArea); tw = pUnits->GetSheetWidth(sArea); th = pUnits->GetSheetHeight(sArea); sx = rUnit.x; sy = rUnit.y; sw = rUnit.w; sh = rUnit.h; } void CHUD::PaintUnitSheet(unittype_t eUnit, float x, float y, float w, float h, const Color& c) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetUnitSheet(eUnit, hSheet, sx, sy, sw, sh, tw, th); PaintSheet(hSheet, x, y, w, h, sx, sy, sw, sh, tw, th, c); } void CHUD::GetWeaponSheet(weapon_t eWeapon, CMaterialHandle& hSheet, int& sx, int& sy, int& sw, int& sh, int& tw, int& th) { CTextureSheet* pWeapons = &DigitanksWindow()->GetHUD()->m_WeaponsSheet; tstring sArea; switch (eWeapon) { default: case WEAPON_NONE: case PROJECTILE_SMALL: sArea = "LittleBoy"; break; case PROJECTILE_MEDIUM: sArea = "FatMan"; break; case PROJECTILE_LARGE: sArea = "BigMama"; break; case PROJECTILE_AOE: case PROJECTILE_ARTILLERY_AOE: sArea = "AOE"; break; case PROJECTILE_EMP: sArea = "EMP"; break; case PROJECTILE_ICBM: case PROJECTILE_ARTILLERY_ICBM: sArea = "ICBM"; break; case PROJECTILE_GRENADE: sArea = "Grenade"; break; case PROJECTILE_DAISYCHAIN: sArea = "DaisyChain"; break; case PROJECTILE_CLUSTERBOMB: sArea = "ClusterBomb"; break; case PROJECTILE_SPLOOGE: sArea = "Grapeshot"; break; case PROJECTILE_TRACTORBOMB: sArea = "RepulsorBomb"; break; case PROJECTILE_EARTHSHAKER: sArea = "Earthshaker"; break; case PROJECTILE_CAMERAGUIDED: sArea = "CameraGuidedMissile"; break; case WEAPON_LASER: case WEAPON_INFANTRYLASER: sArea = "FragmentationRay"; break; case WEAPON_CHARGERAM: sArea = "ChargingRAM"; break; case PROJECTILE_TREECUTTER: sArea = "TreeCutter"; break; case PROJECTILE_FLAK: sArea = "MachineGun"; break; case PROJECTILE_DEVASTATOR: sArea = "Devastator"; break; case PROJECTILE_TORPEDO: sArea = "Torpedo"; break; } Rect rUnit = pWeapons->GetArea(sArea); hSheet = pWeapons->GetSheet(sArea); tw = pWeapons->GetSheetWidth(sArea); th = pWeapons->GetSheetHeight(sArea); sx = rUnit.x; sy = rUnit.y; sw = rUnit.w; sh = rUnit.h; } void CHUD::PaintWeaponSheet(weapon_t eWeapon, float x, float y, float w, float h, const Color& c) { CMaterialHandle hSheet; int sx, sy, sw, sh, tw, th; GetWeaponSheet(eWeapon, hSheet, sx, sy, sw, sh, tw, th); PaintSheet(hSheet, x, y, w, h, sx, sy, sw, sh, tw, th, c); } const CTextureSheet& CHUD::GetWeaponSheet() { return DigitanksWindow()->GetHUD()->m_WeaponsSheet; } const CTextureSheet& CHUD::GetButtonSheet() { return DigitanksWindow()->GetHUD()->m_ButtonSheet; } const CTextureSheet& CHUD::GetDownloadSheet() { return DigitanksWindow()->GetHUD()->m_DownloadSheet; } const CTextureSheet& CHUD::GetKeysSheet() { return DigitanksWindow()->GetHUD()->m_KeysSheet; } CMaterialHandle CHUD::GetActionTanksSheet() { return DigitanksWindow()->GetHUD()->m_hActionTanksSheet; } CMaterialHandle CHUD::GetPurchasePanel() { return DigitanksWindow()->GetHUD()->m_hPurchasePanel; } CMaterialHandle CHUD::GetShieldTexture() { return DigitanksWindow()->GetHUD()->m_hShieldTexture; } void CHUD::ClientEnterGame() { UpdateInfo(); UpdateTeamInfo(); UpdateScoreboard(); UpdateTurnButton(); SetupMenu(); m_pPressEnter->SetText(""); m_pSceneTree->BuildTree(true); m_ahScoreboardTanks.clear(); Layout(); } void CHUD::UpdateInfo() { if (!DigitanksGame()) return; m_pAttackInfo->SetText(""); CDigitank* pCurrentTank = DigitanksGame()->GetPrimarySelectionTank(); if (pCurrentTank) UpdateTankInfo(pCurrentTank); CStructure* pCurrentStructure = DigitanksGame()->GetPrimarySelectionStructure(); if (pCurrentStructure) UpdateStructureInfo(pCurrentStructure); CSelectable* pCurrentSelection = DigitanksGame()->GetPrimarySelection(); if (pCurrentSelection) { tstring sInfo; pCurrentSelection->UpdateInfo(sInfo); m_pTankInfo->SetText(sInfo.c_str()); } else m_pTankInfo->SetText(_T("No selection.")); } void CHUD::UpdateTankInfo(CDigitank* pTank) { m_pAttackInfo->SetText(_T("")); Vector vecOrigin; if (DigitanksGame()->GetControlMode() == MODE_MOVE && pTank->GetPreviewMoveTurnPower() <= pTank->GetRemainingMovementEnergy()) vecOrigin = pTank->GetPreviewMove(); else vecOrigin = pTank->GetGlobalOrigin(); Vector vecAim; if (DigitanksGame()->GetControlMode() == MODE_AIM) vecAim = pTank->GetPreviewAim(); else vecAim = pTank->GetLastAim(); Vector vecAttack = vecOrigin - vecAim; float flAttackDistance = vecAttack.Length(); if (!pTank->IsInsideMaxRange(vecAim)) return; if (flAttackDistance < pTank->GetMinRange()) return; if (!pTank->IsPreviewAimValid()) return; float flRadius = pTank->FindAimRadius(vecAim); CDigitank* pClosestTarget = NULL; for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); if (!pEntity) continue; CDigitank* pTargetTank = dynamic_cast<CDigitank*>(pEntity); if (!pTargetTank) continue; if (pTargetTank == pTank) continue; if (pTargetTank->GetPlayerOwner() == pTank->GetPlayerOwner()) continue; Vector vecOrigin2D = pTargetTank->GetGlobalOrigin().Flattened(); Vector vecAim2D = vecAim.Flattened(); if ((vecOrigin2D - vecAim2D).LengthSqr() > flRadius*flRadius) continue; if (pTargetTank->GetVisibility() == 0) continue; if (!pClosestTarget) { pClosestTarget = pTargetTank; continue; } if ((pTargetTank->GetGlobalOrigin() - vecAim).LengthSqr() < (pClosestTarget->GetGlobalOrigin() - vecAim).LengthSqr()) pClosestTarget = pTargetTank; } if (!pClosestTarget) return; vecAttack = vecOrigin - pClosestTarget->GetGlobalOrigin(); Vector vecOrigin2D = pClosestTarget->GetGlobalOrigin().Flattened(); Vector vecAim2D = vecAim.Flattened(); float flTargetDistance = (vecAim2D - vecOrigin2D).Length(); if (flTargetDistance > flRadius) return; float flShieldStrength = pClosestTarget->GetShieldValue(); float flDamageBlocked = flShieldStrength * pClosestTarget->GetDefenseScale(true); float flAttackDamage = CDigitanksWeapon::GetWeaponDamage(pTank->GetCurrentWeapon()); float flShieldDamage; float flTankDamage = 0; if (flAttackDamage - flDamageBlocked <= 0) flShieldDamage = flAttackDamage; else { flShieldDamage = flDamageBlocked; flTankDamage = flAttackDamage - flDamageBlocked; } char szAttackInfo[1024]; sprintf(szAttackInfo, "ATTACK REPORT\n \n" "Shield Damage: %d/%d\n" "Hull Damage: %d/%d\n", (int)flShieldDamage, (int)(flShieldStrength * pClosestTarget->GetDefenseScale(true)), (int)flTankDamage, (int)pClosestTarget->GetHealth() ); m_pAttackInfo->SetText(szAttackInfo); } void CHUD::UpdateStructureInfo(CStructure* pStructure) { m_pAttackInfo->SetText(_T("")); } void CHUD::UpdateTeamInfo() { if (!DigitanksGame()) return; bool bShow = false; if (DigitanksGame()->GetGameType() == GAMETYPE_STANDARD || DigitanksGame()->GetGameType() == GAMETYPE_CAMPAIGN) bShow = true; if (!bShow) { m_pPowerInfo->SetText(""); m_pFleetInfo->SetText(""); m_pBandwidthInfo->SetText(""); return; } CDigitanksPlayer* pTeam = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); if (!pTeam) return; if (!pTeam->GetPrimaryCPU()) return; tstring s1; s1 = tsprintf(tstring("%d +%.1f/turn\n"), (int)pTeam->GetPower(), pTeam->GetPowerPerTurn()); m_pPowerInfo->SetText(s1); tstring s2; s2 = tsprintf(tstring("%d/%d\n"), pTeam->GetUsedFleetPoints(), pTeam->GetTotalFleetPoints()); m_pFleetInfo->SetText(s2); if (pTeam->GetUpdateDownloading()) { tstring s3; s3 = tsprintf(tstring("%d/%dmb +%.1fmb/turn\n"), (int)pTeam->GetUpdateDownloaded(), (int)pTeam->GetUpdateSize(), pTeam->GetBandwidth()); m_pBandwidthInfo->SetText(s3); } else m_pBandwidthInfo->SetText(tsprintf(tstring("%dmb +%.1fmb/turn\n"), (int)pTeam->GetMegabytes(), pTeam->GetBandwidth())); } void CHUD::UpdateScoreboard() { if (!DigitanksGame()) return; if (DigitanksGame()->GetGameType() != GAMETYPE_STANDARD) return; tvector<const CDigitanksPlayer*> apSortedTeams; // Prob not the fastest sorting algorithm but it doesn't need to be. for (size_t i = 0; i < DigitanksGame()->GetNumPlayers(); i++) { const CDigitanksPlayer* pTeam = DigitanksGame()->GetDigitanksPlayer(i); if (!pTeam->ShouldIncludeInScoreboard()) continue; if (apSortedTeams.size() == 0) { apSortedTeams.push_back(pTeam); continue; } bool bFound = false; for (size_t j = 0; j < apSortedTeams.size(); j++) { if (pTeam->GetScore() > apSortedTeams[j]->GetScore()) { apSortedTeams.insert(apSortedTeams.begin()+j, pTeam); bFound = true; break; } } if (!bFound) apSortedTeams.push_back(pTeam); } tstring s; tstring p; for (size_t i = 0; i < apSortedTeams.size(); i++) { const CDigitanksPlayer* pTeam = apSortedTeams[i]; if (DigitanksGame()->IsTeamControlledByMe(pTeam)) s += _T("["); s += pTeam->GetPlayerName(); if (DigitanksGame()->IsTeamControlledByMe(pTeam)) s += _T("]"); s += tsprintf(tstring(": %d\n"), pTeam->GetScore()); } m_pScoreboard->SetText(_T("Score:\n \n")); m_pScoreboard->AppendText(s); m_pScoreboard->SetSize(100, 9999); m_pScoreboard->SetSize(m_pScoreboard->GetWidth(), (int)m_pScoreboard->GetTextHeight()); int iWidth = RootPanel()->GetWidth(); m_pScoreboard->SetPos(iWidth - m_pScoreboard->GetWidth() - 10, m_pAttackInfo->GetTop() - m_pScoreboard->GetHeight() - 20); } void CHUD::UpdateTurnButton() { if (!IsVisible()) return; bool bWasBlinking = m_bBlinkTurnButton; m_bBlinkTurnButton = false; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()) return; if (!DigitanksGame()->GetCurrentLocalDigitanksPlayer()) return; if (!DigitanksGame()->IsTeamControlledByMe(DigitanksGame()->GetCurrentPlayer())) { SetButtonSheetTexture(m_pTurnButton, &m_HUDSheet, "EnemyTurnButton"); m_pPressEnter->SetVisible(true); return; } bool bTurnComplete = true; for (size_t i = 0; i < DigitanksGame()->GetCurrentPlayer()->GetNumUnits(); i++) { CDigitank* pTank = dynamic_cast<CDigitank*>(DigitanksGame()->GetCurrentPlayer()->GetUnit(i)); if (pTank) { if (pTank->NeedsOrders()) { bTurnComplete = false; break; } } } for (size_t i = 0; i < DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems(); i++) { const actionitem_t* pItem = DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(i); if (!pItem->bHandled) { bTurnComplete = false; break; } } if (bTurnComplete) { if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY && !bWasBlinking && DigitanksGame()->GetTurn() == 0 && !DigitanksWindow()->GetInstructor()->GetCurrentPanel()) DigitanksWindow()->GetInstructor()->DisplayLesson("artillery-endturn"); m_bBlinkTurnButton = true; SetButtonSheetTexture(m_pTurnButton, &m_HUDSheet, "TurnCompleteButton"); m_pPressEnter->SetVisible(true); } else { SetButtonSheetTexture(m_pTurnButton, &m_HUDSheet, "TurnButton"); m_pPressEnter->SetVisible(false); } if (DigitanksGame()->GetCurrentPlayer() != DigitanksGame()->GetCurrentLocalDigitanksPlayer()) m_pPressEnter->SetVisible(true); } void CHUD::SetupMenu() { SetupMenu(m_eMenuMode); } void CHUD::SetupMenu(menumode_t eMenuMode) { if (!DigitanksGame()) return; Color clrBox = glgui::g_clrBox; clrBox.SetAlpha(100); for (size_t i = 0; i < NUM_BUTTONS; i++) { m_apButtons[i]->SetClickedListener(NULL, NULL); m_apButtons[i]->SetEnabled(false); SetButtonColor(i, clrBox); m_apButtons[i]->SetTexture(CMaterialHandle()); SetButtonInfo(i, _T("")); SetButtonTooltip(i, _T("")); } if (!IsActive() || !DigitanksGame()->GetPrimarySelection() || DigitanksGame()->GetPrimarySelection()->GetPlayerOwner() != DigitanksGame()->GetCurrentLocalDigitanksPlayer()) return; DigitanksGame()->GetPrimarySelection()->SetupMenu(eMenuMode); m_eMenuMode = eMenuMode; } void CHUD::SetButtonListener(int i, IEventListener::Callback pfnCallback) { if (pfnCallback) { m_apButtons[i]->SetClickedListener(this, pfnCallback); m_apButtons[i]->SetEnabled(true); m_apButtons[i]->SetAlpha(1.0f); } else { m_apButtons[i]->SetClickedListener(NULL, NULL); m_apButtons[i]->SetEnabled(false); m_apButtons[i]->SetAlpha(0.5f); } } void CHUD::SetButtonTexture(int i, const tstring& sArea) { SetButtonSheetTexture(m_apButtons[i], &m_ButtonSheet, sArea); } void CHUD::SetButtonColor(int i, Color clrButton) { m_apButtons[i]->SetButtonColor(clrButton); } void CHUD::SetButtonInfo(int iButton, const tstring& pszInfo) { m_aszButtonInfos[iButton] = pszInfo; } void CHUD::SetButtonTooltip(int iButton, const tstring& sTip) { m_apButtons[iButton]->SetTooltip(sTip); } void CHUD::ButtonCallback(int iButton) { if (m_apButtons[iButton]->GetClickedListener()) m_apButtons[iButton]->GetClickedListenerCallback()(m_apButtons[iButton]->GetClickedListener(), ""); } void CHUD::GameStart() { DigitanksGame()->SetControlMode(MODE_NONE); ClearTurnInfo(); } void CHUD::GameOver(bool bPlayerWon) { DigitanksWindow()->GameOver(bPlayerWon); } void CHUD::NewCurrentTeam() { m_bAllActionItemsHandled = false; DigitanksGame()->SetControlMode(MODE_NONE); UpdateTurnButton(); UpdateTeamInfo(); if (DigitanksGame()->GetCurrentPlayer() == DigitanksGame()->GetCurrentLocalDigitanksPlayer()) m_pPressEnter->SetText("Press <ENTER> to end your turn..."); else m_pPressEnter->SetText("Other players are taking their turns..."); if (DigitanksGame()->IsTeamControlledByMe(DigitanksGame()->GetCurrentPlayer())) m_flTurnInfoLerpGoal = 1; else m_flTurnInfoLerpGoal = 0; if (DigitanksGame()->IsTeamControlledByMe(DigitanksGame()->GetCurrentPlayer())) { // Don't open the research window on the first turn, give the player a chance to see the game grid first. if (DigitanksGame()->GetTurn() >= 1 && DigitanksGame()->GetUpdateGrid() && !DigitanksGame()->GetCurrentPlayer()->GetUpdateDownloading()) { bool bShouldOpen = false; for (size_t x = 0; x < UPDATE_GRID_SIZE; x++) { for (size_t y = 0; y < UPDATE_GRID_SIZE; y++) { if (DigitanksGame()->GetUpdateGrid()->m_aUpdates[x][y].m_eUpdateClass != UPDATECLASS_EMPTY && !DigitanksGame()->GetCurrentPlayer()->HasDownloadedUpdate(x, y)) { bShouldOpen = true; break; } } if (bShouldOpen) break; } m_bUpdatesBlinking = bShouldOpen; // If we've got to the third turn and the player isn't downloading anything, pop it up so he knows it's there. if (DigitanksGame()->GetTurn() == 3 && bShouldOpen) { m_pUpdatesPanel->SetVisible(true); DigitanksGame()->SetControlMode(MODE_NONE); m_bUpdatesBlinking = false; } } if (DigitanksWindow()->GetInstructor()->GetActive()) m_bUpdatesBlinking = false; m_pDemoNotice->SetText(""); // If we have local hotseat multiplayer, update for the new team. m_pSceneTree->BuildTree(); if (DigitanksGame()->GetPlayer(0) == DigitanksGame()->GetCurrentPlayer() && DigitanksGame()->GetTurn() == 0) { // Don't show for the first team on the first turn, show fight instead. } else DigitanksWindow()->GetHUD()->ShowNewTurnSign(); } UpdateScoreboard(); if (DigitanksGame()->IsTeamControlledByMe(DigitanksGame()->GetCurrentPlayer())) { bool bShow = true; // Don't show the action items until we have a CPU because we have the story and the tutorials to think about first. if (DigitanksGame()->GetGameType() == GAMETYPE_STANDARD && !DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) bShow = false; if (m_pUpdatesPanel->IsVisible()) bShow = false; if (bShow) ShowFirstActionItem(); } if (GameNetwork()->IsConnected() && DigitanksGame()->IsTeamControlledByMe(DigitanksGame()->GetCurrentPlayer())) CSoundLibrary::PlaySound(NULL, _T("sound/lesson-learned.wav")); // No time to make a new sound. CRootPanel::Get()->Layout(); } void CHUD::NewCurrentSelection() { UpdateTurnButton(); UpdateInfo(); SetupMenu(MENUMODE_MAIN); ShowActionItem(DigitanksGame()->GetPrimarySelection()); if (m_pWeaponPanel->IsVisible()) m_pWeaponPanel->SetVisible(false); if (DigitanksGame()->GetPrimarySelection()) { Vector vecTarget = DigitanksGame()->GetPrimarySelection()->GetGlobalOrigin(); EAngle angCamera = DigitanksGame()->GetOverheadCamera()->GetAngles(); float flDistance = DigitanksGame()->GetOverheadCamera()->GetDistance(); int iRotations = 0; while (iRotations++ < 4) { Vector vecCamera = AngleVector(angCamera) * flDistance + vecTarget; Vector vecHit; CBaseEntity* pHit = nullptr; DigitanksGame()->TraceLine(vecCamera, vecTarget, vecHit, &pHit); if (pHit == DigitanksGame()->GetPrimarySelection()) break; angCamera.y += 90; } DigitanksGame()->GetOverheadCamera()->SetAngle(angCamera); } } void CHUD::ShowFirstActionItem() { m_bAllActionItemsHandled = false; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems()) { m_iCurrentActionItem = -1; ShowNextActionItem(); } else { m_pActionItem->SetText(""); m_bAllActionItemsHandled = true; m_flActionItemsLerpGoal = 0; } } void CHUD::ShowNextActionItem() { if (m_bAllActionItemsHandled) return; size_t iOriginalActionItem = m_iCurrentActionItem; do { m_iCurrentActionItem = (m_iCurrentActionItem+1)%DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems(); if (m_iCurrentActionItem == iOriginalActionItem) { // We're done! m_bAllActionItemsHandled = true; m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; } // Bit of a hack. If m_iCurrentActionItem was -1 (or ~0 unsigned) then it'll now be 0. // Once it loops back around to 0 again the second time we'll consider it done. if (iOriginalActionItem == -1) iOriginalActionItem = 0; const actionitem_t* pItem = DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(m_iCurrentActionItem); if (pItem->eActionType == ACTIONTYPE_DOWNLOADCOMPLETE && DigitanksGame()->GetCurrentPlayer()->GetUpdateDownloading()) { DigitanksGame()->GetCurrentLocalDigitanksPlayer()->HandledActionItem(ACTIONTYPE_DOWNLOADCOMPLETE); UpdateTurnButton(); } if (pItem->bHandled) continue; // Only perform this check with tanks. Structures always return false for NeedsOrders() CEntityHandle<CDigitank> hDigitank(pItem->iUnit); if (hDigitank != NULL && !hDigitank->NeedsOrders()) { // If must have been handled already. DigitanksGame()->GetCurrentLocalDigitanksPlayer()->HandledActionItem(hDigitank); UpdateTurnButton(); continue; } ShowActionItem(m_iCurrentActionItem); return; } while (true); } void CHUD::ShowActionItem(CSelectable* pSelectable) { if (m_bAllActionItemsHandled) return; CDigitanksPlayer* pLocalPlayer = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); if (!pLocalPlayer) return; if (pSelectable) { for (size_t i = 0; i < pLocalPlayer->GetNumActionItems(); i++) { if (pLocalPlayer->GetActionItem(i)->iUnit == pSelectable->GetHandle()) { if (i == m_iCurrentActionItem) return; m_iCurrentActionItem = i; ShowActionItem(m_iCurrentActionItem); return; } } } // There is no action item for the current unit. If the current action item has no unit, don't clobber it just to show the "press next" message. if (m_iCurrentActionItem >= 0 && m_iCurrentActionItem < pLocalPlayer->GetNumActionItems() && pLocalPlayer->GetActionItem(m_iCurrentActionItem)->iUnit == ~0) return; ShowActionItem(~0); } void CHUD::ShowActionItem(actiontype_t eActionItem) { if (m_bAllActionItemsHandled) return; for (size_t i = 0; i < DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems(); i++) { if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(i)->eActionType == eActionItem) { if (i == m_iCurrentActionItem) return; m_iCurrentActionItem = i; ShowActionItem(m_iCurrentActionItem); return; } } } void CHUD::ShowActionItem(size_t iActionItem) { if (m_bAllActionItemsHandled) return; if (DigitanksGame()->GetGameType() != GAMETYPE_STANDARD) return; if (iActionItem >= DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems()) { m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; } const actionitem_t* pItem = DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(iActionItem); // Some action items are handled just by looking at them. if (pItem->eActionType == ACTIONTYPE_WELCOME || pItem->eActionType == ACTIONTYPE_CONTROLS || pItem->eActionType == ACTIONTYPE_NEWSTRUCTURE || pItem->eActionType == ACTIONTYPE_AUTOMOVEENEMY || pItem->eActionType == ACTIONTYPE_UPGRADE || pItem->eActionType == ACTIONTYPE_UNITREADY || pItem->eActionType == ACTIONTYPE_FORTIFIEDENEMY) { DigitanksGame()->GetCurrentLocalDigitanksPlayer()->HandledActionItem(iActionItem); UpdateTurnButton(); } switch (pItem->eActionType) { case ACTIONTYPE_WELCOME: m_pActionItem->SetText( "WELCOME TO DIGITANKS\n \n" "On the right is a list of tasks for you for each turn.\n \n" "Click an icon on the right to view that task. Tasks that are blinking need handling.\n \n" "When you're done, press the 'End Turn' button to continue.\n"); break; case ACTIONTYPE_CONTROLS: m_pActionItem->SetText( "QUICK CONTROLS\n \n" "Rotate view - Drag right mouse button\n" "Move view - Hold space, move mouse\n" "Zoom - Scrollwheel or pgup/pgdn\n"); break; case ACTIONTYPE_NEWSTRUCTURE: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; case ACTIONTYPE_UNITORDERS: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; case ACTIONTYPE_UNITAUTOMOVE: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; case ACTIONTYPE_AUTOMOVECANCELED: m_pActionItem->SetText( "UNIT AUTO-MOVE INTERRUPTED\n \n" "This unit's auto-move has been canceled, due to it taking damage from enemy fire. Please assign it new orders.\n"); break; case ACTIONTYPE_AUTOMOVEENEMY: m_pActionItem->SetText( "UNIT AUTO-MOVE THREAT\n \n" "This unit is auto-moving to a new location, but an enemy is visible. You may wish to cancel this auto move.\n"); break; case ACTIONTYPE_UNITDAMAGED: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; case ACTIONTYPE_FORTIFIEDENEMY: m_pActionItem->SetText( "ENEMY SIGHTED\n \n" "An enemy has been sighted in range of this fortified unit. Strike while the iron is hot.\n"); break; case ACTIONTYPE_UPGRADE: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; case ACTIONTYPE_UNITREADY: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; return; case ACTIONTYPE_DOWNLOADCOMPLETE: m_pActionItem->SetText(""); m_flActionItemsLerpGoal = 0; OpenUpdatesCallback(""); return; case ACTIONTYPE_DOWNLOADUPDATES: m_pActionItem->SetText( "DOWNLOAD UPDATES\n \n" "You can download updates for your structures. Press the 'Download' button at the top of the screen to choose an update.\n"); break; } // Just in case it was turned off because of the tutorials. if (pItem->eActionType == ACTIONTYPE_DOWNLOADUPDATES) m_bUpdatesBlinking = true; m_flActionItemsLerpGoal = 1; } void CHUD::OnAddNewActionItem() { m_bAllActionItemsHandled = false; } void CHUD::ShowTankSelectionMedal() { m_flSelectorMedalStart = GameServer()->GetGameTime(); CSoundLibrary::PlaySound(NULL, _T("sound/lesson-learned.wav")); } void CHUD::OnTakeShieldDamage(CDigitank* pVictim, CBaseEntity* pAttacker, CBaseEntity* pInflictor, float flDamage, bool bDirectHit, bool bShieldOnly) { CProjectile* pProjectile = dynamic_cast<CProjectile*>(pInflictor); if (pProjectile && !pProjectile->SendsNotifications()) return; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() == NULL) return; if (pVictim && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetVisibilityAtPoint(pVictim->GetGlobalOrigin()) < 0.1f) return; // Cleans itself up. new CDamageIndicator(pVictim, flDamage, true); if (pVictim && !pVictim->IsAlive() && bDirectHit && flDamage > 0) new CHitIndicator(pVictim, _T("OVERKILL!")); } void CHUD::OnTakeDamage(CBaseEntity* pVictim, CBaseEntity* pAttacker, CBaseEntity* pInflictor, float flDamage, bool bDirectHit, bool bKilled) { CProjectile* pProjectile = dynamic_cast<CProjectile*>(pInflictor); if (pProjectile && !pProjectile->SendsNotifications()) return; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() == NULL) return; if (pVictim && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetVisibilityAtPoint(pVictim->GetGlobalOrigin()) < 0.1f) return; // Cleans itself up. new CDamageIndicator(pVictim, flDamage, false); if ((pVictim && pVictim->IsAlive() || bKilled) && bDirectHit && flDamage > 0) new CHitIndicator(pVictim, _T("DIRECT HIT!")); } void CHUD::OnDisabled(CBaseEntity* pVictim, CBaseEntity* pAttacker, CBaseEntity* pInflictor) { CProjectile* pProjectile = dynamic_cast<CProjectile*>(pInflictor); if (pProjectile && !pProjectile->SendsNotifications()) return; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() == NULL) return; if (pVictim && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetVisibilityAtPoint(pVictim->GetGlobalOrigin()) < 0.1f) return; if (pVictim && pVictim->IsAlive()) { if (dynamic_cast<CDigitank*>(pVictim)) new CHitIndicator(pVictim, _T("DISABLED!")); else new CHitIndicator(pVictim, _T("DISCONNECTED!")); } } void CHUD::OnMiss(CBaseEntity* pVictim, CBaseEntity* pAttacker, CBaseEntity* pInflictor) { if (pVictim == pAttacker) return; CProjectile* pProjectile = dynamic_cast<CProjectile*>(pInflictor); if (pProjectile && !pProjectile->SendsNotifications()) return; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() == NULL) return; if (pVictim && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetVisibilityAtPoint(pVictim->GetGlobalOrigin()) < 0.1f) return; if (pVictim && pVictim->IsAlive()) new CHitIndicator(pVictim, _T("MISS!")); } void CHUD::OnCritical(CBaseEntity* pVictim, CBaseEntity* pAttacker, CBaseEntity* pInflictor) { CProjectile* pProjectile = dynamic_cast<CProjectile*>(pInflictor); if (pProjectile && !pProjectile->SendsNotifications()) return; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() == NULL) return; if (pVictim && DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetVisibilityAtPoint(pVictim->GetGlobalOrigin()) < 0.1f) return; if (pVictim) new CHitIndicator(pVictim, _T("CRITICAL HIT!")); } void CHUD::OnAddUnitToTeam(CDigitanksPlayer* pTeam, CBaseEntity* pEntity) { m_pSceneTree->OnAddUnitToTeam(pTeam, pEntity); } void CHUD::OnRemoveUnitFromTeam(CDigitanksPlayer* pTeam, CBaseEntity* pEntity) { m_pSceneTree->OnRemoveUnitFromTeam(pTeam, pEntity); } void CHUD::TankSpeak(class CBaseEntity* pTank, const tstring& sSpeech) { CDigitank* pDigitank = dynamic_cast<CDigitank*>(pTank); if (pDigitank && pDigitank->GetVisibility() == 0) return; // Cleans itself up. new CSpeechBubble(pTank, sSpeech); } void CHUD::ClearTurnInfo() { m_pTurnInfo->SetText(""); } void CHUD::SetHUDActive(bool bActive) { m_bHUDActive = bActive; SetupMenu(m_eMenuMode); if (!bActive) DigitanksGame()->SetControlMode(MODE_NONE); } bool CHUD::IsVisible() { if (!GameServer()) return false; if (GameServer()->IsLoading()) return false; if (!DigitanksGame()) return false; if (DigitanksGame()->GetGameType() == GAMETYPE_MENU) return false; return BaseClass::IsVisible(); } void CHUD::ShowButtonInfo(int iButton) { if (iButton < 0 || iButton >= NUM_BUTTONS) return; m_pButtonInfo->SetText(m_aszButtonInfos[iButton].c_str()); m_pButtonInfo->SetSize(m_pButtonInfo->GetWidth(), 9999); m_pButtonInfo->SetSize(m_pButtonInfo->GetWidth(), (int)m_pButtonInfo->GetTextHeight()); int iWidth = RootPanel()->GetWidth(); int iHeight = RootPanel()->GetHeight(); m_pButtonInfo->SetPos(iWidth/2 + 720/2 - m_pButtonInfo->GetWidth() - 50, iHeight - 160 - m_pButtonInfo->GetHeight()); } void CHUD::HideButtonInfo() { m_pButtonInfo->SetText(""); } bool CHUD::IsButtonInfoVisible() { return m_pButtonInfo->GetText().length() > 0; } bool CHUD::IsUpdatesPanelOpen() { if (!m_pUpdatesPanel) return false; return m_pUpdatesPanel->IsVisible(); } void CHUD::SlideUpdateIcon(int x, int y) { m_iUpdateIconSlideStartX = x; m_iUpdateIconSlideStartY = y; m_flUpdateIconSlide = GameServer()->GetGameTime(); } void ActionSignCallback(CCommand* pCommand, tvector<tstring>& asTokens, const tstring& sCommand) { if (asTokens.size() < 2) return; if (asTokens[1] == _T("fight")) DigitanksWindow()->GetHUD()->ShowFightSign(); else if (asTokens[1] == _T("showdown")) DigitanksWindow()->GetHUD()->ShowShowdownSign(); else if (asTokens[1] == _T("newturn")) DigitanksWindow()->GetHUD()->ShowNewTurnSign(); } CCommand actionsign("actionsign", ActionSignCallback); void CHUD::ShowFightSign() { m_eActionSign = ACTIONSIGN_FIGHT; m_flActionSignStart = GameServer()->GetGameTime(); CSoundLibrary::PlaySound(NULL, _T("sound/actionsign.wav")); } void CHUD::ShowShowdownSign() { m_eActionSign = ACTIONSIGN_SHOWDOWN; m_flActionSignStart = GameServer()->GetGameTime(); CSoundLibrary::PlaySound(NULL, _T("sound/actionsign.wav")); } void CHUD::ShowNewTurnSign() { m_eActionSign = ACTIONSIGN_NEWTURN; m_flActionSignStart = GameServer()->GetGameTime(); CSoundLibrary::PlaySound(NULL, _T("sound/actionsign.wav")); } void PowerupNotifyCallback(CCommand* pCommand, tvector<tstring>& asTokens, const tstring& sCommand) { if (!DigitanksGame()->GetCurrentLocalDigitanksPlayer()) return; DigitanksWindow()->GetHUD()->AddPowerupNotification(DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetTank(0), POWERUP_BONUS); } CCommand powerup_notify("powerup_notify", PowerupNotifyCallback); void CHUD::AddPowerupNotification(const CDigitanksEntity* pEntity, powerup_type_t ePowerup) { powerup_notification_t* pNewNotification = NULL; for (size_t i = 0; i < m_aPowerupNotifications.size(); i++) { powerup_notification_t* pNotification = &m_aPowerupNotifications[i]; if (pNotification->bActive) continue; pNewNotification = pNotification; break; } if (!pNewNotification) pNewNotification = &m_aPowerupNotifications.push_back(); pNewNotification->bActive = true; pNewNotification->ePowerupType = ePowerup; pNewNotification->flTime = GameServer()->GetGameTime(); pNewNotification->hEntity = pEntity; } void CHUD::ShowFileRescue(const tstring& sTexture) { m_sFileRescueTexture = sTexture; m_flFileRescueStart = GameServer()->GetGameTime(); CSoundLibrary::PlaySound(NULL, _T("lesson-learned.wav")); // No time to make a new sound. } void CHUD::CloseWeaponPanel() { m_pWeaponPanel->SetVisible(false); } FRect CHUD::GetButtonDimensions(size_t i) { FRect r; m_apButtons[i]->GetAbsDimensions(r.x, r.y, r.w, r.h); return r; } void CHUD::ChooseActionItemCallback(const tstring& sArgs) { size_t iActionItem = ~0; int mx, my; CRootPanel::GetFullscreenMousePos(mx, my); // Bit of a hack since we don't know what button was pressed we have to look for it. for (size_t i = 0; i < m_apActionItemButtons.size(); i++) { float x, y, w, h; m_apActionItemButtons[i]->GetAbsDimensions(x, y, w, h); if (mx >= x && my >= y && mx < x + w && my < y + h) { iActionItem = i; break; } } if (iActionItem == ~0) return; ShowActionItem(iActionItem); if (iActionItem < DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems()) { const actionitem_t* pItem = DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(iActionItem); CEntityHandle<CSelectable> hSelection(pItem->iUnit); if (hSelection != NULL) { DigitanksGame()->GetCurrentPlayer()->SetPrimarySelection(hSelection); DigitanksGame()->GetOverheadCamera()->SetTarget(hSelection->GetGlobalOrigin()); if (DigitanksGame()->GetOverheadCamera()->GetDistance() > 250) DigitanksGame()->GetOverheadCamera()->SetDistance(250); } } m_flSmallActionItemLerpGoal = 0; } void CHUD::ShowSmallActionItemCallback(const tstring& sArgs) { m_iCurrentSmallActionItem = ~0; m_flSmallActionItemLerpGoal = 0; int mx, my; CRootPanel::GetFullscreenMousePos(mx, my); // Bit of a hack since we don't know what button was pressed we have to look for it. for (size_t i = 0; i < m_apActionItemButtons.size(); i++) { float x, y, w, h; m_apActionItemButtons[i]->GetAbsDimensions(x, y, w, h); if (mx >= x && my >= y && mx < x + w && my < y + h) { m_iCurrentSmallActionItem = i; break; } } if (m_iCurrentSmallActionItem == ~0) return; m_flSmallActionItemLerpGoal = 1; if (!DigitanksGame()->GetCurrentLocalDigitanksPlayer()) return; if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetNumActionItems() == 0) return; const actionitem_t* pItem = DigitanksGame()->GetCurrentLocalDigitanksPlayer()->GetActionItem(m_iCurrentSmallActionItem); switch (pItem->eActionType) { case ACTIONTYPE_WELCOME: m_sSmallActionItem = _T("WELCOME TO DIGITANKS"); break; case ACTIONTYPE_CONTROLS: m_sSmallActionItem = _T("QUICK CONTROLS"); break; case ACTIONTYPE_NEWSTRUCTURE: m_sSmallActionItem = _T("STRUCTURE COMPLETED"); break; case ACTIONTYPE_UNITORDERS: m_sSmallActionItem = _T("ORDERS NEEDED"); break; case ACTIONTYPE_UNITAUTOMOVE: m_sSmallActionItem = _T("AUTO-MOVE COMPLETED"); break; case ACTIONTYPE_AUTOMOVECANCELED: m_sSmallActionItem = _T("AUTO-MOVE INTERRUPTED"); break; case ACTIONTYPE_AUTOMOVEENEMY: m_sSmallActionItem = _T("AUTO-MOVE THREAT"); break; case ACTIONTYPE_UNITDAMAGED: m_sSmallActionItem = _T("UNIT DAMAGED"); break; case ACTIONTYPE_FORTIFIEDENEMY: m_sSmallActionItem = _T("ENEMY IN RANGE"); break; case ACTIONTYPE_UPGRADE: m_sSmallActionItem = _T("UPRGADE COMPLETED"); break; case ACTIONTYPE_UNITREADY: m_sSmallActionItem = _T("UNIT COMPLETED"); break; case ACTIONTYPE_DOWNLOADCOMPLETE: m_sSmallActionItem = _T("DOWNLOAD COMPLETED"); break; case ACTIONTYPE_DOWNLOADUPDATES: m_sSmallActionItem = _T("DOWNLOAD UPDATES"); break; } } void CHUD::HideSmallActionItemCallback(const tstring& sArgs) { m_flSmallActionItemLerpGoal = 0; } void CHUD::CloseActionItemsCallback(const tstring& sArgs) { ShowActionItem(~0); } void CHUD::CursorInTurnButtonCallback(const tstring& sArgs) { if (!DigitanksGame()->GetCurrentPlayer()) return; for (size_t i = 0; i < DigitanksGame()->GetCurrentPlayer()->GetNumTanks(); i++) { CDigitank* pTank = DigitanksGame()->GetCurrentPlayer()->GetTank(i); if (!pTank) continue; if (pTank->NeedsOrders()) { m_flTurnWarningGoal = 1; return; } } m_flTurnWarningGoal = 0; } void CHUD::CursorOutTurnButtonCallback(const tstring& sArgs) { m_flTurnWarningGoal = 0; } void CHUD::ButtonCursorIn0Callback(const tstring& sArgs) { ShowButtonInfo(0); } void CHUD::ButtonCursorIn1Callback(const tstring& sArgs) { ShowButtonInfo(1); } void CHUD::ButtonCursorIn2Callback(const tstring& sArgs) { ShowButtonInfo(2); } void CHUD::ButtonCursorIn3Callback(const tstring& sArgs) { ShowButtonInfo(3); } void CHUD::ButtonCursorIn4Callback(const tstring& sArgs) { ShowButtonInfo(4); } void CHUD::ButtonCursorIn5Callback(const tstring& sArgs) { ShowButtonInfo(5); } void CHUD::ButtonCursorIn6Callback(const tstring& sArgs) { ShowButtonInfo(6); } void CHUD::ButtonCursorIn7Callback(const tstring& sArgs) { ShowButtonInfo(7); } void CHUD::ButtonCursorIn8Callback(const tstring& sArgs) { ShowButtonInfo(8); } void CHUD::ButtonCursorIn9Callback(const tstring& sArgs) { ShowButtonInfo(9); } void CHUD::ButtonCursorOutCallback(const tstring& sArgs) { HideButtonInfo(); } void CHUD::EndTurnCallback(const tstring& sArgs) { if (DigitanksGame()->GetCurrentLocalDigitanksPlayer() != DigitanksGame()->GetCurrentPlayer()) return; m_flActionItemsLerpGoal = 0; CSoundLibrary::PlaySound(NULL, _T("sound/turn.wav")); DigitanksGame()->EndTurn(); } void CHUD::OpenUpdatesCallback(const tstring& sArgs) { if (m_pUpdatesPanel) m_pUpdatesPanel->SetVisible(true); m_bUpdatesBlinking = false; DigitanksGame()->SetControlMode(MODE_NONE); } void CHUD::MoveCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (DigitanksGame()->GetControlMode() == MODE_MOVE) DigitanksGame()->SetControlMode(MODE_NONE); else DigitanksGame()->SetControlMode(MODE_MOVE); DigitanksWindow()->GetInstructor()->FinishedLesson("mission-1-move-mode"); DigitanksWindow()->SetContextualCommandsOverride(true); SetupMenu(); } void CHUD::CancelAutoMoveCallback(const tstring& sArgs) { if (!m_bHUDActive) return; DigitanksGame()->SetControlMode(MODE_NONE); for (size_t i = 0; i < DigitanksGame()->GetCurrentPlayer()->GetNumTanks(); i++) { if (DigitanksGame()->GetCurrentPlayer()->IsSelected(DigitanksGame()->GetCurrentPlayer()->GetTank(i))) DigitanksGame()->GetCurrentPlayer()->GetTank(i)->CancelGoalMovePosition(); } SetupMenu(); } void CHUD::TurnCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (DigitanksGame()->GetControlMode() == MODE_TURN) DigitanksGame()->SetControlMode(MODE_NONE); else DigitanksGame()->SetControlMode(MODE_TURN); DigitanksWindow()->SetContextualCommandsOverride(true); SetupMenu(); } void CHUD::AimCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (DigitanksGame()->GetControlMode() == MODE_AIM) DigitanksGame()->SetControlMode(MODE_NONE); else if (DigitanksGame()->GetPrimarySelectionTank()) { CDigitank* pTank = DigitanksGame()->GetPrimarySelectionTank(); if (pTank->GetCurrentWeapon() == PROJECTILE_AIRSTRIKE) { if (pTank->GetNumWeapons()) pTank->SetCurrentWeapon(pTank->GetWeapon(0)); else pTank->SetCurrentWeapon(WEAPON_NONE); } DigitanksGame()->SetControlMode(MODE_AIM); DigitanksGame()->SetAimTypeByWeapon(pTank->GetCurrentWeapon()); } DigitanksWindow()->SetContextualCommandsOverride(true); SetupMenu(); } void CHUD::FortifyCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()->GetPrimarySelectionTank()) return; DigitanksGame()->SetControlMode(MODE_NONE); for (size_t i = 0; i < DigitanksGame()->GetCurrentPlayer()->GetNumTanks(); i++) { if (DigitanksGame()->GetCurrentPlayer()->IsSelected(DigitanksGame()->GetCurrentPlayer()->GetTank(i))) { DigitanksGame()->GetCurrentPlayer()->GetTank(i)->Fortify(); DigitanksGame()->GetCurrentLocalDigitanksPlayer()->HandledActionItem(DigitanksGame()->GetCurrentPlayer()->GetTank(i)); } } SetupMenu(MENUMODE_MAIN); UpdateInfo(); } void CHUD::SentryCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()->GetPrimarySelectionTank()) return; DigitanksGame()->SetControlMode(MODE_NONE); for (size_t i = 0; i < DigitanksGame()->GetCurrentPlayer()->GetNumTanks(); i++) { if (DigitanksGame()->GetCurrentPlayer()->IsSelected(DigitanksGame()->GetCurrentPlayer()->GetTank(i))) { DigitanksGame()->GetCurrentPlayer()->GetTank(i)->Sentry(); DigitanksGame()->GetCurrentLocalDigitanksPlayer()->HandledActionItem(DigitanksGame()->GetCurrentPlayer()->GetTank(i)); } } SetupMenu(MENUMODE_MAIN); UpdateInfo(); } void CHUD::PromoteCallback(const tstring& sArgs) { if (!m_bHUDActive) return; SetupMenu(MENUMODE_PROMOTE); } void CHUD::PromoteAttackCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelectionTank()) return; CDigitank* pTank = DigitanksGame()->GetPrimarySelectionTank(); pTank->PromoteAttack(); SetupMenu(MENUMODE_MAIN); UpdateInfo(); // DigitanksWindow()->GetInstructor()->FinishedLesson(CInstructor::TUTORIAL_UPGRADE); } void CHUD::PromoteDefenseCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelectionTank()) return; CDigitank* pTank = DigitanksGame()->GetPrimarySelectionTank(); pTank->PromoteDefense(); SetupMenu(MENUMODE_MAIN); UpdateInfo(); // DigitanksWindow()->GetInstructor()->FinishedLesson(CInstructor::TUTORIAL_UPGRADE); } void CHUD::PromoteMovementCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelectionTank()) return; CDigitank* pTank = DigitanksGame()->GetPrimarySelectionTank(); pTank->PromoteMovement(); SetupMenu(MENUMODE_MAIN); UpdateInfo(); // DigitanksWindow()->GetInstructor()->FinishedLesson(CInstructor::TUTORIAL_UPGRADE); } void CHUD::FireSpecialCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (DigitanksGame()->GetControlMode() == MODE_AIM) DigitanksGame()->SetControlMode(MODE_NONE); else if (DigitanksGame()->GetCurrentPlayer() && DigitanksGame()->GetCurrentPlayer()->GetPrimarySelectionTank()) { DigitanksGame()->GetCurrentPlayer()->GetPrimarySelectionTank()->SetCurrentWeapon(PROJECTILE_AIRSTRIKE); DigitanksGame()->SetControlMode(MODE_AIM); DigitanksGame()->SetAimTypeByWeapon(PROJECTILE_AIRSTRIKE); } SetupMenu(); } void CHUD::BuildMiniBufferCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_MINIBUFFER); DigitanksGame()->SetControlMode(MODE_BUILD); DigitanksWindow()->GetInstructor()->FinishedLesson("strategy-buildbuffer", true); SetupMenu(); } void CHUD::BuildBufferCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_BUFFER); DigitanksGame()->SetControlMode(MODE_BUILD); SetupMenu(); } void CHUD::BuildBatteryCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_BATTERY); DigitanksGame()->SetControlMode(MODE_BUILD); DigitanksWindow()->GetInstructor()->FinishedLesson("strategy-buildbuffer", true); SetupMenu(); } void CHUD::BuildPSUCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_PSU); DigitanksGame()->SetControlMode(MODE_BUILD); SetupMenu(); } void CHUD::BuildLoaderCallback(const tstring& sArgs) { if (!m_bHUDActive) return; SetupMenu(MENUMODE_LOADERS); } void CHUD::BuildInfantryLoaderCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_INFANTRYLOADER); DigitanksGame()->SetControlMode(MODE_BUILD); SetupMenu(); } void CHUD::BuildTankLoaderCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_TANKLOADER); DigitanksGame()->SetControlMode(MODE_BUILD); SetupMenu(); } void CHUD::BuildArtilleryLoaderCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_ARTILLERYLOADER); DigitanksGame()->SetControlMode(MODE_BUILD); SetupMenu(); } void CHUD::CancelBuildCallback(const tstring& sArgs) { DigitanksGame()->SetControlMode(MODE_NONE); SetupMenu(); } void CHUD::BuildUnitCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelectionStructure()) return; CStructure* pStructure = DigitanksGame()->GetPrimarySelectionStructure(); CLoader* pLoader = dynamic_cast<CLoader*>(pStructure); if (!pLoader) return; pLoader->BeginProduction(); SetupMenu(); UpdateInfo(); UpdateTeamInfo(); } void CHUD::BuildScoutCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->BeginRogueProduction(); SetupMenu(); UpdateInfo(); UpdateTeamInfo(); } void CHUD::BuildTurretCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU()) return; CCPU* pCPU = DigitanksGame()->GetCurrentPlayer()->GetPrimaryCPU(); if (!pCPU) return; pCPU->SetPreviewStructure(STRUCTURE_FIREWALL); DigitanksGame()->SetControlMode(MODE_BUILD); SetupMenu(); } void CHUD::BeginUpgradeCallback(const tstring& sArgs) { if (!m_bHUDActive) return; if (!DigitanksGame()) return; if (!DigitanksGame()->GetPrimarySelectionStructure()) return; CStructure* pStructure = DigitanksGame()->GetPrimarySelectionStructure(); pStructure->BeginUpgrade(); DigitanksGame()->SetControlMode(MODE_NONE); SetupMenu(); UpdateInfo(); UpdateTeamInfo(); } void CHUD::CloakCallback(const tstring& sArgs) { CDigitank* pDigitank = DigitanksGame()->GetPrimarySelectionTank(); if (!pDigitank) return; if (!pDigitank->HasCloak()) return; if (pDigitank->IsCloaked()) pDigitank->Uncloak(); else pDigitank->Cloak(); } void CHUD::ChooseWeaponCallback(const tstring& sArgs) { if (!m_bHUDActive) return; DigitanksGame()->SetControlMode(MODE_NONE); if (m_pWeaponPanel->IsVisible()) m_pWeaponPanel->SetVisible(false); else { m_pWeaponPanel->Layout(); m_pWeaponPanel->SetVisible(true); DigitanksWindow()->GetInstructor()->FinishedLesson("artillery-aim", true); } } void CHUD::GoToMainCallback(const tstring& sArgs) { SetupMenu(MENUMODE_MAIN); } void CHUD::ShowPowerInfoCallback(const tstring& sArgs) { m_pTeamInfo->SetText(""); if (DigitanksGame()->GetGameType() != GAMETYPE_STANDARD) return; CDigitanksPlayer* pCurrentTeam = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); if (!pCurrentTeam) return; m_pTeamInfo->AppendText("POWER INFO\n \n"); m_pTeamInfo->AppendText(tsprintf(tstring("Power stored: %.1f\n"), pCurrentTeam->GetPower())); m_pTeamInfo->AppendText(tsprintf(tstring("Power per turn: +%.1f\n \n"), pCurrentTeam->GetPowerPerTurn())); for (size_t i = 0; i < pCurrentTeam->GetNumUnits(); i++) { const CBaseEntity* pEntity = pCurrentTeam->GetUnit(i); if (!pEntity) continue; const CStructure* pStructure = dynamic_cast<const CStructure*>(pEntity); if (!pStructure) continue; if (pStructure->Power() > 0) m_pTeamInfo->AppendText(tsprintf(pStructure->GetEntityName() + _T(": +%.1f\n"), pStructure->Power())); const CCollector* pCollector = dynamic_cast<const CCollector*>(pEntity); if (!pCollector) continue; if (pCollector->IsConstructing()) continue; float flEfficiency; if (!pCollector->GetSupplier() || !pCollector->GetSupplyLine()) flEfficiency = 0; else flEfficiency = pCollector->GetSupplier()->GetChildEfficiency() * pCollector->GetSupplyLine()->GetIntegrity(); m_pTeamInfo->AppendText(tsprintf(pCollector->GetEntityName() + _T(": +%.1f (%d%%)\n"), pCollector->GetPowerProduced(), (int)(flEfficiency * 100))); } LayoutTeamInfo(); } void CHUD::ShowFleetInfoCallback(const tstring& sArgs) { m_pTeamInfo->SetText(""); if (DigitanksGame()->GetGameType() != GAMETYPE_STANDARD) return; CDigitanksPlayer* pCurrentTeam = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); if (!pCurrentTeam) return; m_pTeamInfo->AppendText("FLEET INFO\n \n"); m_pTeamInfo->AppendText(tsprintf(tstring("Fleet points available: %d\n"), pCurrentTeam->GetTotalFleetPoints())); m_pTeamInfo->AppendText(tsprintf(tstring("Fleet points in use: %d\n \n"), pCurrentTeam->GetUsedFleetPoints())); int iScouts = 0; int iTanks = 0; int iArtillery = 0; int iInfantry = 0; m_pTeamInfo->AppendText(_T("Suppliers:\n")); for (size_t i = 0; i < pCurrentTeam->GetNumUnits(); i++) { const CBaseEntity* pEntity = pCurrentTeam->GetUnit(i); if (!pEntity) continue; const CDigitanksEntity* pDTEnt = dynamic_cast<const CDigitanksEntity*>(pEntity); if (pDTEnt) { if (pDTEnt->GetUnitType() == UNIT_SCOUT) iScouts++; else if (pDTEnt->GetUnitType() == UNIT_TANK) iTanks++; else if (pDTEnt->GetUnitType() == UNIT_INFANTRY) iInfantry++; else if (pDTEnt->GetUnitType() == UNIT_ARTILLERY) iArtillery++; } const CStructure* pStructure = dynamic_cast<const CStructure*>(pEntity); if (!pStructure) continue; if (pStructure->IsConstructing()) continue; if (pStructure->FleetPoints() > 0) m_pTeamInfo->AppendText(tsprintf(pStructure->GetEntityName() + _T(": +%d\n"), pStructure->FleetPoints())); } m_pTeamInfo->AppendText(_T(" \nFleet:\n")); if (iScouts) m_pTeamInfo->AppendText(tsprintf(tstring("%d Rogues (%d): %d\n"), iScouts, CScout::ScoutFleetPoints(), iScouts*CScout::ScoutFleetPoints())); if (iInfantry) m_pTeamInfo->AppendText(tsprintf(tstring("%d Resistors (%d): %d\n"), iInfantry, CMechInfantry::InfantryFleetPoints(), iInfantry*CMechInfantry::InfantryFleetPoints())); if (iTanks) m_pTeamInfo->AppendText(tsprintf(tstring("%d Digitanks (%d): %d\n"), iTanks, CMainBattleTank::MainTankFleetPoints(), iTanks*CMainBattleTank::MainTankFleetPoints())); if (iArtillery) m_pTeamInfo->AppendText(tsprintf(tstring("%d Artillery (%d): %d\n"), iArtillery, CArtillery::ArtilleryFleetPoints(), iArtillery*CArtillery::ArtilleryFleetPoints())); LayoutTeamInfo(); } void CHUD::ShowBandwidthInfoCallback(const tstring& sArgs) { m_pTeamInfo->SetText(""); if (DigitanksGame()->GetGameType() != GAMETYPE_STANDARD) return; CDigitanksPlayer* pCurrentTeam = DigitanksGame()->GetCurrentLocalDigitanksPlayer(); if (!pCurrentTeam) return; m_pTeamInfo->AppendText("BANDWIDTH INFO\n \n"); if (pCurrentTeam->GetUpdateDownloading()) { m_pTeamInfo->AppendText(tsprintf(tstring("Downloading: %s\n"), pCurrentTeam->GetUpdateDownloading()->GetName().c_str())); m_pTeamInfo->AppendText(tsprintf(tstring("Progress: %.1f/%dmb (%d turns)\n"), pCurrentTeam->GetUpdateDownloaded(), (int)pCurrentTeam->GetUpdateSize(), pCurrentTeam->GetTurnsToDownload())); m_pTeamInfo->AppendText(tsprintf(tstring("Download rate: %.1fmb/turn\n \n"), pCurrentTeam->GetBandwidth())); } for (size_t i = 0; i < pCurrentTeam->GetNumUnits(); i++) { const CBaseEntity* pEntity = pCurrentTeam->GetUnit(i); if (!pEntity) continue; const CStructure* pStructure = dynamic_cast<const CStructure*>(pEntity); if (!pStructure) continue; if (pStructure->IsConstructing()) continue; if (pStructure->Bandwidth() > 0) m_pTeamInfo->AppendText(tsprintf(pStructure->GetEntityName() + _T(": +%.1fmb\n"), pStructure->Bandwidth())); } LayoutTeamInfo(); } void CHUD::HideTeamInfoCallback(const tstring& sArgs) { m_pTeamInfo->SetText(""); } void CHUD::FireTurretCallback(const tstring& sArgs) { CAutoTurret* pTurret = dynamic_cast<CAutoTurret*>(DigitanksGame()->GetPrimarySelection()); if (!pTurret) return; pTurret->Fire(); } void CHUD::LayoutTeamInfo() { if (m_pTeamInfo->GetText().length() == 0) return; m_pTeamInfo->ComputeLines(); m_pTeamInfo->SetSize(300, (int)m_pTeamInfo->GetTextHeight()); m_pTeamInfo->SetPos(GetWidth() - m_pTeamInfo->GetWidth() - 50, 50); } void CHUD::SetNeedsUpdate() { DigitanksWindow()->GetHUD()->m_bNeedsUpdate = true; } void CHUD::SetTeamMembersUpdated() { DigitanksWindow()->GetHUD()->m_pSceneTree->OnTeamMembersUpdated(); } CDamageIndicator::CDamageIndicator(CBaseEntity* pVictim, float flDamage, bool bShield) : CLabel(0, 0, 100, 100, _T("")) { m_hVictim = pVictim; m_flDamage = flDamage; m_bShield = bShield; m_flTime = GameServer()->GetGameTime(); if (pVictim) m_vecLastOrigin = pVictim->GetGlobalOrigin(); glgui::CRootPanel::Get()->AddControl(this, true); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(m_vecLastOrigin); if (bShield) vecScreen += Vector(10, 10, 0); SetPos((int)vecScreen.x, (int)vecScreen.y); if (m_bShield) SetTextColor(Color(255, 255, 255)); else if (flDamage < 0) SetTextColor(Color(0, 255, 0)); else SetTextColor(Color(255, 0, 0)); int iDamage = (int)flDamage; // Don't let it say 0 if (flDamage > 0 && iDamage < 1) iDamage = 1; if (flDamage < 0 && iDamage > -1) iDamage = -1; if (flDamage < 0.5f && flDamage > -0.1f) { m_flTime = 0; SetVisible(false); } char szDamage[100]; if (iDamage < 0) sprintf(szDamage, "+%d %s", -iDamage, bShield?"shield":"hull"); else sprintf(szDamage, "-%d", iDamage); SetText(szDamage); SetFont(_T("header"), 18); SetAlign(CLabel::TA_TOPLEFT); SetWrap(false); } void CDamageIndicator::Think() { double flFadeTime = 1.0f; if (GameServer()->GetGameTime() - m_flTime > flFadeTime) { GetParent().DowncastStatic<CPanel>()->RemoveControl(this); return; } if (m_hVictim != NULL) m_vecLastOrigin = m_hVictim->GetGlobalOrigin(); float flOffset = RemapVal(GameServer()->GetGameTime() - m_flTime, 0, flFadeTime, 10.0, 20); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(m_vecLastOrigin); if (m_bShield) vecScreen += Vector(10, 10, 0); SetPos((int)(vecScreen.x+flOffset), (int)(vecScreen.y-flOffset)); SetAlpha((float)RemapVal(GameServer()->GetGameTime() - m_flTime, 0, flFadeTime, 255.0, 0)); // Cull tanks behind the camera if (GameServer()->GetRenderer()->GetCameraVector().Dot((m_vecLastOrigin-GameServer()->GetCameraManager()->GetCameraPosition()).Normalized()) < 0) SetAlpha(0); BaseClass::Think(); } void CDamageIndicator::Paint(float x, float y, float w, float h) { if (m_bShield) { float iWidth = GetTextWidth(); float iHeight = GetTextHeight(); CRootPanel::PaintRect(x, y-iHeight/2, iWidth, iHeight, Color(0, 0, 0, GetAlpha()/2)); } BaseClass::Paint(x, y, w, h); } CHitIndicator::CHitIndicator(CBaseEntity* pVictim, tstring sMessage) : CLabel(0, 0, 200, 100, _T("")) { m_hVictim = pVictim; m_flTime = GameServer()->GetGameTime(); m_vecLastOrigin = pVictim->GetGlobalOrigin(); glgui::CRootPanel::Get()->AddControl(this, true); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(pVictim->GetGlobalOrigin()); vecScreen.x -= 20; vecScreen.y -= 20; SetPos((int)vecScreen.x, (int)vecScreen.y); SetTextColor(Color(255, 255, 255)); SetText(sMessage.c_str()); SetWrap(false); SetFont(_T("header"), 18); SetAlign(CLabel::TA_TOPLEFT); } void CHitIndicator::Think() { double flFadeTime = 1.0f; if (GameServer()->GetGameTime() - m_flTime > flFadeTime) { GetParent().DowncastStatic<CPanel>()->RemoveControl(this); return; } if (m_hVictim != NULL) m_vecLastOrigin = m_hVictim->GetGlobalOrigin(); float flOffset = RemapVal(GameServer()->GetGameTime() - m_flTime, 0, flFadeTime, 10.0, 20); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(m_vecLastOrigin); vecScreen.x -= 20; vecScreen.y -= 20; SetPos((int)(vecScreen.x+flOffset), (int)(vecScreen.y-flOffset)); SetAlpha((int)RemapVal(GameServer()->GetGameTime() - m_flTime, 0, flFadeTime, 255.0, 0)); // Cull tanks behind the camera if (GameServer()->GetRenderer()->GetCameraVector().Dot((m_vecLastOrigin-GameServer()->GetCameraManager()->GetCameraPosition()).Normalized()) < 0) SetAlpha(0); BaseClass::Think(); } void CHitIndicator::Paint(float x, float y, float w, float h) { float iWidth = GetTextWidth(); float iHeight = GetTextHeight(); CRootPanel::PaintRect(x, y-iHeight/2, iWidth, iHeight, Color(0, 0, 0, GetAlpha()/2)); BaseClass::Paint(x, y, w, h); } CSpeechBubble::CSpeechBubble(CBaseEntity* pSpeaker, tstring sSpeech) : CLabel(0, 0, 83*2/3, 47*2/3, _T("")) { m_hSpeaker = pSpeaker; m_flTime = GameServer()->GetGameTime(); m_vecLastOrigin = pSpeaker->GetGlobalOrigin(); if (pSpeaker) m_flRadius = pSpeaker->GetBoundingRadius(); else m_flRadius = 10; glgui::CRootPanel::Get()->AddControl(this, (DigitanksGame()->GetGameType() == GAMETYPE_MENU)?false:true); SetTextColor(Color(255, 255, 255)); SetText(sSpeech.c_str()); SetWrap(false); SetFont(_T("smileys"), 18); SetAlign(CLabel::TA_MIDDLECENTER); } void CSpeechBubble::Think() { double flFadeTime = 3.0f; if (!GameServer()) return; if (GameServer()->GetGameTime() - m_flTime > flFadeTime) { GetParent().DowncastStatic<CPanel>()->RemoveControl(this); return; } if (m_hSpeaker != NULL) m_vecLastOrigin = m_hSpeaker->GetGlobalOrigin(); Vector vecUp; GameServer()->GetRenderer()->GetCameraVectors(NULL, NULL, &vecUp); Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(m_vecLastOrigin); Vector vecTop = GameServer()->GetRenderer()->ScreenPosition(m_vecLastOrigin + vecUp*m_flRadius); float flWidth = (vecTop - vecScreen).Length()*2 + 10; vecScreen.x -= (flWidth/2 + 50); vecScreen.y -= flWidth; SetPos((int)(vecScreen.x), (int)(vecScreen.y)); SetAlpha((int)RemapValClamped(GameServer()->GetGameTime() - m_flTime, flFadeTime-1, flFadeTime, 255.0, 0)); // Cull tanks behind the camera if (GameServer()->GetRenderer()->GetCameraVector().Dot((m_vecLastOrigin-GameServer()->GetCameraManager()->GetCameraPosition()).Normalized()) < 0) SetAlpha(0); BaseClass::Think(); } void CSpeechBubble::Paint(float x, float y, float w, float h) { if (!GameServer()) return; if (DigitanksWindow()->GetHUD()->IsUpdatesPanelOpen()) return; do { CRenderingContext c(GameServer()->GetRenderer(), true); c.SetBlend(BLEND_ALPHA); CHUD::PaintHUDSheet("SpeechBubble", x, y, w, h, Color(255, 255, 255, GetAlpha())); } while (false); BaseClass::Paint(x, y, w, h); } CHowToPlayPanel::CHowToPlayPanel() : CPanel(0, 0, 100, 100) { m_pOpen = AddControl(new CLabel(0, 0, 100, 100, _T(""), _T("header"), 18)); m_bOpen = false; m_flGoalLerp = 0; m_flCurLerp = 0; m_pControls = AddControl(new CLabel(0, 0, 100, 100, _T(""), _T("text"), 13)); } void CHowToPlayPanel::Layout() { BaseClass::Layout(); if (IsOpen()) m_pOpen->SetText(_T("Click to close")); else m_pOpen->SetText(_T("How to play")); m_pOpen->SetSize(150, 50); m_pOpen->SetPos(0, 300); m_pOpen->SetAlign(CLabel::TA_MIDDLECENTER); m_pControls->SetSize(330, 250); m_pControls->SetPos(10, 30); m_pControls->SetAlign(CLabel::TA_TOPLEFT); tstring sTips; if (DigitanksGame()->GetGameType() == GAMETYPE_STANDARD) sTips = _T("TIPS:\n* Structures can only be built on your Network.\n* To create more Network, build Buffers.\n* To harvest more resources, build a Buffer near an Electronode and then build a Capacitor on top of the Electronode.\n* Use Resistors and Firewalls to defend your base and destroy the enemy CPUs to win.\n \n"); else sTips = _T("TIPS:\n* Tanks have a limited amount of movement energy per turn.\n* Each tank can fire once per turn.\n* When all tanks have moved or fired, press the 'End Turn' button to regain movement energy and attacks.\n \n"); m_pControls->SetText( tstring(_T("OBJECTIVE: ")) + DigitanksGame()->GetObjective() + _T("\n \n") + sTips + _T("CONTROLS:\n") _T("Scroll view: Hold spacebar\n") _T("Rotate view: Hold right click\n") _T("Zoom view: Scrollwheel or pgup/pgdn\n") _T("Select similar units: Double click\n") ); } void CHowToPlayPanel::Think() { BaseClass::Think(); SetVisible(!DigitanksGame()->IsFeatureDisabled(DISABLE_HOWTOPLAY)); m_flCurLerp = Approach(m_flGoalLerp, m_flCurLerp, GameServer()->GetFrameTime()*2); // m_pUpdatesButton->SetPos(iWidth/2 - 617/2 - 35, 0); int iX = 150; // Keep it to the left of the downloads button. Don't want to cover that up. if (iX > (GetParent()->GetWidth()/2 - 617/2 - 35) - 150 - 10) iX = (GetParent()->GetWidth()/2 - 617/2 - 35) - 150 - 10; SetPos(iX, (int)(RemapVal(Bias(m_flCurLerp, 0.6f), 0, 1, -300, 0))); SetSize((int)(RemapVal(Bias(m_flCurLerp, 0.6f), 0, 1, 150, 350)), 350); m_pOpen->SetSize((int)(RemapVal(Bias(m_flCurLerp, 0.6f), 0, 1, 150, 300)), 50); m_pControls->SetAlpha(m_flCurLerp); } void CHowToPlayPanel::Paint(float x, float y, float w, float h) { CRootPanel::PaintRect(x, y, w, h); BaseClass::Paint(x, y, w, h); } bool CHowToPlayPanel::IsOpen() { return m_bOpen; } void CHowToPlayPanel::Open() { m_bOpen = true; m_flGoalLerp = 1; Layout(); } void CHowToPlayPanel::Close() { m_bOpen = false; m_flGoalLerp = 0; Layout(); } bool CHowToPlayPanel::MousePressed(int code, int mx, int my) { if (IsOpen()) Close(); else Open(); return true; } bool CHowToPlayPanel::MouseReleased(int code, int mx, int my) { return true; } bool CMouseCapturePanel::MousePressed(int code, int mx, int my) { BaseClass::MousePressed(code, mx, my); return true; } bool CMouseCapturePanel::MouseReleased(int code, int mx, int my) { BaseClass::MouseReleased(code, mx, my); if (DigitanksGame()->GetCurrentLocalDigitanksPlayer()->IsMouseDragging()) return false; return true; }
29.923654
323
0.709949
[ "geometry", "vector" ]
62fb268d318f1a6dccf8e3d498c8ee2b64f7d1e3
2,879
cpp
C++
modules/task_3/chernyh_d_simpson/simpson.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/chernyh_d_simpson/simpson.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/chernyh_d_simpson/simpson.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
2
2022-03-31T17:48:22.000Z
2022-03-31T18:06:07.000Z
// Copyright 2022 Chernyh Daria #include <tbb/parallel_reduce.h> #include <iostream> #include <functional> #include <numeric> #include"../../../modules/task_3/chernyh_d_simpson/simpson.h" void SimpsonCalcul::operator() (const tbb::blocked_range<int>& r) { std::vector<double> x_left(dimension), x_right(dimension), x_mid(dimension); for (int i = r.begin(); i != r.end(); ++i) { for (size_t j = 0; j < dimension; j++) { x_left[j] = a[j] + i * weight[j]; x_right[j] = a[j] + (i + 1) * weight[j]; x_mid[j] = (x_left[j] + x_right[j]) / 2; } res += h * (func(x_left) + 4 * func(x_mid) + func(x_right)); } } void SimpsonCalcul::join(const SimpsonCalcul& sc) { res += sc.res; } double SimpsonTbb(const std::vector<double>& a, const std::vector<double>& b, int n, double(*func)(const std::vector<double>&)) { // CHEKS if (a.size() != b.size()) throw("Different dimesions of borders"); if (a.empty()) throw("Empty borders"); if (!(a < b)) throw("Wrong border format"); if (n % 2) throw("The number of partitions must be even"); size_t dimension = a.size(); std::vector<double> weight(dimension); double h = 1.0; std::vector<double> x_left(dimension); std::vector<double> x_right(dimension); std::vector<double> x_mid(dimension); for (size_t j = 0; j < dimension; j++) { weight[j] = (b[j] - a[j]) / static_cast<double>(n); h *= b[j] - a[j]; } h *= 1 / static_cast<double>(6.0 * n); SimpsonCalcul sc(func, a, weight, dimension, h); tbb::parallel_reduce(tbb::blocked_range<int>(0, n), sc); return sc.getRes(); } double SimpsonSeq(const std::vector<double>& a, const std::vector<double>& b, int n, double(*func)(const std::vector<double>&)) { // CHEKS if (a.size() != b.size()) throw("Different dimesions of borders"); if (a.empty()) throw("Empty borders"); if (!(a < b)) throw("Wrong border format"); if (n % 2) throw("The number of partitions must be even"); size_t dimension = a.size(); double res = 0.0; std::vector<double> weight(dimension); double h = 1.0; std::vector<double> x_left(dimension); std::vector<double> x_right(dimension); std::vector<double> x_mid(dimension); for (size_t j = 0; j < dimension; j++) { weight[j] = (b[j] - a[j]) / static_cast<double>(n); h *= b[j] - a[j]; } h *= 1 / static_cast<double>(6.0 * n); for (int i = 0; i < n; i++) { for (size_t j = 0; j < dimension; j++) { x_left[j] = a[j] + i * weight[j]; x_right[j] = a[j] + (i + 1) * weight[j]; x_mid[j] = (x_left[j] + x_right[j]) / 2; } res += h * (func(x_left) + 4 * func(x_mid) + func(x_right)); } return res; }
30.62766
80
0.552275
[ "vector" ]
1a09a4919f3c4c249fe656adcd14ed2e629f7448
5,382
cc
C++
modules/tools/navi_generator/backend/util/navigation_expander.cc
yujianyi/fusion_localization
c0057e29cbf690d6260f021080fd951c1a6b6baa
[ "Apache-2.0" ]
2
2019-03-04T02:11:04.000Z
2019-04-18T11:19:45.000Z
modules/tools/navi_generator/backend/util/navigation_expander.cc
yujianyi/fusion_localization
c0057e29cbf690d6260f021080fd951c1a6b6baa
[ "Apache-2.0" ]
1
2019-03-15T08:37:53.000Z
2019-03-15T08:37:53.000Z
modules/tools/navi_generator/backend/util/navigation_expander.cc
yujianyi/fusion_localization
c0057e29cbf690d6260f021080fd951c1a6b6baa
[ "Apache-2.0" ]
1
2019-03-04T02:11:09.000Z
2019-03-04T02:11:09.000Z
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the implementation of the class * "NavigationExpander". */ #include "modules/tools/navi_generator/backend/util/navigation_expander.h" #include <cmath> #include <list> #include <memory> #include <string> #include <vector> #include "modules/common/log.h" #include "modules/tools/navi_generator/backend/util/file_operator.h" namespace apollo { namespace navi_generator { namespace util { using apollo::planning::ReferencePoint; bool NavigationExpander::ExpandLane( const std::string& src_smoothed_file_name, const int left_lane_number, const int right_lane_number, const double lane_width, std::list<ExpandedFileInfo>* const expanded_files) { CHECK_NOTNULL(expanded_files); std::vector<apollo::planning::ReferencePoint> lane_points; std::list<LanePointsInfo> expanded_lane_list; FileOperator file_operator; // Import smoothed file. if (!file_operator.Import(src_smoothed_file_name, &lane_points)) { AERROR << "Import file failed"; return false; } // Expand lane if (!ExpandLane(lane_points, left_lane_number, right_lane_number, lane_width, &expanded_lane_list)) { AERROR << "Expand Lane failed"; return false; } // Export expanded lane data to files if (expanded_lane_list.empty()) { AERROR << "Expanded Lane list is empty"; return false; } std::string::size_type n = src_smoothed_file_name.rfind('.'); std::string prefix = src_smoothed_file_name.substr(0, n); for (const auto& lane_points_info : expanded_lane_list) { int index = lane_points_info.index; std::string file_name = prefix + "_" + std::to_string(lane_points_info.index) + ".smoothed"; ExpandedFileInfo expanded_file_info; expanded_file_info.index = index; expanded_file_info.file_name = file_name; // Skip export source smoothed file if (lane_points_info.index == right_lane_number) { expanded_file_info.file_name = src_smoothed_file_name; expanded_files->emplace_back(expanded_file_info); continue; } if (!file_operator.Export(file_name, lane_points_info.points)) { AERROR << "Expanded Lane list is empty"; return false; } expanded_files->emplace_back(expanded_file_info); } return true; } bool NavigationExpander::ExpandLane( const LanePoints& src_lane, const int left_lane_number, const int right_lane_number, const double lane_width, std::list<LanePointsInfo>* const dst_lane_list) { CHECK_NOTNULL(dst_lane_list); bool is_left_expand = false; // Current lane LanePointsInfo src_lane_points_info; src_lane_points_info.index = right_lane_number; src_lane_points_info.points = src_lane; dst_lane_list->emplace_back(src_lane_points_info); // Expand right lane. for (int i = 0; i < right_lane_number; ++i) { LanePointsInfo lane_points_info = dst_lane_list->back(); LanePointsInfo right_lane_points_info; right_lane_points_info.index = right_lane_number - i - 1; is_left_expand = false; ExpandOneLane(lane_points_info.points, lane_width, is_left_expand, &right_lane_points_info.points); dst_lane_list->emplace_back(right_lane_points_info); } // Expand left lane. for (int j = 0; j < left_lane_number; ++j) { LanePointsInfo lane_points_info = dst_lane_list->front(); LanePointsInfo left_lane_points_info; left_lane_points_info.index = lane_points_info.index + j + 1; is_left_expand = true; ExpandOneLane(lane_points_info.points, lane_width, is_left_expand, &left_lane_points_info.points); dst_lane_list->emplace_front(left_lane_points_info); } return true; } bool NavigationExpander::ExpandOneLane(const LanePoints& src_lane, const double lane_width, const bool is_left_expand, LanePoints* const dst_lane) { CHECK_NOTNULL(dst_lane); for (const auto& ref_point : src_lane) { ReferencePoint pt = ref_point; if (is_left_expand) { pt.set_x(ref_point.x() + lane_width * std::cos(ref_point.heading() + M_PI_2)); pt.set_y(ref_point.y() + lane_width * std::sin(ref_point.heading() + M_PI_2)); } else { pt.set_x(ref_point.x() + lane_width * std::cos(ref_point.heading() - M_PI_2)); pt.set_y(ref_point.y() + lane_width * std::sin(ref_point.heading() - M_PI_2)); } dst_lane->push_back(pt); } return true; } } // namespace util } // namespace navi_generator } // namespace apollo
35.88
79
0.681903
[ "vector" ]
1a0e667ad8533bd9fa881b831ad52fd2ff225c3e
87,993
cpp
C++
src/js/vm/TypedArrayObject.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
149
2018-12-23T09:08:00.000Z
2022-02-02T09:18:38.000Z
src/js/vm/TypedArrayObject.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
null
null
null
src/js/vm/TypedArrayObject.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
56
2018-12-23T18:11:40.000Z
2021-11-30T13:18:17.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "vm/TypedArrayObject-inl.h" #include "vm/TypedArrayObject.h" #include "mozilla/Alignment.h" #include "mozilla/Casting.h" #include "mozilla/FloatingPoint.h" #include "mozilla/PodOperations.h" #include "mozilla/TextUtils.h" #include <string.h> #ifndef XP_WIN # include <sys/mman.h> #endif #include "jsapi.h" #include "jsnum.h" #include "jstypes.h" #include "jsutil.h" #include "builtin/Array.h" #include "builtin/DataViewObject.h" #include "builtin/TypedObjectConstants.h" #include "gc/Barrier.h" #include "gc/Marking.h" #include "jit/InlinableNatives.h" #include "js/Conversions.h" #include "js/UniquePtr.h" #include "js/Wrapper.h" #include "util/Windows.h" #include "vm/ArrayBufferObject.h" #include "vm/GlobalObject.h" #include "vm/Interpreter.h" #include "vm/JSContext.h" #include "vm/JSObject.h" #include "vm/PIC.h" #include "vm/SelfHosting.h" #include "vm/SharedMem.h" #include "vm/WrapperObject.h" #include "gc/Nursery-inl.h" #include "gc/StoreBuffer-inl.h" #include "vm/ArrayBufferObject-inl.h" #include "vm/JSAtom-inl.h" #include "vm/NativeObject-inl.h" #include "vm/Shape-inl.h" using namespace js; using mozilla::AssertedCast; using mozilla::IsAsciiDigit; using JS::CanonicalizeNaN; using JS::ToInt32; using JS::ToUint32; /* * TypedArrayObject * * The non-templated base class for the specific typed implementations. * This class holds all the member variables that are used by * the subclasses. */ /* static */ int TypedArrayObject::lengthOffset() { return NativeObject::getFixedSlotOffset(LENGTH_SLOT); } /* static */ int TypedArrayObject::dataOffset() { return NativeObject::getPrivateDataOffset(DATA_SLOT); } /* static */ bool TypedArrayObject::is(HandleValue v) { return v.isObject() && v.toObject().is<TypedArrayObject>(); } /* static */ bool TypedArrayObject::ensureHasBuffer(JSContext* cx, Handle<TypedArrayObject*> tarray) { if (tarray->hasBuffer()) { return true; } Rooted<ArrayBufferObject*> buffer(cx, ArrayBufferObject::create(cx, tarray->byteLength())); if (!buffer) { return false; } if (!buffer->addView(cx, tarray)) { return false; } // tarray is not shared, because if it were it would have a buffer. memcpy(buffer->dataPointer(), tarray->dataPointerUnshared(), tarray->byteLength()); // If the object is in the nursery, the buffer will be freed by the next // nursery GC. Free the data slot pointer if the object has no inline data. Nursery& nursery = cx->nursery(); if (tarray->isTenured() && !tarray->hasInlineElements() && !nursery.isInside(tarray->elements())) { js_free(tarray->elements()); } tarray->setPrivate(buffer->dataPointer()); tarray->setFixedSlot(TypedArrayObject::BUFFER_SLOT, ObjectValue(*buffer)); // Notify compiled jit code that the base pointer has moved. MarkObjectStateChange(cx, tarray); return true; } #ifdef DEBUG void TypedArrayObject::assertZeroLengthArrayData() const { if (length() == 0 && !hasBuffer()) { uint8_t* end = fixedData(TypedArrayObject::FIXED_DATA_START); MOZ_ASSERT(end[0] == ZeroLengthArrayData); } } #endif void TypedArrayObject::finalize(FreeOp* fop, JSObject* obj) { MOZ_ASSERT(!IsInsideNursery(obj)); TypedArrayObject* curObj = &obj->as<TypedArrayObject>(); // Template objects or discarded objects (which didn't have enough room // for inner elements). Don't have anything to free. if (!curObj->elementsRaw()) { return; } curObj->assertZeroLengthArrayData(); // Typed arrays with a buffer object do not need to be free'd if (curObj->hasBuffer()) { return; } // Free the data slot pointer if it does not point into the old JSObject. if (!curObj->hasInlineElements()) { js_free(curObj->elements()); } } /* static */ size_t TypedArrayObject::objectMoved(JSObject* obj, JSObject* old) { TypedArrayObject* newObj = &obj->as<TypedArrayObject>(); TypedArrayObject* oldObj = &old->as<TypedArrayObject>(); MOZ_ASSERT(newObj->elementsRaw() == oldObj->elementsRaw()); MOZ_ASSERT(obj->isTenured()); // Typed arrays with a buffer object do not need an update. if (oldObj->hasBuffer()) { return 0; } if (!IsInsideNursery(old)) { // Update the data slot pointer if it points to the old JSObject. if (oldObj->hasInlineElements()) { newObj->setInlineElements(); } return 0; } Nursery& nursery = obj->runtimeFromMainThread()->gc.nursery(); void* buf = oldObj->elements(); if (!nursery.isInside(buf)) { nursery.removeMallocedBuffer(buf); return 0; } // Determine if we can use inline data for the target array. If this is // possible, the nursery will have picked an allocation size that is large // enough. size_t nbytes = 0; switch (oldObj->type()) { #define OBJECT_MOVED_TYPED_ARRAY(T, N) \ case Scalar::N: \ nbytes = oldObj->length() * sizeof(T); \ break; JS_FOR_EACH_TYPED_ARRAY(OBJECT_MOVED_TYPED_ARRAY) #undef OBJECT_MOVED_TYPED_ARRAY default: MOZ_CRASH("Unsupported TypedArray type"); } size_t headerSize = dataOffset() + sizeof(HeapSlot); // See AllocKindForLazyBuffer. gc::AllocKind newAllocKind = obj->asTenured().getAllocKind(); MOZ_ASSERT_IF(nbytes == 0, headerSize + sizeof(uint8_t) <= GetGCKindBytes(newAllocKind)); if (headerSize + nbytes <= GetGCKindBytes(newAllocKind)) { MOZ_ASSERT(oldObj->hasInlineElements()); #ifdef DEBUG if (nbytes == 0) { uint8_t* output = newObj->fixedData(TypedArrayObject::FIXED_DATA_START); output[0] = ZeroLengthArrayData; } #endif newObj->setInlineElements(); } else { MOZ_ASSERT(!oldObj->hasInlineElements()); AutoEnterOOMUnsafeRegion oomUnsafe; nbytes = JS_ROUNDUP(nbytes, sizeof(Value)); void* data = newObj->zone()->pod_malloc<uint8_t>(nbytes); if (!data) { oomUnsafe.crash("Failed to allocate typed array elements while tenuring."); } MOZ_ASSERT(!nursery.isInside(data)); newObj->initPrivate(data); } mozilla::PodCopy(newObj->elements(), oldObj->elements(), nbytes); // Set a forwarding pointer for the element buffers in case they were // preserved on the stack by Ion. nursery.setForwardingPointerWhileTenuring(oldObj->elements(), newObj->elements(), /* direct = */nbytes >= sizeof(uintptr_t)); return newObj->hasInlineElements() ? 0 : nbytes; } bool TypedArrayObject::hasInlineElements() const { return elements() == this->fixedData(TypedArrayObject::FIXED_DATA_START) && byteLength() <= TypedArrayObject::INLINE_BUFFER_LIMIT; } void TypedArrayObject::setInlineElements() { char* dataSlot = reinterpret_cast<char*>(this) + this->dataOffset(); *reinterpret_cast<void**>(dataSlot) = this->fixedData(TypedArrayObject::FIXED_DATA_START); } /* Helper clamped uint8_t type */ uint32_t JS_FASTCALL js::ClampDoubleToUint8(const double x) { // Not < so that NaN coerces to 0 if (!(x >= 0)) { return 0; } if (x > 255) { return 255; } double toTruncate = x + 0.5; uint8_t y = uint8_t(toTruncate); /* * now val is rounded to nearest, ties rounded up. We want * rounded to nearest ties to even, so check whether we had a * tie. */ if (y == toTruncate) { /* * It was a tie (since adding 0.5 gave us the exact integer * we want). Since we rounded up, we either already have an * even number or we have an odd number but the number we * want is one less. So just unconditionally masking out the * ones bit should do the trick to get us the value we * want. */ return y & ~1; } return y; } template<typename ElementType> static inline JSObject* NewArray(JSContext* cx, uint32_t nelements); namespace { enum class SpeciesConstructorOverride { None, ArrayBuffer }; enum class CreateSingleton { Yes, No }; template<typename NativeType> class TypedArrayObjectTemplate : public TypedArrayObject { friend class TypedArrayObject; public: static constexpr Scalar::Type ArrayTypeID() { return TypeIDOfType<NativeType>::id; } static bool ArrayTypeIsUnsigned() { return TypeIsUnsigned<NativeType>(); } static bool ArrayTypeIsFloatingPoint() { return TypeIsFloatingPoint<NativeType>(); } static const size_t BYTES_PER_ELEMENT = sizeof(NativeType); static JSObject* createPrototype(JSContext* cx, JSProtoKey key) { Handle<GlobalObject*> global = cx->global(); RootedObject typedArrayProto(cx, GlobalObject::getOrCreateTypedArrayPrototype(cx, global)); if (!typedArrayProto) { return nullptr; } const Class* clasp = TypedArrayObject::protoClassForType(ArrayTypeID()); return GlobalObject::createBlankPrototypeInheriting(cx, clasp, typedArrayProto); } static JSObject* createConstructor(JSContext* cx, JSProtoKey key) { Handle<GlobalObject*> global = cx->global(); RootedFunction ctorProto(cx, GlobalObject::getOrCreateTypedArrayConstructor(cx, global)); if (!ctorProto) { return nullptr; } JSFunction* fun = NewFunctionWithProto(cx, class_constructor, 3, JSFunction::NATIVE_CTOR, nullptr, ClassName(key, cx), ctorProto, gc::AllocKind::FUNCTION, SingletonObject); if (fun) { fun->setJitInfo(&jit::JitInfo_TypedArrayConstructor); } return fun; } static inline const Class* instanceClass() { return TypedArrayObject::classForType(ArrayTypeID()); } static bool is(HandleValue v) { return v.isObject() && v.toObject().hasClass(instanceClass()); } static void setIndexValue(TypedArrayObject& tarray, uint32_t index, double d) { // If the array is an integer array, we only handle up to // 32-bit ints from this point on. if we want to handle // 64-bit ints, we'll need some changes. // Assign based on characteristics of the destination type if (ArrayTypeIsFloatingPoint()) { setIndex(tarray, index, NativeType(d)); } else if (ArrayTypeIsUnsigned()) { MOZ_ASSERT(sizeof(NativeType) <= 4); uint32_t n = ToUint32(d); setIndex(tarray, index, NativeType(n)); } else if (ArrayTypeID() == Scalar::Uint8Clamped) { // The uint8_clamped type has a special rounding converter // for doubles. setIndex(tarray, index, NativeType(d)); } else { MOZ_ASSERT(sizeof(NativeType) <= 4); int32_t n = ToInt32(d); setIndex(tarray, index, NativeType(n)); } } static TypedArrayObject* makeProtoInstance(JSContext* cx, HandleObject proto, gc::AllocKind allocKind) { MOZ_ASSERT(proto); JSObject* obj = NewObjectWithGivenProto(cx, instanceClass(), proto, allocKind); return obj ? &obj->as<TypedArrayObject>() : nullptr; } static TypedArrayObject* makeTypedInstance(JSContext* cx, CreateSingleton createSingleton, gc::AllocKind allocKind) { const Class* clasp = instanceClass(); if (createSingleton == CreateSingleton::Yes) { JSObject* obj = NewBuiltinClassInstance(cx, clasp, allocKind, SingletonObject); if (!obj) { return nullptr; } return &obj->as<TypedArrayObject>(); } jsbytecode* pc; RootedScript script(cx, cx->currentScript(&pc)); NewObjectKind newKind = GenericObject; if (script && ObjectGroup::useSingletonForAllocationSite(script, pc, clasp)) { newKind = SingletonObject; } RootedObject obj(cx, NewBuiltinClassInstance(cx, clasp, allocKind, newKind)); if (!obj) { return nullptr; } if (script && !ObjectGroup::setAllocationSiteObjectGroup(cx, script, pc, obj, newKind == SingletonObject)) { return nullptr; } return &obj->as<TypedArrayObject>(); } static TypedArrayObject* makeInstance(JSContext* cx, Handle<ArrayBufferObjectMaybeShared*> buffer, CreateSingleton createSingleton, uint32_t byteOffset, uint32_t len, HandleObject proto) { MOZ_ASSERT_IF(!buffer, byteOffset == 0); MOZ_ASSERT_IF(buffer, !buffer->isDetached()); MOZ_ASSERT(len < INT32_MAX / sizeof(NativeType)); gc::AllocKind allocKind = buffer ? gc::GetGCObjectKind(instanceClass()) : AllocKindForLazyBuffer(len * sizeof(NativeType)); // Subclassing mandates that we hand in the proto every time. Most of // the time, though, that [[Prototype]] will not be interesting. If // it isn't, we can do some more TI optimizations. RootedObject checkProto(cx); if (proto) { checkProto = GlobalObject::getOrCreatePrototype(cx, JSCLASS_CACHED_PROTO_KEY(instanceClass())); if (!checkProto) { return nullptr; } } AutoSetNewObjectMetadata metadata(cx); Rooted<TypedArrayObject*> obj(cx); if (proto && proto != checkProto) { obj = makeProtoInstance(cx, proto, allocKind); } else { obj = makeTypedInstance(cx, createSingleton, allocKind); } if (!obj) { return nullptr; } bool isSharedMemory = buffer && IsSharedArrayBuffer(buffer.get()); obj->setFixedSlot(TypedArrayObject::BUFFER_SLOT, ObjectOrNullValue(buffer)); // This is invariant. Self-hosting code that sets BUFFER_SLOT // (if it does) must maintain it, should it need to. if (isSharedMemory) { obj->setIsSharedMemory(); } if (buffer) { obj->initDataPointer(buffer->dataPointerEither() + byteOffset); // If the buffer is for an inline typed object, the data pointer // may be in the nursery, so include a barrier to make sure this // object is updated if that typed object moves. auto ptr = buffer->dataPointerEither(); if (!IsInsideNursery(obj) && cx->nursery().isInside(ptr)) { // Shared buffer data should never be nursery-allocated, so we // need to fail here if isSharedMemory. However, mmap() can // place a SharedArrayRawBuffer up against the bottom end of a // nursery chunk, and a zero-length buffer will erroneously be // perceived as being inside the nursery; sidestep that. if (isSharedMemory) { MOZ_ASSERT(buffer->byteLength() == 0 && (uintptr_t(ptr.unwrapValue()) & gc::ChunkMask) == 0); } else { cx->runtime()->gc.storeBuffer().putWholeCell(obj); } } } else { void* data = obj->fixedData(FIXED_DATA_START); obj->initPrivate(data); memset(data, 0, len * sizeof(NativeType)); #ifdef DEBUG if (len == 0) { uint8_t* elements = static_cast<uint8_t*>(data); elements[0] = ZeroLengthArrayData; } #endif } obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(len)); obj->setFixedSlot(TypedArrayObject::BYTEOFFSET_SLOT, Int32Value(byteOffset)); #ifdef DEBUG if (buffer) { uint32_t arrayByteLength = obj->byteLength(); uint32_t arrayByteOffset = obj->byteOffset(); uint32_t bufferByteLength = buffer->byteLength(); // Unwraps are safe: both are for the pointer value. if (IsArrayBuffer(buffer.get())) { MOZ_ASSERT_IF(!AsArrayBuffer(buffer.get()).isDetached(), buffer->dataPointerEither().unwrap(/*safe*/) <= obj->dataPointerEither().unwrap(/*safe*/)); } MOZ_ASSERT(bufferByteLength - arrayByteOffset >= arrayByteLength); MOZ_ASSERT(arrayByteOffset <= bufferByteLength); } // Verify that the private slot is at the expected place MOZ_ASSERT(obj->numFixedSlots() == TypedArrayObject::DATA_SLOT); #endif // ArrayBufferObjects track their views to support detaching. if (buffer && buffer->is<ArrayBufferObject>()) { if (!buffer->as<ArrayBufferObject>().addView(cx, obj)) { return nullptr; } } return obj; } static TypedArrayObject* makeTemplateObject(JSContext* cx, int32_t len) { MOZ_ASSERT(len >= 0); size_t nbytes; MOZ_ALWAYS_TRUE(CalculateAllocSize<NativeType>(len, &nbytes)); MOZ_ASSERT(nbytes < TypedArrayObject::SINGLETON_BYTE_LENGTH); NewObjectKind newKind = TenuredObject; bool fitsInline = nbytes <= INLINE_BUFFER_LIMIT; const Class* clasp = instanceClass(); gc::AllocKind allocKind = !fitsInline ? gc::GetGCObjectKind(clasp) : AllocKindForLazyBuffer(nbytes); MOZ_ASSERT(CanBeFinalizedInBackground(allocKind, clasp)); allocKind = GetBackgroundAllocKind(allocKind); AutoSetNewObjectMetadata metadata(cx); jsbytecode* pc; RootedScript script(cx, cx->currentScript(&pc)); if (script && ObjectGroup::useSingletonForAllocationSite(script, pc, clasp)) { newKind = SingletonObject; } JSObject* tmp = NewBuiltinClassInstance(cx, clasp, allocKind, newKind); if (!tmp) { return nullptr; } Rooted<TypedArrayObject*> tarray(cx, &tmp->as<TypedArrayObject>()); initTypedArraySlots(tarray, len); // Template objects do not need memory for its elements, since there // won't be any elements to store. Therefore, we set the pointer to // nullptr and avoid allocating memory that will never be used. tarray->initPrivate(nullptr); if (script && !ObjectGroup::setAllocationSiteObjectGroup(cx, script, pc, tarray, newKind == SingletonObject)) { return nullptr; } return tarray; } static void initTypedArraySlots(TypedArrayObject* tarray, int32_t len) { MOZ_ASSERT(len >= 0); tarray->setFixedSlot(TypedArrayObject::BUFFER_SLOT, NullValue()); tarray->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(AssertedCast<int32_t>(len))); tarray->setFixedSlot(TypedArrayObject::BYTEOFFSET_SLOT, Int32Value(0)); // Verify that the private slot is at the expected place. MOZ_ASSERT(tarray->numFixedSlots() == TypedArrayObject::DATA_SLOT); #ifdef DEBUG if (len == 0) { uint8_t* output = tarray->fixedData(TypedArrayObject::FIXED_DATA_START); output[0] = TypedArrayObject::ZeroLengthArrayData; } #endif } static void initTypedArrayData(JSContext* cx, TypedArrayObject* tarray, int32_t len, void* buf, gc::AllocKind allocKind) { if (buf) { #ifdef DEBUG Nursery& nursery = cx->nursery(); MOZ_ASSERT_IF(!nursery.isInside(buf) && !tarray->hasInlineElements(), tarray->isTenured()); #endif tarray->initPrivate(buf); } else { size_t nbytes = len * sizeof(NativeType); #ifdef DEBUG size_t dataOffset = TypedArrayObject::dataOffset(); size_t offset = dataOffset + sizeof(HeapSlot); MOZ_ASSERT(offset + nbytes <= GetGCKindBytes(allocKind)); #endif void* data = tarray->fixedData(FIXED_DATA_START); tarray->initPrivate(data); memset(data, 0, nbytes); } } static TypedArrayObject* makeTypedArrayWithTemplate(JSContext* cx, TypedArrayObject* templateObj, int32_t len) { if (len < 0 || uint32_t(len) >= INT32_MAX / sizeof(NativeType)) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return nullptr; } size_t nbytes; MOZ_ALWAYS_TRUE(js::CalculateAllocSize<NativeType>(len, &nbytes)); bool fitsInline = nbytes <= INLINE_BUFFER_LIMIT; AutoSetNewObjectMetadata metadata(cx); const Class* clasp = templateObj->group()->clasp(); gc::AllocKind allocKind = !fitsInline ? gc::GetGCObjectKind(clasp) : AllocKindForLazyBuffer(nbytes); MOZ_ASSERT(CanBeFinalizedInBackground(allocKind, clasp)); allocKind = GetBackgroundAllocKind(allocKind); RootedObjectGroup group(cx, templateObj->group()); NewObjectKind newKind = TenuredObject; UniquePtr<void, JS::FreePolicy> buf; if (!fitsInline && len > 0) { buf.reset(cx->pod_calloc<uint8_t>(nbytes)); if (!buf) { return nullptr; } } TypedArrayObject* obj = NewObjectWithGroup<TypedArrayObject>(cx, group, allocKind, newKind); if (!obj) { return nullptr; } initTypedArraySlots(obj, len); initTypedArrayData(cx, obj, len, buf.release(), allocKind); return obj; } // ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add // 22.2.4.1 TypedArray ( ) // 22.2.4.2 TypedArray ( length ) // 22.2.4.3 TypedArray ( typedArray ) // 22.2.4.4 TypedArray ( object ) // 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] ) static bool class_constructor(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 1 (22.2.4.1) or 2 (22.2.4.2-5). if (!ThrowIfNotConstructing(cx, args, "typed array")) { return false; } JSObject* obj = create(cx, args); if (!obj) { return false; } args.rval().setObject(*obj); return true; } private: static JSObject* create(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(args.isConstructing()); // 22.2.4.1 TypedArray ( ) // 22.2.4.2 TypedArray ( length ) if (args.length() == 0 || !args[0].isObject()) { // 22.2.4.2, step 3. uint64_t len; if (!ToIndex(cx, args.get(0), JSMSG_BAD_ARRAY_LENGTH, &len)) { return nullptr; } // 22.2.4.1, step 3 and 22.2.4.2, step 5. // 22.2.4.2.1 AllocateTypedArray, step 1. RootedObject proto(cx); if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) { return nullptr; } return fromLength(cx, len, proto); } RootedObject dataObj(cx, &args[0].toObject()); // 22.2.4.{3,4,5}, step 4. // 22.2.4.2.1 AllocateTypedArray, step 1. RootedObject proto(cx); if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) { return nullptr; } // 22.2.4.3 TypedArray ( typedArray ) // 22.2.4.4 TypedArray ( object ) if (!UncheckedUnwrap(dataObj)->is<ArrayBufferObjectMaybeShared>()) { return fromArray(cx, dataObj, proto); } // 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] ) uint64_t byteOffset = 0; if (args.hasDefined(1)) { // Step 6. if (!ToIndex(cx, args[1], &byteOffset)) { return nullptr; } // Step 7. if (byteOffset % sizeof(NativeType) != 0) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS); return nullptr; } } uint64_t length = UINT64_MAX; if (args.hasDefined(2)) { // Step 8.a. if (!ToIndex(cx, args[2], &length)) { return nullptr; } } // Steps 9-17. if (dataObj->is<ArrayBufferObjectMaybeShared>()) { HandleArrayBufferObjectMaybeShared buffer = dataObj.as<ArrayBufferObjectMaybeShared>(); return fromBufferSameCompartment(cx, buffer, byteOffset, length, proto); } return fromBufferWrapped(cx, dataObj, byteOffset, length, proto); } // ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add // 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] ) // Steps 9-12. static bool computeAndCheckLength(JSContext* cx, HandleArrayBufferObjectMaybeShared bufferMaybeUnwrapped, uint64_t byteOffset, uint64_t lengthIndex, uint32_t* length) { MOZ_ASSERT(byteOffset % sizeof(NativeType) == 0); MOZ_ASSERT(byteOffset < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)); MOZ_ASSERT_IF(lengthIndex != UINT64_MAX, lengthIndex < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)); // Step 9. if (bufferMaybeUnwrapped->isDetached()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return false; } // Step 10. uint32_t bufferByteLength = bufferMaybeUnwrapped->byteLength(); uint32_t len; if (lengthIndex == UINT64_MAX) { // Steps 11.a, 11.c. if (bufferByteLength % sizeof(NativeType) != 0 || byteOffset > bufferByteLength) { // The given byte array doesn't map exactly to // |sizeof(NativeType) * N| or |byteOffset| is invalid. JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS); return false; } // Step 11.b. uint32_t newByteLength = bufferByteLength - uint32_t(byteOffset); len = newByteLength / sizeof(NativeType); } else { // Step 12.a. uint64_t newByteLength = lengthIndex * sizeof(NativeType); // Step 12.b. if (byteOffset + newByteLength > bufferByteLength) { // |byteOffset + newByteLength| is too big for the arraybuffer JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS); return false; } len = uint32_t(lengthIndex); } // ArrayBuffer is too large for TypedArrays: // Standalone ArrayBuffers can hold up to INT32_MAX bytes, whereas // buffers in TypedArrays must have less than or equal to // |INT32_MAX - sizeof(NativeType) - INT32_MAX % sizeof(NativeType)| // bytes. if (len >= INT32_MAX / sizeof(NativeType)) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS); return false; } MOZ_ASSERT(byteOffset <= UINT32_MAX); *length = len; return true; } // ES2018 draft rev 8340bf9a8427ea81bb0d1459471afbcc91d18add // 22.2.4.5 TypedArray ( buffer [ , byteOffset [ , length ] ] ) // Steps 9-17. static JSObject* fromBufferSameCompartment(JSContext* cx, HandleArrayBufferObjectMaybeShared buffer, uint64_t byteOffset, uint64_t lengthIndex, HandleObject proto) { // Steps 9-12. uint32_t length; if (!computeAndCheckLength(cx, buffer, byteOffset, lengthIndex, &length)) { return nullptr; } CreateSingleton createSingleton = CreateSingleton::No; if (length * sizeof(NativeType) >= TypedArrayObject::SINGLETON_BYTE_LENGTH) { createSingleton = CreateSingleton::Yes; } // Steps 13-17. return makeInstance(cx, buffer, createSingleton, uint32_t(byteOffset), length, proto); } // Create a TypedArray object in another compartment. // // ES6 supports creating a TypedArray in global A (using global A's // TypedArray constructor) backed by an ArrayBuffer created in global B. // // Our TypedArrayObject implementation doesn't support a TypedArray in // compartment A backed by an ArrayBuffer in compartment B. So in this // case, we create the TypedArray in B (!) and return a cross-compartment // wrapper. // // Extra twist: the spec says the new TypedArray's [[Prototype]] must be // A's TypedArray.prototype. So even though we're creating the TypedArray // in B, its [[Prototype]] must be (a cross-compartment wrapper for) the // TypedArray.prototype in A. static JSObject* fromBufferWrapped(JSContext* cx, HandleObject bufobj, uint64_t byteOffset, uint64_t lengthIndex, HandleObject proto) { JSObject* unwrapped = CheckedUnwrap(bufobj); if (!unwrapped) { ReportAccessDenied(cx); return nullptr; } if (!unwrapped->is<ArrayBufferObjectMaybeShared>()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_BAD_ARGS); return nullptr; } RootedArrayBufferObjectMaybeShared unwrappedBuffer(cx); unwrappedBuffer = &unwrapped->as<ArrayBufferObjectMaybeShared>(); uint32_t length; if (!computeAndCheckLength(cx, unwrappedBuffer, byteOffset, lengthIndex, &length)) { return nullptr; } // Make sure to get the [[Prototype]] for the created typed array from // this compartment. RootedObject protoRoot(cx, proto); if (!protoRoot) { protoRoot = GlobalObject::getOrCreatePrototype(cx, JSCLASS_CACHED_PROTO_KEY(instanceClass())); if (!protoRoot) { return nullptr; } } RootedObject typedArray(cx); { JSAutoRealm ar(cx, unwrappedBuffer); RootedObject wrappedProto(cx, protoRoot); if (!cx->compartment()->wrap(cx, &wrappedProto)) { return nullptr; } typedArray = makeInstance(cx, unwrappedBuffer, CreateSingleton::No, uint32_t(byteOffset), length, wrappedProto); if (!typedArray) { return nullptr; } } if (!cx->compartment()->wrap(cx, &typedArray)) { return nullptr; } return typedArray; } public: static JSObject* fromBuffer(JSContext* cx, HandleObject bufobj, uint32_t byteOffset, int32_t lengthInt) { if (byteOffset % sizeof(NativeType) != 0) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS); return nullptr; // invalid byteOffset } uint64_t lengthIndex = lengthInt >= 0 ? uint64_t(lengthInt) : UINT64_MAX; if (bufobj->is<ArrayBufferObjectMaybeShared>()) { HandleArrayBufferObjectMaybeShared buffer = bufobj.as<ArrayBufferObjectMaybeShared>(); return fromBufferSameCompartment(cx, buffer, byteOffset, lengthIndex, nullptr); } return fromBufferWrapped(cx, bufobj, byteOffset, lengthIndex, nullptr); } static bool maybeCreateArrayBuffer(JSContext* cx, uint32_t count, uint32_t unit, HandleObject nonDefaultProto, MutableHandle<ArrayBufferObject*> buffer) { if (count >= INT32_MAX / unit) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return false; } uint32_t byteLength = count * unit; MOZ_ASSERT(byteLength < INT32_MAX); static_assert(INLINE_BUFFER_LIMIT % sizeof(NativeType) == 0, "ArrayBuffer inline storage shouldn't waste any space"); if (!nonDefaultProto && byteLength <= INLINE_BUFFER_LIMIT) { // The array's data can be inline, and the buffer created lazily. return true; } ArrayBufferObject* buf = ArrayBufferObject::create(cx, byteLength, nonDefaultProto); if (!buf) { return false; } buffer.set(buf); return true; } // 22.2.4.1 TypedArray ( ) // 22.2.4.2 TypedArray ( length ) static JSObject* fromLength(JSContext* cx, uint64_t nelements, HandleObject proto = nullptr) { // 22.2.4.1, step 1 and 22.2.4.2, steps 1-3 (performed in caller). // 22.2.4.1, step 2 and 22.2.4.2, step 4 (implicit). // 22.2.4.1, step 3 and 22.2.4.2, step 5 (call AllocateTypedArray). if (nelements > UINT32_MAX) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return nullptr; } Rooted<ArrayBufferObject*> buffer(cx); if (!maybeCreateArrayBuffer(cx, uint32_t(nelements), BYTES_PER_ELEMENT, nullptr, &buffer)) { return nullptr; } return makeInstance(cx, buffer, CreateSingleton::No, 0, uint32_t(nelements), proto); } static bool AllocateArrayBuffer(JSContext* cx, HandleObject ctor, uint32_t count, uint32_t unit, MutableHandle<ArrayBufferObject*> buffer); static JSObject* fromArray(JSContext* cx, HandleObject other, HandleObject proto = nullptr); static JSObject* fromTypedArray(JSContext* cx, HandleObject other, bool isWrapped, HandleObject proto); static JSObject* fromObject(JSContext* cx, HandleObject other, HandleObject proto); static const NativeType getIndex(TypedArrayObject* tarray, uint32_t index) { MOZ_ASSERT(index < tarray->length()); return jit::AtomicOperations::loadSafeWhenRacy(tarray->dataPointerEither().cast<NativeType*>() + index); } static void setIndex(TypedArrayObject& tarray, uint32_t index, NativeType val) { MOZ_ASSERT(index < tarray.length()); jit::AtomicOperations::storeSafeWhenRacy(tarray.dataPointerEither().cast<NativeType*>() + index, val); } static Value getIndexValue(TypedArrayObject* tarray, uint32_t index); }; #define CREATE_TYPE_FOR_TYPED_ARRAY(T, N) \ typedef TypedArrayObjectTemplate<T> N##Array; JS_FOR_EACH_TYPED_ARRAY(CREATE_TYPE_FOR_TYPED_ARRAY) #undef CREATE_TYPE_FOR_TYPED_ARRAY } /* anonymous namespace */ TypedArrayObject* js::TypedArrayCreateWithTemplate(JSContext* cx, HandleObject templateObj, int32_t len) { MOZ_ASSERT(templateObj->is<TypedArrayObject>()); TypedArrayObject* tobj = &templateObj->as<TypedArrayObject>(); switch (tobj->type()) { #define CREATE_TYPED_ARRAY(T, N) \ case Scalar::N: \ return TypedArrayObjectTemplate<T>::makeTypedArrayWithTemplate(cx, tobj, len); JS_FOR_EACH_TYPED_ARRAY(CREATE_TYPED_ARRAY) #undef CREATE_TYPED_ARRAY default: MOZ_CRASH("Unsupported TypedArray type"); } } // ES2018 draft rev 2aea8f3e617b49df06414eb062ab44fad87661d3 // 24.1.1.1 AllocateArrayBuffer ( constructor, byteLength ) // byteLength = count * unit template<typename T> /* static */ bool TypedArrayObjectTemplate<T>::AllocateArrayBuffer(JSContext* cx, HandleObject ctor, uint32_t count, uint32_t unit, MutableHandle<ArrayBufferObject*> buffer) { // 24.1.1.1 step 1 (partially). RootedObject proto(cx); JSFunction* arrayBufferCtor = GlobalObject::getOrCreateArrayBufferConstructor(cx, cx->global()); if (!arrayBufferCtor) { return false; } // As an optimization, skip the "prototype" lookup for %ArrayBuffer%. if (ctor != arrayBufferCtor) { // 9.1.13 OrdinaryCreateFromConstructor, steps 1-2. if (!GetPrototypeFromConstructor(cx, ctor, &proto)) { return false; } JSObject* arrayBufferProto = GlobalObject::getOrCreateArrayBufferPrototype(cx, cx->global()); if (!arrayBufferProto) { return false; } // Reset |proto| if it's the default %ArrayBufferPrototype%. if (proto == arrayBufferProto) { proto = nullptr; } } // 24.1.1.1 steps 1 (remaining part), 2-6. if (!maybeCreateArrayBuffer(cx, count, unit, proto, buffer)) { return false; } return true; } static bool IsArrayBufferSpecies(JSContext* cx, JSFunction* species) { return IsSelfHostedFunctionWithName(species, cx->names().ArrayBufferSpecies); } static JSObject* GetBufferSpeciesConstructor(JSContext* cx, Handle<TypedArrayObject*> typedArray, bool isWrapped, SpeciesConstructorOverride override) { RootedObject defaultCtor(cx, GlobalObject::getOrCreateArrayBufferConstructor(cx, cx->global())); if (!defaultCtor) { return nullptr; } // Use the current global's ArrayBuffer if the override is set. if (override == SpeciesConstructorOverride::ArrayBuffer) { return defaultCtor; } RootedObject obj(cx, typedArray->bufferObject()); if (!obj) { MOZ_ASSERT(!isWrapped); // The buffer was never exposed to content code, so if // 1. %ArrayBufferPrototype%.constructor == %ArrayBuffer%, and // 2. %ArrayBuffer%[@@species] == ArrayBufferSpecies // we don't have to reify the buffer object and can simply return the // default arrray buffer constructor. JSObject* proto = GlobalObject::getOrCreateArrayBufferPrototype(cx, cx->global()); if (!proto) { return nullptr; } Value ctor; bool found; if (GetOwnPropertyPure(cx, proto, NameToId(cx->names().constructor), &ctor, &found) && ctor.isObject() && &ctor.toObject() == defaultCtor) { jsid speciesId = SYMBOL_TO_JSID(cx->wellKnownSymbols().species); JSFunction* getter; if (GetOwnGetterPure(cx, defaultCtor, speciesId, &getter) && getter && IsArrayBufferSpecies(cx, getter)) { return defaultCtor; } } if (!TypedArrayObject::ensureHasBuffer(cx, typedArray)) { return nullptr; } obj.set(typedArray->bufferObject()); } else { if (isWrapped && !cx->compartment()->wrap(cx, &obj)) { return nullptr; } } return SpeciesConstructor(cx, obj, defaultCtor, IsArrayBufferSpecies); } template<typename T> /* static */ JSObject* TypedArrayObjectTemplate<T>::fromArray(JSContext* cx, HandleObject other, HandleObject proto /* = nullptr */) { // Allow nullptr proto for FriendAPI methods, which don't care about // subclassing. if (other->is<TypedArrayObject>()) { return fromTypedArray(cx, other, /* wrapped= */ false, proto); } if (other->is<WrapperObject>() && UncheckedUnwrap(other)->is<TypedArrayObject>()) { return fromTypedArray(cx, other, /* wrapped= */ true, proto); } return fromObject(cx, other, proto); } // ES2018 draft rev 272beb67bc5cd9fd18a220665198384108208ee1 // 22.2.4.3 TypedArray ( typedArray ) template<typename T> /* static */ JSObject* TypedArrayObjectTemplate<T>::fromTypedArray(JSContext* cx, HandleObject other, bool isWrapped, HandleObject proto) { // Step 1. MOZ_ASSERT_IF(!isWrapped, other->is<TypedArrayObject>()); MOZ_ASSERT_IF(isWrapped, other->is<WrapperObject>() && UncheckedUnwrap(other)->is<TypedArrayObject>()); // Step 2 (Already performed in caller). // Steps 3-4 (Allocation deferred until later). // Step 5. Rooted<TypedArrayObject*> srcArray(cx); if (!isWrapped) { srcArray = &other->as<TypedArrayObject>(); } else { RootedObject unwrapped(cx, CheckedUnwrap(other)); if (!unwrapped) { ReportAccessDenied(cx); return nullptr; } JSAutoRealm ar(cx, unwrapped); srcArray = &unwrapped->as<TypedArrayObject>(); // To keep things simpler, we always reify the array buffer for // wrapped typed arrays. if (!TypedArrayObject::ensureHasBuffer(cx, srcArray)) { return nullptr; } } // Step 6 (skipped). // Step 7. if (srcArray->hasDetachedBuffer()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return nullptr; } // Step 9. uint32_t elementLength = srcArray->length(); // Steps 10-11. Scalar::Type srcType = srcArray->type(); // Steps 12-13 (skipped). // Steps 16-17. bool isShared = srcArray->isSharedMemory(); SpeciesConstructorOverride override = isShared ? SpeciesConstructorOverride::ArrayBuffer : SpeciesConstructorOverride::None; RootedObject bufferCtor(cx, GetBufferSpeciesConstructor(cx, srcArray, isWrapped, override)); if (!bufferCtor) { return nullptr; } // Steps 8, 18-19. Rooted<ArrayBufferObject*> buffer(cx); if (ArrayTypeID() == srcType) { // Step 15. uint32_t byteLength = srcArray->byteLength(); // Step 18.a. // 24.1.1.4 CloneArrayBuffer(...), steps 1-3. if (!AllocateArrayBuffer(cx, bufferCtor, byteLength, 1, &buffer)) { return nullptr; } } else { // Steps 14-15, 19.a. if (!AllocateArrayBuffer(cx, bufferCtor, elementLength, BYTES_PER_ELEMENT, &buffer)) { return nullptr; } } // Step 19.b or 24.1.1.4 step 4. if (srcArray->hasDetachedBuffer()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return nullptr; } // Steps 3-4 (remaining part), 20-23. Rooted<TypedArrayObject*> obj(cx, makeInstance(cx, buffer, CreateSingleton::No, 0, elementLength, proto)); if (!obj) { return nullptr; } // Steps 19.c-f or 24.1.1.4 steps 5-7. MOZ_ASSERT(!obj->isSharedMemory()); if (isShared) { if (!ElementSpecific<T, SharedOps>::setFromTypedArray(obj, srcArray, 0)) { return nullptr; } } else { if (!ElementSpecific<T, UnsharedOps>::setFromTypedArray(obj, srcArray, 0)) { return nullptr; } } // Step 24. return obj; } static MOZ_ALWAYS_INLINE bool IsOptimizableInit(JSContext* cx, HandleObject iterable, bool* optimized) { MOZ_ASSERT(!*optimized); if (!IsPackedArray(iterable)) { return true; } ForOfPIC::Chain* stubChain = ForOfPIC::getOrCreate(cx); if (!stubChain) { return false; } return stubChain->tryOptimizeArray(cx, iterable.as<ArrayObject>(), optimized); } // ES2017 draft rev 6859bb9ccaea9c6ede81d71e5320e3833b92cb3e // 22.2.4.4 TypedArray ( object ) template<typename T> /* static */ JSObject* TypedArrayObjectTemplate<T>::fromObject(JSContext* cx, HandleObject other, HandleObject proto) { // Steps 1-2 (Already performed in caller). // Steps 3-4 (Allocation deferred until later). bool optimized = false; if (!IsOptimizableInit(cx, other, &optimized)) { return nullptr; } // Fast path when iterable is a packed array using the default iterator. if (optimized) { // Step 6.a (We don't need to call IterableToList for the fast path). HandleArrayObject array = other.as<ArrayObject>(); // Step 6.b. uint32_t len = array->getDenseInitializedLength(); // Step 6.c. Rooted<ArrayBufferObject*> buffer(cx); if (!maybeCreateArrayBuffer(cx, len, BYTES_PER_ELEMENT, nullptr, &buffer)) { return nullptr; } Rooted<TypedArrayObject*> obj(cx, makeInstance(cx, buffer, CreateSingleton::No, 0, len, proto)); if (!obj) { return nullptr; } // Steps 6.d-e. MOZ_ASSERT(!obj->isSharedMemory()); if (!ElementSpecific<T, UnsharedOps>::initFromIterablePackedArray(cx, obj, array)) { return nullptr; } // Step 6.f (The assertion isn't applicable for the fast path). // Step 6.g. return obj; } // Step 5. RootedValue callee(cx); RootedId iteratorId(cx, SYMBOL_TO_JSID(cx->wellKnownSymbols().iterator)); if (!GetProperty(cx, other, other, iteratorId, &callee)) { return nullptr; } // Steps 6-8. RootedObject arrayLike(cx); if (!callee.isNullOrUndefined()) { // Throw if other[Symbol.iterator] isn't callable. if (!callee.isObject() || !callee.toObject().isCallable()) { RootedValue otherVal(cx, ObjectValue(*other)); UniqueChars bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, otherVal, nullptr); if (!bytes) { return nullptr; } JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_NOT_ITERABLE, bytes.get()); return nullptr; } FixedInvokeArgs<2> args2(cx); args2[0].setObject(*other); args2[1].set(callee); // Step 6.a. RootedValue rval(cx); if (!CallSelfHostedFunction(cx, cx->names().IterableToList, UndefinedHandleValue, args2, &rval)) { return nullptr; } // Steps 6.b-g (Implemented in steps 9-13 below). arrayLike = &rval.toObject(); } else { // Step 7 is an assertion: object is not an Iterator. Testing this is // literally the very last thing we did, so we don't assert here. // Step 8. arrayLike = other; } // Step 9. uint32_t len; if (!GetLengthProperty(cx, arrayLike, &len)) { return nullptr; } // Step 10. Rooted<ArrayBufferObject*> buffer(cx); if (!maybeCreateArrayBuffer(cx, len, BYTES_PER_ELEMENT, nullptr, &buffer)) { return nullptr; } Rooted<TypedArrayObject*> obj(cx, makeInstance(cx, buffer, CreateSingleton::No, 0, len, proto)); if (!obj) { return nullptr; } // Steps 11-12. MOZ_ASSERT(!obj->isSharedMemory()); if (!ElementSpecific<T, UnsharedOps>::setFromNonTypedArray(cx, obj, arrayLike, len)) { return nullptr; } // Step 13. return obj; } bool TypedArrayConstructor(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_CALL_OR_CONSTRUCT, args.isConstructing() ? "construct" : "call"); return false; } /* static */ bool TypedArrayObject::GetTemplateObjectForNative(JSContext* cx, Native native, uint32_t len, MutableHandleObject res) { #define CHECK_TYPED_ARRAY_CONSTRUCTOR(T, N) \ if (native == &TypedArrayObjectTemplate<T>::class_constructor) { \ size_t nbytes; \ if (!js::CalculateAllocSize<T>(len, &nbytes)) \ return true; \ \ if (nbytes < TypedArrayObject::SINGLETON_BYTE_LENGTH) { \ res.set(TypedArrayObjectTemplate<T>::makeTemplateObject(cx, len)); \ return !!res; \ } \ } JS_FOR_EACH_TYPED_ARRAY(CHECK_TYPED_ARRAY_CONSTRUCTOR) #undef CHECK_TYPED_ARRAY_CONSTRUCTOR return true; } static bool TypedArray_lengthGetter(JSContext* cx, unsigned argc, Value* vp) { return TypedArrayObject::Getter<TypedArrayObject::lengthValue>(cx, argc, vp); } bool BufferGetterImpl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(TypedArrayObject::is(args.thisv())); Rooted<TypedArrayObject*> tarray(cx, &args.thisv().toObject().as<TypedArrayObject>()); if (!TypedArrayObject::ensureHasBuffer(cx, tarray)) { return false; } args.rval().set(TypedArrayObject::bufferValue(tarray)); return true; } /*static*/ bool js::TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return CallNonGenericMethod<TypedArrayObject::is, BufferGetterImpl>(cx, args); } /* static */ const JSPropertySpec TypedArrayObject::protoAccessors[] = { JS_PSG("length", TypedArray_lengthGetter, 0), JS_PSG("buffer", TypedArray_bufferGetter, 0), JS_PSG("byteLength", TypedArrayObject::Getter<TypedArrayObject::byteLengthValue>, 0), JS_PSG("byteOffset", TypedArrayObject::Getter<TypedArrayObject::byteOffsetValue>, 0), JS_SELF_HOSTED_SYM_GET(toStringTag, "TypedArrayToStringTag", 0), JS_PS_END }; template<typename T> static inline bool SetFromTypedArray(Handle<TypedArrayObject*> target, Handle<TypedArrayObject*> source, uint32_t offset) { // WARNING: |source| may be an unwrapped typed array from a different // compartment. Proceed with caution! if (target->isSharedMemory() || source->isSharedMemory()) { return ElementSpecific<T, SharedOps>::setFromTypedArray(target, source, offset); } return ElementSpecific<T, UnsharedOps>::setFromTypedArray(target, source, offset); } template<typename T> static inline bool SetFromNonTypedArray(JSContext* cx, Handle<TypedArrayObject*> target, HandleObject source, uint32_t len, uint32_t offset) { MOZ_ASSERT(!source->is<TypedArrayObject>(), "use SetFromTypedArray"); if (target->isSharedMemory()) { return ElementSpecific<T, SharedOps>::setFromNonTypedArray(cx, target, source, len, offset); } return ElementSpecific<T, UnsharedOps>::setFromNonTypedArray(cx, target, source, len, offset); } // ES2017 draft rev c57ef95c45a371f9c9485bb1c3881dbdc04524a2 // 22.2.3.23 %TypedArray%.prototype.set ( overloaded [ , offset ] ) // 22.2.3.23.1 %TypedArray%.prototype.set ( array [ , offset ] ) // 22.2.3.23.2 %TypedArray%.prototype.set( typedArray [ , offset ] ) /* static */ bool TypedArrayObject::set_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(TypedArrayObject::is(args.thisv())); // Steps 1-5 (Validation performed as part of CallNonGenericMethod). Rooted<TypedArrayObject*> target(cx, &args.thisv().toObject().as<TypedArrayObject>()); // Steps 6-7. double targetOffset = 0; if (args.length() > 1) { // Step 6. if (!ToInteger(cx, args[1], &targetOffset)) { return false; } // Step 7. if (targetOffset < 0) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX); return false; } } // Steps 8-9. if (target->hasDetachedBuffer()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return false; } // 22.2.3.23.1, step 15. (22.2.3.23.2 only applies if args[0] is a typed // array, so it doesn't make a difference there to apply ToObject here.) RootedObject src(cx, ToObject(cx, args.get(0))); if (!src) { return false; } Rooted<TypedArrayObject*> srcTypedArray(cx); { JSObject* obj = CheckedUnwrap(src); if (!obj) { ReportAccessDenied(cx); return false; } if (obj->is<TypedArrayObject>()) { srcTypedArray = &obj->as<TypedArrayObject>(); } } if (srcTypedArray) { // Remaining steps of 22.2.3.23.2. // WARNING: |srcTypedArray| may be an unwrapped typed array from a // different compartment. Proceed with caution! // Steps 11-12. if (srcTypedArray->hasDetachedBuffer()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return false; } // Step 10 (Reordered). uint32_t targetLength = target->length(); // Step 22 (Split into two checks to provide better error messages). if (targetOffset > targetLength) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX); return false; } // Step 22 (Cont'd). uint32_t offset = uint32_t(targetOffset); if (srcTypedArray->length() > targetLength - offset) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return false; } // Steps 13-21, 23-28. switch (target->type()) { #define SET_FROM_TYPED_ARRAY(T, N) \ case Scalar::N: \ if (!SetFromTypedArray<T>(target, srcTypedArray, offset)) \ return false; \ break; JS_FOR_EACH_TYPED_ARRAY(SET_FROM_TYPED_ARRAY) #undef SET_FROM_TYPED_ARRAY default: MOZ_CRASH("Unsupported TypedArray type"); } } else { // Remaining steps of 22.2.3.23.1. // Step 10. // We can't reorder this step because side-effects in step 16 can // detach the underlying array buffer from the typed array. uint32_t targetLength = target->length(); // Step 16. uint32_t srcLength; if (!GetLengthProperty(cx, src, &srcLength)) { return false; } // Step 17 (Split into two checks to provide better error messages). if (targetOffset > targetLength) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX); return false; } // Step 17 (Cont'd). uint32_t offset = uint32_t(targetOffset); if (srcLength > targetLength - offset) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return false; } // Steps 11-14, 18-21. if (srcLength > 0) { // GetLengthProperty in step 16 can lead to the execution of user // code which may detach the buffer. Handle this case here to // ensure SetFromNonTypedArray is never called with a detached // buffer. We still need to execute steps 21.a-b for their // possible side-effects. if (target->hasDetachedBuffer()) { // Steps 21.a-b. RootedValue v(cx); if (!GetElement(cx, src, src, 0, &v)) { return false; } double unused; if (!ToNumber(cx, v, &unused)) { return false; } // Step 21.c. JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return false; } switch (target->type()) { #define SET_FROM_NON_TYPED_ARRAY(T, N) \ case Scalar::N: \ if (!SetFromNonTypedArray<T>(cx, target, src, srcLength, offset)) \ return false; \ break; JS_FOR_EACH_TYPED_ARRAY(SET_FROM_NON_TYPED_ARRAY) #undef SET_FROM_NON_TYPED_ARRAY default: MOZ_CRASH("Unsupported TypedArray type"); } // Step 21.c. // SetFromNonTypedArray doesn't throw when the array buffer gets // detached. if (target->hasDetachedBuffer()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_TYPED_ARRAY_DETACHED); return false; } } } // Step 29/22. args.rval().setUndefined(); return true; } /* static */ bool TypedArrayObject::set(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return CallNonGenericMethod<TypedArrayObject::is, TypedArrayObject::set_impl>(cx, args); } /* static */ const JSFunctionSpec TypedArrayObject::protoFunctions[] = { JS_SELF_HOSTED_FN("subarray", "TypedArraySubarray", 2, 0), #if 0 /* disabled until perf-testing is completed */ JS_SELF_HOSTED_FN("set", "TypedArraySet", 2, 0), #else JS_FN("set", TypedArrayObject::set, 1, 0), #endif JS_SELF_HOSTED_FN("copyWithin", "TypedArrayCopyWithin", 3, 0), JS_SELF_HOSTED_FN("every", "TypedArrayEvery", 1, 0), JS_SELF_HOSTED_FN("fill", "TypedArrayFill", 3, 0), JS_SELF_HOSTED_FN("filter", "TypedArrayFilter", 1, 0), JS_SELF_HOSTED_FN("find", "TypedArrayFind", 1, 0), JS_SELF_HOSTED_FN("findIndex", "TypedArrayFindIndex", 1, 0), JS_SELF_HOSTED_FN("forEach", "TypedArrayForEach", 1, 0), JS_SELF_HOSTED_FN("indexOf", "TypedArrayIndexOf", 2, 0), JS_SELF_HOSTED_FN("join", "TypedArrayJoin", 1, 0), JS_SELF_HOSTED_FN("lastIndexOf", "TypedArrayLastIndexOf", 1, 0), JS_SELF_HOSTED_FN("map", "TypedArrayMap", 1, 0), JS_SELF_HOSTED_FN("reduce", "TypedArrayReduce", 1, 0), JS_SELF_HOSTED_FN("reduceRight", "TypedArrayReduceRight", 1, 0), JS_SELF_HOSTED_FN("reverse", "TypedArrayReverse", 0, 0), JS_SELF_HOSTED_FN("slice", "TypedArraySlice", 2, 0), JS_SELF_HOSTED_FN("some", "TypedArraySome", 1, 0), JS_SELF_HOSTED_FN("sort", "TypedArraySort", 1, 0), JS_SELF_HOSTED_FN("entries", "TypedArrayEntries", 0, 0), JS_SELF_HOSTED_FN("keys", "TypedArrayKeys", 0, 0), JS_SELF_HOSTED_FN("values", "TypedArrayValues", 0, 0), JS_SELF_HOSTED_SYM_FN(iterator, "TypedArrayValues", 0, 0), JS_SELF_HOSTED_FN("includes", "TypedArrayIncludes", 2, 0), JS_SELF_HOSTED_FN("toString", "ArrayToString", 0, 0), JS_SELF_HOSTED_FN("toLocaleString", "TypedArrayToLocaleString", 2, 0), JS_FS_END }; /* static */ const JSFunctionSpec TypedArrayObject::staticFunctions[] = { JS_SELF_HOSTED_FN("from", "TypedArrayStaticFrom", 3, 0), JS_SELF_HOSTED_FN("of", "TypedArrayStaticOf", 0, 0), JS_FS_END }; /* static */ const JSPropertySpec TypedArrayObject::staticProperties[] = { JS_SELF_HOSTED_SYM_GET(species, "TypedArraySpecies", 0), JS_PS_END }; static JSObject* CreateSharedTypedArrayPrototype(JSContext* cx, JSProtoKey key) { return GlobalObject::createBlankPrototype(cx, cx->global(), &TypedArrayObject::sharedTypedArrayPrototypeClass); } static const ClassSpec TypedArrayObjectSharedTypedArrayPrototypeClassSpec = { GenericCreateConstructor<TypedArrayConstructor, 0, gc::AllocKind::FUNCTION>, CreateSharedTypedArrayPrototype, TypedArrayObject::staticFunctions, TypedArrayObject::staticProperties, TypedArrayObject::protoFunctions, TypedArrayObject::protoAccessors, nullptr, ClassSpec::DontDefineConstructor }; /* static */ const Class TypedArrayObject::sharedTypedArrayPrototypeClass = { "TypedArrayPrototype", JSCLASS_HAS_CACHED_PROTO(JSProto_TypedArray), JS_NULL_CLASS_OPS, &TypedArrayObjectSharedTypedArrayPrototypeClassSpec }; // this default implementation is only valid for integer types // less than 32-bits in size. template<typename NativeType> Value TypedArrayObjectTemplate<NativeType>::getIndexValue(TypedArrayObject* tarray, uint32_t index) { static_assert(sizeof(NativeType) < 4, "this method must only handle NativeType values that are " "always exact int32_t values"); return Int32Value(getIndex(tarray, index)); } namespace { // and we need to specialize for 32-bit integers and floats template<> Value TypedArrayObjectTemplate<int32_t>::getIndexValue(TypedArrayObject* tarray, uint32_t index) { return Int32Value(getIndex(tarray, index)); } template<> Value TypedArrayObjectTemplate<uint32_t>::getIndexValue(TypedArrayObject* tarray, uint32_t index) { uint32_t val = getIndex(tarray, index); return NumberValue(val); } template<> Value TypedArrayObjectTemplate<float>::getIndexValue(TypedArrayObject* tarray, uint32_t index) { float val = getIndex(tarray, index); double dval = val; /* * Doubles in typed arrays could be typed-punned arrays of integers. This * could allow user code to break the engine-wide invariant that only * canonical nans are stored into jsvals, which means user code could * confuse the engine into interpreting a double-typed jsval as an * object-typed jsval. * * This could be removed for platforms/compilers known to convert a 32-bit * non-canonical nan to a 64-bit canonical nan. */ return DoubleValue(CanonicalizeNaN(dval)); } template<> Value TypedArrayObjectTemplate<double>::getIndexValue(TypedArrayObject* tarray, uint32_t index) { double val = getIndex(tarray, index); /* * Doubles in typed arrays could be typed-punned arrays of integers. This * could allow user code to break the engine-wide invariant that only * canonical nans are stored into jsvals, which means user code could * confuse the engine into interpreting a double-typed jsval as an * object-typed jsval. */ return DoubleValue(CanonicalizeNaN(val)); } } /* anonymous namespace */ Value TypedArrayObject::getElement(uint32_t index) { switch (type()) { case Scalar::Int8: return Int8Array::getIndexValue(this, index); case Scalar::Uint8: return Uint8Array::getIndexValue(this, index); case Scalar::Int16: return Int16Array::getIndexValue(this, index); case Scalar::Uint16: return Uint16Array::getIndexValue(this, index); case Scalar::Int32: return Int32Array::getIndexValue(this, index); case Scalar::Uint32: return Uint32Array::getIndexValue(this, index); case Scalar::Float32: return Float32Array::getIndexValue(this, index); case Scalar::Float64: return Float64Array::getIndexValue(this, index); case Scalar::Uint8Clamped: return Uint8ClampedArray::getIndexValue(this, index); case Scalar::Int64: case Scalar::MaxTypedArrayViewType: break; } MOZ_CRASH("Unknown TypedArray type"); } void TypedArrayObject::setElement(TypedArrayObject& obj, uint32_t index, double d) { MOZ_ASSERT(index < obj.length()); #ifdef JS_MORE_DETERMINISTIC // See the comment in ElementSpecific::doubleToNative. d = JS::CanonicalizeNaN(d); #endif switch (obj.type()) { case Scalar::Int8: Int8Array::setIndexValue(obj, index, d); return; case Scalar::Uint8: Uint8Array::setIndexValue(obj, index, d); return; case Scalar::Uint8Clamped: Uint8ClampedArray::setIndexValue(obj, index, d); return; case Scalar::Int16: Int16Array::setIndexValue(obj, index, d); return; case Scalar::Uint16: Uint16Array::setIndexValue(obj, index, d); return; case Scalar::Int32: Int32Array::setIndexValue(obj, index, d); return; case Scalar::Uint32: Uint32Array::setIndexValue(obj, index, d); return; case Scalar::Float32: Float32Array::setIndexValue(obj, index, d); return; case Scalar::Float64: Float64Array::setIndexValue(obj, index, d); return; case Scalar::Int64: case Scalar::MaxTypedArrayViewType: break; } MOZ_CRASH("Unknown TypedArray type"); } void TypedArrayObject::getElements(Value* vp) { uint32_t length = this->length(); MOZ_ASSERT_IF(length > 0, !hasDetachedBuffer()); switch (type()) { #define GET_ELEMENTS(T, N) \ case Scalar::N: \ for (uint32_t i = 0; i < length; ++i, ++vp) \ *vp = N##Array::getIndexValue(this, i); \ break; JS_FOR_EACH_TYPED_ARRAY(GET_ELEMENTS) #undef GET_ELEMENTS default: MOZ_CRASH("Unknown TypedArray type"); } } /*** *** JS impl ***/ /* * TypedArrayObject boilerplate */ #define IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Name,NativeType) \ JS_FRIEND_API(JSObject*) JS_New ## Name ## Array(JSContext* cx, uint32_t nelements) \ { \ return TypedArrayObjectTemplate<NativeType>::fromLength(cx, nelements); \ } \ JS_FRIEND_API(JSObject*) JS_New ## Name ## ArrayFromArray(JSContext* cx, HandleObject other) \ { \ return TypedArrayObjectTemplate<NativeType>::fromArray(cx, other); \ } \ JS_FRIEND_API(JSObject*) JS_New ## Name ## ArrayWithBuffer(JSContext* cx, \ HandleObject arrayBuffer, uint32_t byteOffset, int32_t length) \ { \ return TypedArrayObjectTemplate<NativeType>::fromBuffer(cx, arrayBuffer, byteOffset, \ length); \ } \ JS_FRIEND_API(bool) JS_Is ## Name ## Array(JSObject* obj) \ { \ if (!(obj = CheckedUnwrap(obj))) \ return false; \ const Class* clasp = obj->getClass(); \ return clasp == TypedArrayObjectTemplate<NativeType>::instanceClass(); \ } \ JS_FRIEND_API(JSObject*) js::Unwrap ## Name ## Array(JSObject* obj) \ { \ obj = CheckedUnwrap(obj); \ if (!obj) \ return nullptr; \ const Class* clasp = obj->getClass(); \ if (clasp == TypedArrayObjectTemplate<NativeType>::instanceClass()) \ return obj; \ return nullptr; \ } \ const js::Class* const js::detail::Name ## ArrayClassPtr = \ &js::TypedArrayObject::classes[TypedArrayObjectTemplate<NativeType>::ArrayTypeID()]; IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Int8, int8_t) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Uint8, uint8_t) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Uint8Clamped, uint8_clamped) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Int16, int16_t) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Uint16, uint16_t) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Int32, int32_t) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Uint32, uint32_t) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Float32, float) IMPL_TYPED_ARRAY_JSAPI_CONSTRUCTORS(Float64, double) #define IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Name, ExternalType, InternalType) \ JS_FRIEND_API(JSObject*) JS_GetObjectAs ## Name ## Array(JSObject* obj, \ uint32_t* length, \ bool* isShared, \ ExternalType** data) \ { \ if (!(obj = CheckedUnwrap(obj))) \ return nullptr; \ \ const Class* clasp = obj->getClass(); \ if (clasp != TypedArrayObjectTemplate<InternalType>::instanceClass()) \ return nullptr; \ \ TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); \ *length = tarr->length(); \ *isShared = tarr->isSharedMemory(); \ *data = static_cast<ExternalType*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isShared flag*/)); \ \ return obj; \ } IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Int8, int8_t, int8_t) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Uint8, uint8_t, uint8_t) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Uint8Clamped, uint8_t, uint8_clamped) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Int16, int16_t, int16_t) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Uint16, uint16_t, uint16_t) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Int32, int32_t, int32_t) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Uint32, uint32_t, uint32_t) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Float32, float, float) IMPL_TYPED_ARRAY_COMBINED_UNWRAPPERS(Float64, double, double) static const ClassOps TypedArrayClassOps = { nullptr, /* addProperty */ nullptr, /* delProperty */ nullptr, /* enumerate */ nullptr, /* newEnumerate */ nullptr, /* resolve */ nullptr, /* mayResolve */ TypedArrayObject::finalize, /* finalize */ nullptr, /* call */ nullptr, /* hasInstance */ nullptr, /* construct */ ArrayBufferViewObject::trace, /* trace */ }; static const ClassExtension TypedArrayClassExtension = { nullptr, TypedArrayObject::objectMoved, }; #define IMPL_TYPED_ARRAY_PROPERTIES(_type) \ { \ JS_INT32_PS("BYTES_PER_ELEMENT", _type##Array::BYTES_PER_ELEMENT, \ JSPROP_READONLY | JSPROP_PERMANENT), \ JS_PS_END \ } static const JSPropertySpec static_prototype_properties[Scalar::MaxTypedArrayViewType][2] = { IMPL_TYPED_ARRAY_PROPERTIES(Int8), IMPL_TYPED_ARRAY_PROPERTIES(Uint8), IMPL_TYPED_ARRAY_PROPERTIES(Int16), IMPL_TYPED_ARRAY_PROPERTIES(Uint16), IMPL_TYPED_ARRAY_PROPERTIES(Int32), IMPL_TYPED_ARRAY_PROPERTIES(Uint32), IMPL_TYPED_ARRAY_PROPERTIES(Float32), IMPL_TYPED_ARRAY_PROPERTIES(Float64), IMPL_TYPED_ARRAY_PROPERTIES(Uint8Clamped) }; #define IMPL_TYPED_ARRAY_CLASS_SPEC(_type) \ { \ _type##Array::createConstructor, \ _type##Array::createPrototype, \ nullptr, \ static_prototype_properties[Scalar::Type::_type], \ nullptr, \ static_prototype_properties[Scalar::Type::_type], \ nullptr, \ JSProto_TypedArray \ } static const ClassSpec TypedArrayObjectClassSpecs[Scalar::MaxTypedArrayViewType] = { IMPL_TYPED_ARRAY_CLASS_SPEC(Int8), IMPL_TYPED_ARRAY_CLASS_SPEC(Uint8), IMPL_TYPED_ARRAY_CLASS_SPEC(Int16), IMPL_TYPED_ARRAY_CLASS_SPEC(Uint16), IMPL_TYPED_ARRAY_CLASS_SPEC(Int32), IMPL_TYPED_ARRAY_CLASS_SPEC(Uint32), IMPL_TYPED_ARRAY_CLASS_SPEC(Float32), IMPL_TYPED_ARRAY_CLASS_SPEC(Float64), IMPL_TYPED_ARRAY_CLASS_SPEC(Uint8Clamped) }; #define IMPL_TYPED_ARRAY_CLASS(_type) \ { \ #_type "Array", \ JSCLASS_HAS_RESERVED_SLOTS(TypedArrayObject::RESERVED_SLOTS) | \ JSCLASS_HAS_PRIVATE | \ JSCLASS_HAS_CACHED_PROTO(JSProto_##_type##Array) | \ JSCLASS_DELAY_METADATA_BUILDER | \ JSCLASS_SKIP_NURSERY_FINALIZE | \ JSCLASS_BACKGROUND_FINALIZE, \ &TypedArrayClassOps, \ &TypedArrayObjectClassSpecs[Scalar::Type::_type], \ &TypedArrayClassExtension \ } const Class TypedArrayObject::classes[Scalar::MaxTypedArrayViewType] = { IMPL_TYPED_ARRAY_CLASS(Int8), IMPL_TYPED_ARRAY_CLASS(Uint8), IMPL_TYPED_ARRAY_CLASS(Int16), IMPL_TYPED_ARRAY_CLASS(Uint16), IMPL_TYPED_ARRAY_CLASS(Int32), IMPL_TYPED_ARRAY_CLASS(Uint32), IMPL_TYPED_ARRAY_CLASS(Float32), IMPL_TYPED_ARRAY_CLASS(Float64), IMPL_TYPED_ARRAY_CLASS(Uint8Clamped) }; // The various typed array prototypes are supposed to 1) be normal objects, // 2) stringify to "[object <name of constructor>]", and 3) (Gecko-specific) // be xrayable. The first and second requirements mandate (in the absence of // @@toStringTag) a custom class. The third requirement mandates that each // prototype's class have the relevant typed array's cached JSProtoKey in them. // Thus we need one class with cached prototype per kind of typed array, with a // delegated ClassSpec. #define IMPL_TYPED_ARRAY_PROTO_CLASS(_type) \ { \ /* * Actually ({}).toString.call(Uint8Array.prototype) should throw, because * Uint8Array.prototype lacks the the typed array internal slots. (Same as * with %TypedArray%.prototype.) It's not clear this is desirable (see * above), but it's what we've always done, so keep doing it till we * implement @@toStringTag or ES6 changes. */ \ #_type "ArrayPrototype", \ JSCLASS_HAS_CACHED_PROTO(JSProto_##_type##Array), \ JS_NULL_CLASS_OPS, \ &TypedArrayObjectClassSpecs[Scalar::Type::_type] \ } const Class TypedArrayObject::protoClasses[Scalar::MaxTypedArrayViewType] = { IMPL_TYPED_ARRAY_PROTO_CLASS(Int8), IMPL_TYPED_ARRAY_PROTO_CLASS(Uint8), IMPL_TYPED_ARRAY_PROTO_CLASS(Int16), IMPL_TYPED_ARRAY_PROTO_CLASS(Uint16), IMPL_TYPED_ARRAY_PROTO_CLASS(Int32), IMPL_TYPED_ARRAY_PROTO_CLASS(Uint32), IMPL_TYPED_ARRAY_PROTO_CLASS(Float32), IMPL_TYPED_ARRAY_PROTO_CLASS(Float64), IMPL_TYPED_ARRAY_PROTO_CLASS(Uint8Clamped) }; /* static */ bool TypedArrayObject::isOriginalLengthGetter(Native native) { return native == TypedArray_lengthGetter; } bool js::IsTypedArrayConstructor(HandleValue v, uint32_t type) { switch (type) { case Scalar::Int8: return IsNativeFunction(v, Int8Array::class_constructor); case Scalar::Uint8: return IsNativeFunction(v, Uint8Array::class_constructor); case Scalar::Int16: return IsNativeFunction(v, Int16Array::class_constructor); case Scalar::Uint16: return IsNativeFunction(v, Uint16Array::class_constructor); case Scalar::Int32: return IsNativeFunction(v, Int32Array::class_constructor); case Scalar::Uint32: return IsNativeFunction(v, Uint32Array::class_constructor); case Scalar::Float32: return IsNativeFunction(v, Float32Array::class_constructor); case Scalar::Float64: return IsNativeFunction(v, Float64Array::class_constructor); case Scalar::Uint8Clamped: return IsNativeFunction(v, Uint8ClampedArray::class_constructor); case Scalar::MaxTypedArrayViewType: break; } MOZ_CRASH("unexpected typed array type"); } bool js::IsBufferSource(JSObject* object, SharedMem<uint8_t*>* dataPointer, size_t* byteLength) { if (object->is<TypedArrayObject>()) { TypedArrayObject& view = object->as<TypedArrayObject>(); *dataPointer = view.dataPointerEither().cast<uint8_t*>(); *byteLength = view.byteLength(); return true; } if (object->is<DataViewObject>()) { DataViewObject& view = object->as<DataViewObject>(); *dataPointer = view.dataPointerEither().cast<uint8_t*>(); *byteLength = view.byteLength(); return true; } if (object->is<ArrayBufferObject>()) { ArrayBufferObject& buffer = object->as<ArrayBufferObject>(); *dataPointer = buffer.dataPointerShared(); *byteLength = buffer.byteLength(); return true; } if (object->is<SharedArrayBufferObject>()) { SharedArrayBufferObject& buffer = object->as<SharedArrayBufferObject>(); *dataPointer = buffer.dataPointerShared(); *byteLength = buffer.byteLength(); return true; } return false; } template <typename CharT> bool js::StringIsTypedArrayIndex(const CharT* s, size_t length, uint64_t* indexp) { const CharT* end = s + length; if (s == end) { return false; } bool negative = false; if (*s == '-') { negative = true; if (++s == end) { return false; } } if (!IsAsciiDigit(*s)) { return false; } uint64_t index = 0; uint32_t digit = JS7_UNDEC(*s++); /* Don't allow leading zeros. */ if (digit == 0 && s != end) { return false; } index = digit; for (; s < end; s++) { if (!IsAsciiDigit(*s)) { return false; } digit = JS7_UNDEC(*s); /* Watch for overflows. */ if ((UINT64_MAX - digit) / 10 < index) { index = UINT64_MAX; } else { index = 10 * index + digit; } } if (negative) { *indexp = UINT64_MAX; } else { *indexp = index; } return true; } template bool js::StringIsTypedArrayIndex(const char16_t* s, size_t length, uint64_t* indexp); template bool js::StringIsTypedArrayIndex(const Latin1Char* s, size_t length, uint64_t* indexp); /* ES6 draft rev 34 (2015 Feb 20) 9.4.5.3 [[DefineOwnProperty]] step 3.c. */ bool js::DefineTypedArrayElement(JSContext* cx, HandleObject obj, uint64_t index, Handle<PropertyDescriptor> desc, ObjectOpResult& result) { MOZ_ASSERT(obj->is<TypedArrayObject>()); // These are all substeps of 3.b. // Steps i-iii are handled by the caller. // Steps iv-v. // We (wrongly) ignore out of range defines with a value. uint32_t length = obj->as<TypedArrayObject>().length(); if (index >= length) { if (obj->as<TypedArrayObject>().hasDetachedBuffer()) { return result.failSoft(JSMSG_TYPED_ARRAY_DETACHED); } return result.failSoft(JSMSG_BAD_INDEX); } // Step vi. if (desc.isAccessorDescriptor()) { return result.fail(JSMSG_CANT_REDEFINE_PROP); } // Step vii. if (desc.hasConfigurable() && desc.configurable()) { return result.fail(JSMSG_CANT_REDEFINE_PROP); } // Step viii. if (desc.hasEnumerable() && !desc.enumerable()) { return result.fail(JSMSG_CANT_REDEFINE_PROP); } // Step ix. if (desc.hasWritable() && !desc.writable()) { return result.fail(JSMSG_CANT_REDEFINE_PROP); } // Step x. if (desc.hasValue()) { // The following step numbers refer to 9.4.5.9 // IntegerIndexedElementSet. // Steps 1-2 are enforced by the caller. // Step 3. double numValue; if (!ToNumber(cx, desc.value(), &numValue)) { return false; } // Steps 4-5, 8-9. if (obj->as<TypedArrayObject>().hasDetachedBuffer()) { return result.fail(JSMSG_TYPED_ARRAY_DETACHED); } // Steps 10-16. TypedArrayObject::setElement(obj->as<TypedArrayObject>(), index, numValue); } // Step xii. return result.succeed(); } /* JS Friend API */ JS_FRIEND_API(bool) JS_IsTypedArrayObject(JSObject* obj) { obj = CheckedUnwrap(obj); return obj ? obj->is<TypedArrayObject>() : false; } JS_FRIEND_API(uint32_t) JS_GetTypedArrayLength(JSObject* obj) { obj = CheckedUnwrap(obj); if (!obj) { return 0; } return obj->as<TypedArrayObject>().length(); } JS_FRIEND_API(uint32_t) JS_GetTypedArrayByteOffset(JSObject* obj) { obj = CheckedUnwrap(obj); if (!obj) { return 0; } return obj->as<TypedArrayObject>().byteOffset(); } JS_FRIEND_API(uint32_t) JS_GetTypedArrayByteLength(JSObject* obj) { obj = CheckedUnwrap(obj); if (!obj) { return 0; } return obj->as<TypedArrayObject>().byteLength(); } JS_FRIEND_API(bool) JS_GetTypedArraySharedness(JSObject* obj) { obj = CheckedUnwrap(obj); if (!obj) { return false; } return obj->as<TypedArrayObject>().isSharedMemory(); } JS_FRIEND_API(js::Scalar::Type) JS_GetArrayBufferViewType(JSObject* obj) { obj = CheckedUnwrap(obj); if (!obj) { return Scalar::MaxTypedArrayViewType; } if (obj->is<TypedArrayObject>()) { return obj->as<TypedArrayObject>().type(); } if (obj->is<DataViewObject>()) { return Scalar::MaxTypedArrayViewType; } MOZ_CRASH("invalid ArrayBufferView type"); } JS_FRIEND_API(int8_t*) JS_GetInt8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Int8); *isSharedMemory = tarr->isSharedMemory(); return static_cast<int8_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isShared*/)); } JS_FRIEND_API(uint8_t*) JS_GetUint8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Uint8); *isSharedMemory = tarr->isSharedMemory(); return static_cast<uint8_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(uint8_t*) JS_GetUint8ClampedArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Uint8Clamped); *isSharedMemory = tarr->isSharedMemory(); return static_cast<uint8_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(int16_t*) JS_GetInt16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Int16); *isSharedMemory = tarr->isSharedMemory(); return static_cast<int16_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(uint16_t*) JS_GetUint16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Uint16); *isSharedMemory = tarr->isSharedMemory(); return static_cast<uint16_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(int32_t*) JS_GetInt32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Int32); *isSharedMemory = tarr->isSharedMemory(); return static_cast<int32_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(uint32_t*) JS_GetUint32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Uint32); *isSharedMemory = tarr->isSharedMemory(); return static_cast<uint32_t*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(float*) JS_GetFloat32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Float32); *isSharedMemory = tarr->isSharedMemory(); return static_cast<float*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); } JS_FRIEND_API(double*) JS_GetFloat64ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&) { obj = CheckedUnwrap(obj); if (!obj) { return nullptr; } TypedArrayObject* tarr = &obj->as<TypedArrayObject>(); MOZ_ASSERT((int32_t) tarr->type() == Scalar::Float64); *isSharedMemory = tarr->isSharedMemory(); return static_cast<double*>(tarr->dataPointerEither().unwrap(/*safe - caller sees isSharedMemory*/)); }
34.917857
121
0.601889
[ "object", "shape" ]
1a11b7eccb4c3b9efd9589f60dbd38a0fe88bdd7
1,861
cpp
C++
libadb/src/libadb/api/interactions/interactions.cpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
1
2022-03-10T15:14:13.000Z
2022-03-10T15:14:13.000Z
libadb/src/libadb/api/interactions/interactions.cpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
9
2022-03-07T21:00:08.000Z
2022-03-15T23:14:52.000Z
libadb/src/libadb/api/interactions/interactions.cpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
null
null
null
#include <libadb/api/interactions/interactions.hpp> #include <libadb/api/gateway/gateway-events.hpp> #include <libadb/api/utils/algorithms.hpp> #include <utility> using namespace adb::api; Interactions::Interactions(std::shared_ptr<GatewayEvents> events) : events_(events) { } std::unique_ptr<adb::types::Subscription> Interactions::subscribeToCommand(const std::string &cmdName, const std::vector<std::string> subCommandPath, CommandSubscriber subscriber) { return std::move(events_->subscribe<Interaction>(Event::INTERACTION_CREATE, [cmdName, subCommandPath, subscriber](auto ev, auto &interaction) { if (interaction.type != InteractionType::APPLICATION_COMMAND) return; if (!interaction.data.has_value()) return; auto data = std::static_pointer_cast<InteractionDataApplicationCommand>(interaction.data.value()); if (!data) return; if (data->name != cmdName) return; if (subCommandPath.empty()) { subscriber(interaction, *data, data->options); return; } if (!data->options.has_value()) return; auto *currentOptions = &data->options.value(); InteractionDataCommandOption *currentOption = nullptr; auto currentSub = subCommandPath.begin(); while (currentOptions && currentSub != subCommandPath.end()) { currentOption = findByName(*currentOptions, std::string{*currentSub}); if (!currentOption) break; currentSub++; currentOptions = currentOption->options.has_value() ? &currentOption->options.value() : nullptr; } if (!currentOption || currentSub != subCommandPath.end()) return; subscriber(interaction, *data, currentOption->options); })); }
37.979592
145
0.642128
[ "vector" ]
1a1e046f54c0fc806a03ec9c5d7105cc4583295f
22,993
cpp
C++
source/gameengine/Ketsji/KX_BlenderMaterial.cpp
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/gameengine/Ketsji/KX_BlenderMaterial.cpp
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/gameengine/Ketsji/KX_BlenderMaterial.cpp
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/** \file gameengine/Ketsji/KX_BlenderMaterial.cpp * \ingroup ketsji */ // ------------------------------------ // ... // ------------------------------------ #include "GL/glew.h" #include "KX_BlenderMaterial.h" #include "BL_Material.h" #include "KX_Scene.h" #include "KX_Light.h" #include "KX_GameObject.h" #include "KX_MeshProxy.h" #include "MT_Vector3.h" #include "MT_Vector4.h" #include "MT_Matrix4x4.h" #include "RAS_BucketManager.h" #include "RAS_MeshObject.h" #include "RAS_IRasterizer.h" #include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h" #include "GPU_draw.h" #include "STR_HashedString.h" // ------------------------------------ #include "DNA_object_types.h" #include "DNA_material_types.h" #include "DNA_image_types.h" #include "DNA_meshdata_types.h" #include "BKE_mesh.h" // ------------------------------------ #include "BLI_utildefines.h" #define spit(x) std::cout << x << std::endl; BL_Shader *KX_BlenderMaterial::mLastShader = NULL; BL_BlenderShader *KX_BlenderMaterial::mLastBlenderShader = NULL; //static PyObject *gTextureDict = 0; KX_BlenderMaterial::KX_BlenderMaterial() : PyObjectPlus(), RAS_IPolyMaterial(), mMaterial(NULL), mShader(0), mBlenderShader(0), mScene(NULL), mUserDefBlend(0), mModified(0), mConstructed(false), mPass(0) { } void KX_BlenderMaterial::Initialize( KX_Scene *scene, BL_Material *data, GameSettings *game) { RAS_IPolyMaterial::Initialize( data->texname[0], data->matname, data->materialindex, data->tile, data->tilexrep[0], data->tileyrep[0], data->alphablend, ((data->ras_mode &ALPHA)!=0), ((data->ras_mode &ZSORT)!=0), ((data->ras_mode &USE_LIGHT)!=0), ((data->ras_mode &TEX)), game ); mMaterial = data; mShader = 0; mBlenderShader = 0; mScene = scene; mUserDefBlend = 0; mModified = 0; mConstructed = false; mPass = 0; // -------------------------------- // RAS_IPolyMaterial variables... m_flag |= RAS_BLENDERMAT; m_flag |= (mMaterial->IdMode>=ONETEX)? RAS_MULTITEX: 0; m_flag |= ((mMaterial->ras_mode & USE_LIGHT)!=0)? RAS_MULTILIGHT: 0; m_flag |= (mMaterial->glslmat)? RAS_BLENDERGLSL: 0; m_flag |= ((mMaterial->ras_mode & CAST_SHADOW)!=0)? RAS_CASTSHADOW: 0; // figure max int enabled = mMaterial->num_enabled; int max = BL_Texture::GetMaxUnits(); mMaterial->num_enabled = enabled>=max?max:enabled; // test the sum of the various modes for equality // so we can ether accept or reject this material // as being equal, this is rather important to // prevent material bleeding for(int i=0; i<mMaterial->num_enabled; i++) { m_multimode += (mMaterial->flag[i] + mMaterial->blend_mode[i]); } m_multimode += mMaterial->IdMode+ (mMaterial->ras_mode & ~(USE_LIGHT)); } KX_BlenderMaterial::~KX_BlenderMaterial() { // cleanup work if (mConstructed) // clean only if material was actually used OnExit(); } MTFace* KX_BlenderMaterial::GetMTFace(void) const { // fonts on polys MT_assert(mMaterial->tface); return mMaterial->tface; } unsigned int* KX_BlenderMaterial::GetMCol(void) const { // fonts on polys return mMaterial->rgb; } void KX_BlenderMaterial::GetMaterialRGBAColor(unsigned char *rgba) const { if (mMaterial) { *rgba++ = (unsigned char) (mMaterial->matcolor[0]*255.0); *rgba++ = (unsigned char) (mMaterial->matcolor[1]*255.0); *rgba++ = (unsigned char) (mMaterial->matcolor[2]*255.0); *rgba++ = (unsigned char) (mMaterial->matcolor[3]*255.0); } else RAS_IPolyMaterial::GetMaterialRGBAColor(rgba); } Material *KX_BlenderMaterial::GetBlenderMaterial() const { return mMaterial->material; } Scene* KX_BlenderMaterial::GetBlenderScene() const { return mScene->GetBlenderScene(); } void KX_BlenderMaterial::ReleaseMaterial() { if (mBlenderShader) mBlenderShader->ReloadMaterial(); } void KX_BlenderMaterial::OnConstruction(int layer) { if (mConstructed) // when material are reused between objects return; if(mMaterial->glslmat) SetBlenderGLSLShader(layer); // for each unique material... int i; for(i=0; i<mMaterial->num_enabled; i++) { if( mMaterial->mapping[i].mapping & USEENV ) { if(!GLEW_ARB_texture_cube_map) { spit("CubeMap textures not supported"); continue; } if(!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) ) spit("unable to initialize image("<<i<<") in "<< mMaterial->matname<< ", image will not be available"); } else { if( mMaterial->img[i] ) { if( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 )) spit("unable to initialize image("<<i<<") in "<< mMaterial->matname<< ", image will not be available"); } } } mBlendFunc[0] =0; mBlendFunc[1] =0; mConstructed = true; } void KX_BlenderMaterial::EndFrame() { if(mLastBlenderShader) { mLastBlenderShader->SetProg(false); mLastBlenderShader = NULL; } if(mLastShader) { mLastShader->SetProg(false); mLastShader = NULL; } } void KX_BlenderMaterial::OnExit() { if( mShader ) { //note, the shader here is allocated, per unique material //and this function is called per face if(mShader == mLastShader) { mShader->SetProg(false); mLastShader = NULL; } delete mShader; mShader = 0; } if( mBlenderShader ) { if(mBlenderShader == mLastBlenderShader) { mBlenderShader->SetProg(false); mLastBlenderShader = NULL; } delete mBlenderShader; mBlenderShader = 0; } BL_Texture::ActivateFirst(); for(int i=0; i<mMaterial->num_enabled; i++) { BL_Texture::ActivateUnit(i); mTextures[i].DeleteTex(); mTextures[i].DisableUnit(); } if( mMaterial->tface ) GPU_set_tpage(mMaterial->tface, 1, mMaterial->alphablend); } void KX_BlenderMaterial::setShaderData( bool enable, RAS_IRasterizer *ras) { MT_assert(GLEW_ARB_shader_objects && mShader); int i; if( !enable || !mShader->Ok() ) { // frame cleanup. if(mShader == mLastShader) { mShader->SetProg(false); mLastShader = NULL; } ras->SetAlphaBlend(TF_SOLID); BL_Texture::DisableAllTextures(); return; } BL_Texture::DisableAllTextures(); mShader->SetProg(true); mLastShader = mShader; BL_Texture::ActivateFirst(); mShader->ApplyShader(); // for each enabled unit for(i=0; i<mMaterial->num_enabled; i++) { if(!mTextures[i].Ok()) continue; mTextures[i].ActivateTexture(); mTextures[0].SetMapping(mMaterial->mapping[i].mapping); } if(!mUserDefBlend) { ras->SetAlphaBlend(mMaterial->alphablend); } else { ras->SetAlphaBlend(TF_SOLID); ras->SetAlphaBlend(-1); // indicates custom mode // tested to be valid enums glEnable(GL_BLEND); glBlendFunc(mBlendFunc[0], mBlendFunc[1]); } } void KX_BlenderMaterial::setBlenderShaderData( bool enable, RAS_IRasterizer *ras) { if( !enable || !mBlenderShader->Ok() ) { ras->SetAlphaBlend(TF_SOLID); // frame cleanup. if(mLastBlenderShader) { mLastBlenderShader->SetProg(false); mLastBlenderShader= NULL; } else BL_Texture::DisableAllTextures(); return; } if(!mBlenderShader->Equals(mLastBlenderShader)) { ras->SetAlphaBlend(mMaterial->alphablend); if(mLastBlenderShader) mLastBlenderShader->SetProg(false); else BL_Texture::DisableAllTextures(); mBlenderShader->SetProg(true, ras->GetTime()); mLastBlenderShader= mBlenderShader; } } void KX_BlenderMaterial::setTexData( bool enable, RAS_IRasterizer *ras) { BL_Texture::DisableAllTextures(); if( !enable ) { ras->SetAlphaBlend(TF_SOLID); return; } BL_Texture::ActivateFirst(); if( mMaterial->IdMode == DEFAULT_BLENDER ) { ras->SetAlphaBlend(mMaterial->alphablend); return; } if( mMaterial->IdMode == TEXFACE ) { // no material connected to the object if( mTextures[0].Ok() ) { mTextures[0].ActivateTexture(); mTextures[0].setTexEnv(0, true); mTextures[0].SetMapping(mMaterial->mapping[0].mapping); ras->SetAlphaBlend(mMaterial->alphablend); } return; } int mode = 0,i=0; for(i=0; (i<mMaterial->num_enabled && i<MAXTEX); i++) { if( !mTextures[i].Ok() ) continue; mTextures[i].ActivateTexture(); mTextures[i].setTexEnv(mMaterial); mode = mMaterial->mapping[i].mapping; if(mode &USEOBJ) setObjectMatrixData(i, ras); else mTextures[i].SetMapping(mode); if(!(mode &USEOBJ)) setTexMatrixData( i ); } if(!mUserDefBlend) { ras->SetAlphaBlend(mMaterial->alphablend); } else { ras->SetAlphaBlend(TF_SOLID); ras->SetAlphaBlend(-1); // indicates custom mode glEnable(GL_BLEND); glBlendFunc(mBlendFunc[0], mBlendFunc[1]); } } void KX_BlenderMaterial::ActivatShaders( RAS_IRasterizer* rasty, TCachingInfo& cachingInfo)const { KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this); // reset... if(tmp->mMaterial->IsShared()) cachingInfo =0; if(mLastBlenderShader) { mLastBlenderShader->SetProg(false); mLastBlenderShader= NULL; } if (GetCachingInfo() != cachingInfo) { if (!cachingInfo) tmp->setShaderData(false, rasty); cachingInfo = GetCachingInfo(); if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) tmp->setShaderData(true, rasty); else tmp->setShaderData(false, rasty); if (mMaterial->ras_mode &TWOSIDED) rasty->SetCullFace(false); else rasty->SetCullFace(true); if ((mMaterial->ras_mode &WIRE) || (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) { if (mMaterial->ras_mode &WIRE) rasty->SetCullFace(false); rasty->SetLines(true); } else rasty->SetLines(false); ActivatGLMaterials(rasty); ActivateTexGen(rasty); } //ActivatGLMaterials(rasty); //ActivateTexGen(rasty); } void KX_BlenderMaterial::ActivateBlenderShaders( RAS_IRasterizer* rasty, TCachingInfo& cachingInfo)const { KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this); if(mLastShader) { mLastShader->SetProg(false); mLastShader= NULL; } if (GetCachingInfo() != cachingInfo) { if (!cachingInfo) tmp->setBlenderShaderData(false, rasty); cachingInfo = GetCachingInfo(); if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) tmp->setBlenderShaderData(true, rasty); else tmp->setBlenderShaderData(false, rasty); if (mMaterial->ras_mode &TWOSIDED) rasty->SetCullFace(false); else rasty->SetCullFace(true); if ((mMaterial->ras_mode &WIRE) || (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) { if (mMaterial->ras_mode &WIRE) rasty->SetCullFace(false); rasty->SetLines(true); } else rasty->SetLines(false); ActivatGLMaterials(rasty); mBlenderShader->SetAttribs(rasty, mMaterial); } } void KX_BlenderMaterial::ActivateMat( RAS_IRasterizer* rasty, TCachingInfo& cachingInfo )const { KX_BlenderMaterial *tmp = const_cast<KX_BlenderMaterial*>(this); if(mLastShader) { mLastShader->SetProg(false); mLastShader= NULL; } if(mLastBlenderShader) { mLastBlenderShader->SetProg(false); mLastBlenderShader= NULL; } if (GetCachingInfo() != cachingInfo) { if (!cachingInfo) tmp->setTexData( false,rasty ); cachingInfo = GetCachingInfo(); if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) tmp->setTexData( true,rasty ); else tmp->setTexData( false,rasty); if (mMaterial->ras_mode &TWOSIDED) rasty->SetCullFace(false); else rasty->SetCullFace(true); if ((mMaterial->ras_mode &WIRE) || (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) { if (mMaterial->ras_mode &WIRE) rasty->SetCullFace(false); rasty->SetLines(true); } else rasty->SetLines(false); ActivatGLMaterials(rasty); ActivateTexGen(rasty); } //ActivatGLMaterials(rasty); //ActivateTexGen(rasty); } bool KX_BlenderMaterial::Activate( RAS_IRasterizer* rasty, TCachingInfo& cachingInfo )const { if(GLEW_ARB_shader_objects && (mShader && mShader->Ok())) { if((mPass++) < mShader->getNumPass() ) { ActivatShaders(rasty, cachingInfo); return true; } else { if(mShader == mLastShader) { mShader->SetProg(false); mLastShader = NULL; } mPass = 0; return false; } } else if( GLEW_ARB_shader_objects && (mBlenderShader && mBlenderShader->Ok() ) ) { if(mPass++ == 0) { ActivateBlenderShaders(rasty, cachingInfo); return true; } else { mPass = 0; return false; } } else { if(mPass++ == 0) { ActivateMat(rasty, cachingInfo); return true; } else { mPass = 0; return false; } } } bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const { if(!RAS_IPolyMaterial::UsesLighting(rasty)) return false; if(mShader && mShader->Ok()) return true; else if(mBlenderShader && mBlenderShader->Ok()) return false; else return true; } void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const { if(mShader && GLEW_ARB_shader_objects) { mShader->Update(ms, rasty); } else if(mBlenderShader && GLEW_ARB_shader_objects) { int alphablend; mBlenderShader->Update(ms, rasty); /* we do blend modes here, because they can change per object * with the same material due to obcolor/obalpha */ alphablend = mBlenderShader->GetAlphaBlend(); if(ELEM3(alphablend, GEMAT_SOLID, GEMAT_ALPHA, GEMAT_ALPHA_SORT) && mMaterial->alphablend != GEMAT_SOLID) alphablend = mMaterial->alphablend; rasty->SetAlphaBlend(alphablend); } } void KX_BlenderMaterial::ActivatGLMaterials( RAS_IRasterizer* rasty )const { if(mShader || !mBlenderShader) { rasty->SetSpecularity( mMaterial->speccolor[0]*mMaterial->spec_f, mMaterial->speccolor[1]*mMaterial->spec_f, mMaterial->speccolor[2]*mMaterial->spec_f, mMaterial->spec_f ); rasty->SetShinyness( mMaterial->hard ); rasty->SetDiffuse( mMaterial->matcolor[0]*mMaterial->ref+mMaterial->emit, mMaterial->matcolor[1]*mMaterial->ref+mMaterial->emit, mMaterial->matcolor[2]*mMaterial->ref+mMaterial->emit, 1.0f); rasty->SetEmissive( mMaterial->matcolor[0]*mMaterial->emit, mMaterial->matcolor[1]*mMaterial->emit, mMaterial->matcolor[2]*mMaterial->emit, 1.0 ); rasty->SetAmbient(mMaterial->amb); } if (mMaterial->material) rasty->SetPolygonOffset(-mMaterial->material->zoffs, 0.0); } void KX_BlenderMaterial::ActivateTexGen(RAS_IRasterizer *ras) const { if(ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) { ras->SetAttribNum(0); if(mShader && GLEW_ARB_shader_objects) { if(mShader->GetAttribute() == BL_Shader::SHD_TANGENT) { ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, 0); ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, 1); ras->SetAttribNum(2); } } ras->SetTexCoordNum(mMaterial->num_enabled); for(int i=0; i<mMaterial->num_enabled; i++) { int mode = mMaterial->mapping[i].mapping; if (mode &USECUSTOMUV) { if (!mMaterial->mapping[i].uvCoName.IsEmpty()) ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_UV2, i); continue; } if( mode &(USEREFL|USEOBJ)) ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_GEN, i); else if(mode &USEORCO) ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_ORCO, i); else if(mode &USENORM) ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_NORM, i); else if(mode &USEUV) ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_UV1, i); else if(mode &USETANG) ras->SetTexCoord(RAS_IRasterizer::RAS_TEXTANGENT, i); else ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_DISABLE, i); } } } void KX_BlenderMaterial::setTexMatrixData(int i) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); if( GLEW_ARB_texture_cube_map && mTextures[i].GetTextureType() == GL_TEXTURE_CUBE_MAP_ARB && mMaterial->mapping[i].mapping & USEREFL) { glScalef( mMaterial->mapping[i].scale[0], -mMaterial->mapping[i].scale[1], -mMaterial->mapping[i].scale[2] ); } else { glScalef( mMaterial->mapping[i].scale[0], mMaterial->mapping[i].scale[1], mMaterial->mapping[i].scale[2] ); } glTranslatef( mMaterial->mapping[i].offsets[0], mMaterial->mapping[i].offsets[1], mMaterial->mapping[i].offsets[2] ); glMatrixMode(GL_MODELVIEW); } static void GetProjPlane(BL_Material *mat, int index,int num, float*param) { param[0]=param[1]=param[2]=param[3]=0.f; if( mat->mapping[index].projplane[num] == PROJX ) param[0] = 1.f; else if( mat->mapping[index].projplane[num] == PROJY ) param[1] = 1.f; else if( mat->mapping[index].projplane[num] == PROJZ) param[2] = 1.f; } void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras) { KX_GameObject *obj = (KX_GameObject*) mScene->GetObjectList()->FindValue(mMaterial->mapping[i].objconame); if(!obj) return; glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR ); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR ); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR ); GLenum plane = GL_EYE_PLANE; // figure plane gen float proj[4]= {0.f,0.f,0.f,0.f}; GetProjPlane(mMaterial, i, 0, proj); glTexGenfv(GL_S, plane, proj); GetProjPlane(mMaterial, i, 1, proj); glTexGenfv(GL_T, plane, proj); GetProjPlane(mMaterial, i, 2, proj); glTexGenfv(GL_R, plane, proj); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); const MT_Matrix4x4& mvmat = ras->GetViewMatrix(); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glScalef( mMaterial->mapping[i].scale[0], mMaterial->mapping[i].scale[1], mMaterial->mapping[i].scale[2] ); MT_Point3 pos = obj->NodeGetWorldPosition(); MT_Vector4 matmul = MT_Vector4(pos[0], pos[1], pos[2], 1.f); MT_Vector4 t = mvmat*matmul; glTranslatef( (float)(-t[0]), (float)(-t[1]), (float)(-t[2]) ); glMatrixMode(GL_MODELVIEW); } // ------------------------------------ void KX_BlenderMaterial::UpdateIPO( MT_Vector4 rgba, MT_Vector3 specrgb, MT_Scalar hard, MT_Scalar spec, MT_Scalar ref, MT_Scalar emit, MT_Scalar alpha ) { // only works one deep now mMaterial->speccolor[0] = (float)(specrgb)[0]; mMaterial->speccolor[1] = (float)(specrgb)[1]; mMaterial->speccolor[2] = (float)(specrgb)[2]; mMaterial->matcolor[0] = (float)(rgba[0]); mMaterial->matcolor[1] = (float)(rgba[1]); mMaterial->matcolor[2] = (float)(rgba[2]); mMaterial->alpha = (float)(alpha); mMaterial->hard = (float)(hard); mMaterial->emit = (float)(emit); mMaterial->spec_f = (float)(spec); mMaterial->ref = (float)(ref); } void KX_BlenderMaterial::SetBlenderGLSLShader(int layer) { if(!mBlenderShader) mBlenderShader = new BL_BlenderShader(mScene, mMaterial->material, layer); if(!mBlenderShader->Ok()) { delete mBlenderShader; mBlenderShader = 0; } } #ifdef WITH_PYTHON PyMethodDef KX_BlenderMaterial::Methods[] = { KX_PYMETHODTABLE( KX_BlenderMaterial, getShader ), KX_PYMETHODTABLE( KX_BlenderMaterial, getMaterialIndex ), KX_PYMETHODTABLE( KX_BlenderMaterial, setBlending ), {NULL,NULL} //Sentinel }; PyAttributeDef KX_BlenderMaterial::Attributes[] = { KX_PYATTRIBUTE_RO_FUNCTION("shader", KX_BlenderMaterial, pyattr_get_shader), KX_PYATTRIBUTE_RO_FUNCTION("material_index", KX_BlenderMaterial, pyattr_get_materialIndex), KX_PYATTRIBUTE_RW_FUNCTION("blending", KX_BlenderMaterial, pyattr_get_blending, pyattr_set_blending), { NULL } //Sentinel }; PyTypeObject KX_BlenderMaterial::Type = { PyVarObject_HEAD_INIT(NULL, 0) "KX_BlenderMaterial", sizeof(PyObjectPlus_Proxy), 0, py_base_dealloc, 0, 0, 0, 0, py_base_repr, 0,0,0,0,0,0,0,0,0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, 0,0,0,0,0,0,0, Methods, 0, 0, &PyObjectPlus::Type, 0,0,0,0,0,0, py_base_new }; PyObject* KX_BlenderMaterial::pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v); return self->PygetShader(NULL, NULL); } PyObject* KX_BlenderMaterial::pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v); return PyLong_FromSsize_t(self->GetMaterialIndex()); } PyObject* KX_BlenderMaterial::pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v); unsigned int* bfunc = self->getBlendFunc(); return Py_BuildValue("(ll)", (long int)bfunc[0], (long int)bfunc[1]); } int KX_BlenderMaterial::pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_BlenderMaterial* self= static_cast<KX_BlenderMaterial*>(self_v); PyObject* obj = self->PysetBlending(value, NULL); if(obj) { Py_DECREF(obj); return 0; } return -1; } KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()") { if( !GLEW_ARB_fragment_shader) { if(!mModified) spit("Fragment shaders not supported"); mModified = true; Py_RETURN_NONE; } if( !GLEW_ARB_vertex_shader) { if(!mModified) spit("Vertex shaders not supported"); mModified = true; Py_RETURN_NONE; } if(!GLEW_ARB_shader_objects) { if(!mModified) spit("GLSL not supported"); mModified = true; Py_RETURN_NONE; } else { // returns Py_None on error // the calling script will need to check if(!mShader && !mModified) { mShader = new BL_Shader(); mModified = true; } if(mShader && !mShader->GetError()) { m_flag &= ~RAS_BLENDERGLSL; mMaterial->SetSharedMaterial(true); mScene->GetBucketManager()->ReleaseDisplayLists(this); return mShader->GetProxy(); }else { // decref all references to the object // then delete it! // We will then go back to fixed functionality // for this material if(mShader) { delete mShader; /* will handle python de-referencing */ mShader=0; } } Py_RETURN_NONE; } PyErr_SetString(PyExc_ValueError, "material.getShader(): KX_BlenderMaterial, GLSL Error"); return NULL; } KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getMaterialIndex, "getMaterialIndex()") { return PyLong_FromSsize_t( GetMaterialIndex() ); } KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getTexture, "getTexture( index )" ) { // TODO: enable python switching return NULL; } KX_PYMETHODDEF_DOC( KX_BlenderMaterial, setTexture , "setTexture( index, tex)") { // TODO: enable python switching return NULL; } static unsigned int GL_array[11] = { GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA_SATURATE }; KX_PYMETHODDEF_DOC( KX_BlenderMaterial, setBlending , "setBlending( bge.logic.src, bge.logic.dest)") { unsigned int b[2]; if(PyArg_ParseTuple(args, "ii:setBlending", &b[0], &b[1])) { bool value_found[2] = {false, false}; for(int i=0; i<11; i++) { if(b[0] == GL_array[i]) { value_found[0] = true; mBlendFunc[0] = b[0]; } if(b[1] == GL_array[i]) { value_found[1] = true; mBlendFunc[1] = b[1]; } if(value_found[0] && value_found[1]) break; } if(!value_found[0] || !value_found[1]) { PyErr_SetString(PyExc_ValueError, "material.setBlending(int, int): KX_BlenderMaterial, invalid enum."); return NULL; } mUserDefBlend = true; Py_RETURN_NONE; } return NULL; } #endif // WITH_PYTHON
23.534289
109
0.69743
[ "object" ]
1a26ef6aa016fd95aa0b4dbf24d64e2b3e627b04
1,264
cpp
C++
src_extras/std_autocomp/extract.cpp
stahta01/Zinjal
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
[ "OML" ]
1
2019-03-24T00:58:59.000Z
2019-03-24T00:58:59.000Z
src_extras/std_autocomp/extract.cpp
stahta01/Zinjal
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
[ "OML" ]
null
null
null
src_extras/std_autocomp/extract.cpp
stahta01/Zinjal
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
[ "OML" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { if (argc<3) { cerr<<"ERROR: argc<3"<<endl; return 1; } ifstream fin(argv[1]); vector<string> v; string aux; while (getline(fin,aux)) v.push_back(aux); fin.close(); ofstream fout; int state=0; for(unsigned int i=0;i<v.size();i++) { string &s=v[i]; if (state==0) { if (s.find("Standard library header ")==0) { string header=s.substr(24); header=header.substr(1,header.size()-2); // system("pwd"); // cerr<<"Opening: \""<<string(argv[2])+"/"+header<<"\"\n"; // cerr<<(fout.is_open()?1:0)<<endl; fout.open((string(argv[2])+"/"+header).c_str(),ios::trunc); state=1; } } else if (state==1) { if (s.find("[edit] Synopsis")!=string::npos) state=2; else if (s.find("Edit section: Synopsis")!=string::npos) state=2; } else if (state==2) { if (s.find(" Retrieved from")==0) state=4; else if (s.find("[edit] Note")==0) state=3; else if (s.find("[edit]")!=0) fout<<s<<endl; // } else if (state==3) { // if (s.find(" Retrieved from")==0) state=4; // else cerr<<argv[1]<<": "<<s<<endl; } } if (state<2) cerr<<argv[1]<<": ERROR: state="<<state<<endl; return 0; }
27.478261
72
0.578323
[ "vector" ]
1a2737f0abcc908ec04f4149e65de47f37662973
809
cpp
C++
uva/uva_00394/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
null
null
null
uva/uva_00394/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
12
2019-09-04T10:38:24.000Z
2019-12-08T18:09:41.000Z
uva/uva_00394/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; typedef pair<int,int> bd; struct ArrDesc{ string name; int dim; vector<bd> bounds; }; int main() { int n; cin >> n; int x; cin >> x; vector<string> names(n); vector<vector<int>> nr; for(int i = 0; i < n; i++) { cin >> names[i]; vector<int> v; int base; cin >> base; v.push_back(base); int b; cin >> b; v.push_back(b); int d; cin >> d; v.push_back(d); for(int j = 0; j < d * 2; j++) { int low; cin >> low; v.push_back(low); int up; cin >> up; v.push_back(up); } nr.push_back(v); } return 0; }
13.948276
38
0.419036
[ "vector" ]
1a2a0eab44009218e50dc77f4cb9c83f6211f342
4,549
cpp
C++
src/stat_bench/reporter/console_reporter.cpp
MusicScience37/cpp-stat-bench
e9cac78d7d3c0fe123e0908122e3876f7a38a127
[ "Apache-2.0" ]
null
null
null
src/stat_bench/reporter/console_reporter.cpp
MusicScience37/cpp-stat-bench
e9cac78d7d3c0fe123e0908122e3876f7a38a127
[ "Apache-2.0" ]
null
null
null
src/stat_bench/reporter/console_reporter.cpp
MusicScience37/cpp-stat-bench
e9cac78d7d3c0fe123e0908122e3876f7a38a127
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 MusicScience37 (Kenta Kabashima) * * 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. */ /*! * \file * \brief Implementation of ConsoleReporter class. */ #include "stat_bench/reporter/console_reporter.h" #include <memory> #include <utility> #include <vector> #include <fmt/color.h> #include <fmt/format.h> #include "stat_bench/clock/monotone_clock_impl.h" #include "stat_bench/stat/custom_stat_output.h" #include "stat_bench/stat/statistics.h" namespace stat_bench { namespace reporter { ConsoleReporter::ConsoleReporter(std::FILE* file) : file_(file) {} void ConsoleReporter::experiment_starts( const clock::SystemTimePoint& time_stamp) { fmt::print(file_, FMT_STRING("Benchmark start at {}\n\n"), time_stamp); fmt::print(file_, FMT_STRING("Time resolution: {:.3e} sec.\n\n"), static_cast<double>(clock::impl::monotone_clock_res()) / static_cast<double>(clock::impl::monotone_clock_freq())); std::fflush(file_); } void ConsoleReporter::experiment_finished( const clock::SystemTimePoint& time_stamp) { fmt::print(file_, FMT_STRING("Benchmark finished at {}\n"), time_stamp); std::fflush(file_); } void ConsoleReporter::measurer_starts(const std::string& name) { fmt::print(file_, FMT_STRING("## {}\n\n"), name); std::fflush(file_); } void ConsoleReporter::measurer_finished(const std::string& name) { fmt::print(file_, "\n"); std::fflush(file_); } namespace { auto format_duration(double val) -> std::string { constexpr double sec_to_ms = 1e+3; constexpr double tol = 1e-3; if (val < tol) { return fmt::format(FMT_STRING("{:.3e}"), val * sec_to_ms); } return fmt::format(FMT_STRING("{:.3f}"), val * sec_to_ms); } } // namespace #define CONSOLE_TABLE_FORMAT "{:<50} {:>10} {:>8} {:>12} {:>12} " #define CONSOLE_TABLE_FORMAT_ERROR "{:<50} {}" void ConsoleReporter::group_starts(const std::string& name) { fmt::print(file_, FMT_STRING("### {}\n\n"), name); fmt::print(file_, FMT_STRING(CONSOLE_TABLE_FORMAT "{}\n"), "", "Iterations", "Samples", "Mean [ms]", "Max [ms]", "Custom Outputs (mean)"); fmt::print(file_, FMT_STRING("{:-<120}\n"), ""); std::fflush(file_); } void ConsoleReporter::group_finished(const std::string& /*name*/) { // no operation } void ConsoleReporter::case_starts( const bench::BenchmarkCaseInfo& /*case_info*/) { // no operation } void ConsoleReporter::case_finished( const bench::BenchmarkCaseInfo& /*case_info*/) { // no operation } void ConsoleReporter::measurement_succeeded( const measurer::Measurement& measurement) { fmt::print(file_, FMT_STRING(CONSOLE_TABLE_FORMAT), fmt::format(FMT_STRING("{} ({}) "), measurement.case_info().case_name(), measurement.cond().params()), measurement.iterations(), measurement.samples(), format_duration(measurement.durations_stat().mean()), format_duration(measurement.durations_stat().max())); for (std::size_t i = 0; i < measurement.custom_stat_outputs().size(); ++i) { fmt::print(file_, FMT_STRING("{}={:.3e}, "), measurement.custom_stat_outputs().at(i)->name(), measurement.custom_stat().at(i).mean()); } for (const auto& out : measurement.custom_outputs()) { fmt::print(file_, FMT_STRING("{}={:.3e}, "), out.first, out.second); } fmt::print(file_, "\n"); std::fflush(file_); } void ConsoleReporter::measurement_failed( const bench::BenchmarkCaseInfo& case_info, const bench::BenchmarkCondition& cond, const std::exception_ptr& error) { try { std::rethrow_exception(error); } catch (const std::exception& e) { fmt::print(file_, fmt::fg(fmt::color::red), FMT_STRING(CONSOLE_TABLE_FORMAT_ERROR), fmt::format( FMT_STRING("{} ({}) "), case_info.case_name(), cond.params()), e.what()); } fmt::print(file_, "\n"); std::fflush(file_); } } // namespace reporter } // namespace stat_bench
32.262411
80
0.662563
[ "vector" ]
1a325d47ff5f5f858294e0e4cdaf9b409085a17a
9,133
cpp
C++
sources/plugins/scs/scscodeeditor.cpp
ostis-ai/kbe
7105798d4edad0993a80f8275cec974badf74d55
[ "MIT" ]
5
2016-12-25T15:43:50.000Z
2021-04-02T13:54:14.000Z
sources/plugins/scs/scscodeeditor.cpp
ostis-ai/kbe
7105798d4edad0993a80f8275cec974badf74d55
[ "MIT" ]
11
2016-12-13T21:00:35.000Z
2021-03-11T09:11:05.000Z
sources/plugins/scs/scscodeeditor.cpp
ostis-ai/kbe
7105798d4edad0993a80f8275cec974badf74d55
[ "MIT" ]
12
2016-12-13T20:49:03.000Z
2021-12-14T15:42:37.000Z
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "scscodeeditor.h" #include <QPainter> #include <QTextBlock> #include <QAbstractItemView> #include <QScrollBar> #include <QStandardItemModel> #include <QDebug> #include "scscodeanalyzer.h" #include "scscodecompleter.h" #include "scsfindwidget.h" #include "scserrortablewidget.h" #include "scscodeerroranalyzer.h" #include "scsparserwrapper.h" #define SPACE_FOR_ERROR_LABEL 20 SCsCodeEditor::SCsCodeEditor(QWidget *parent, SCsErrorTableWidget *errorTable) : QPlainTextEdit(parent) , mErrorTable(errorTable) , mLastCursorPosition(0) , mIsTextInsert(false) { mLineNumberArea = new SCsLineNumberArea(this); mAnalyzer = new SCsCodeAnalyzer(this); mCompleter = new SCsCodeCompleter(this); mErrorAnalyzer = new SCsCodeErrorAnalyzer(this, mErrorTable); mCompleter->setWidget(this); mCompleter->setCompletionMode(QCompleter::PopupCompletion); mCompleter->setCaseSensitivity(Qt::CaseSensitive); mCompleter->setModelSorting(QCompleter::CaseInsensitivelySortedModel); mErrorPixmap = QPixmap(":scs/media/icons/error.png").scaledToHeight(15); connect(mCompleter, SIGNAL(activated(QModelIndex)), this, SLOT(insertCompletion(QModelIndex))); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); connect(this, SIGNAL(textChanged()), this, SLOT(updateAnalyzer())); connect(mErrorAnalyzer,SIGNAL(errorLines(QSet<int>)),this,SLOT(setErrorsLines(QSet<int>))); if (mErrorTable != NULL) connect(mErrorTable, SIGNAL(errorAt(int,int)), this, SLOT(moveTextCursor(int,int))); updateLineNumberAreaWidth(0); highlightCurrentLine(); setLineWrapMode(QPlainTextEdit::NoWrap); } void SCsCodeEditor::setDocumentPath(const QString &path) { Q_UNUSED(path); mAnalyzer->parse(toPlainText(), (QStandardItemModel*)mCompleter->model()); } int SCsCodeEditor::lineNumberAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; return space + SPACE_FOR_ERROR_LABEL; } void SCsCodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void SCsCodeEditor::updateLineNumberArea(const QRect &rect, int dy) { if (dy) mLineNumberArea->scroll(0, dy); else mLineNumberArea->update(0, rect.y(), mLineNumberArea->width(), rect.height()); if (rect.contains(viewport()->rect())) updateLineNumberAreaWidth(0); } void SCsCodeEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); mLineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); } void SCsCodeEditor::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> extraSelections; if (!isReadOnly()) { QTextEdit::ExtraSelection selection; QColor lineColor = QColor(Qt::yellow).lighter(160); selection.format.setBackground(lineColor); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = textCursor(); selection.cursor.clearSelection(); extraSelections.append(selection); } setExtraSelections(extraSelections); } void SCsCodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) { QPainter painter(mLineNumberArea); painter.fillRect(event->rect(), Qt::lightGray); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); int bottom = top + (int) blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(Qt::black); painter.drawText(0, top, mLineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number); if (isLineWithError(blockNumber+1)) painter.drawPixmap(4,top+2,mErrorPixmap); } block = block.next(); top = bottom; bottom = top + (int) blockBoundingRect(block).height(); ++blockNumber; } } QString SCsCodeEditor::textUnderCursor() { QTextCursor tc = textCursor(); tc.movePosition(QTextCursor::WordLeft, QTextCursor::KeepAnchor); return tc.selectedText(); } void SCsCodeEditor::keyPressEvent(QKeyEvent *e) { if ((e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Tab) || e->key() == Qt::Key_Backtab) { e->ignore(); return; } // if (e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_F) // { // mFinder->show(); // mFinder->setFocus(); // mCompleter->popup()->update(); // return; // } if (e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_R) updateErrorAnalyzer(); if (mCompleter->popup()->isVisible()) { switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: case Qt::Key_Tab: case Qt::Key_Backtab: e->ignore(); return; default: break; } } // if (e->key() == Qt::Key_Escape && mFinder->isVisible()) // { // mFinder->hide(); // return; // } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); if (!isShortcut) QPlainTextEdit::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (ctrlOrShift && e->text().isEmpty()) return; bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && ( hasModifier || e->text().isEmpty() || completionPrefix.length() < SCsCodeCompleter::MinCompletetionLength /* || !SCsCodeAnalyzer::isIdentifier(e->text().right(1)) || mAnalyzer->isInEmptyBlock(textCursor().position())*/ )) { mCompleter->popup()->hide(); return; } if (completionPrefix != mCompleter->completionPrefix()) { mCompleter->setCompletionPrefix(completionPrefix); mCompleter->popup()->setCurrentIndex(mCompleter->completionModel()->index(0, 0)); } QRect cr = cursorRect(); cr.setWidth(mCompleter->popup()->sizeHintForColumn(0) + mCompleter->popup()->verticalScrollBar()->sizeHint().width()); mCompleter->complete(cr); } void SCsCodeEditor::insertCompletion(QModelIndex index) { QTextCursor tc = textCursor(); QString templ = mCompleter->completionModel()->data(index, Qt::UserRole).toString(); if (templ.isEmpty()) templ = mCompleter->completionModel()->data(index, Qt::DisplayRole).toString(); quint32 extra = templ.length() - mCompleter->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(templ.right(extra)); setTextCursor(tc); mIsTextInsert = true; } void SCsCodeEditor::updateAnalyzer() { QStandardItemModel* completerModel = static_cast<QStandardItemModel*>(mCompleter->model()); QTextCursor tc = textCursor(); tc.select( QTextCursor::WordUnderCursor ); QString currentWord = tc.selectedText(); mLastCursorPosition = tc.position(); mAnalyzer->ignoreUpdate(currentWord); mAnalyzer->asynchUpdate(toPlainText(), completerModel); } void SCsCodeEditor::updateErrorAnalyzer() { QString text = document()->toPlainText(); mErrorAnalyzer->parse(text); //update(); } bool SCsCodeEditor::isLineWithError(int line) { return mErrorLines.contains(line); } void SCsCodeEditor::setErrorsLines(const QSet<int> &lines) { mErrorLines = lines; update(); } void SCsCodeEditor::moveTextCursor(int line, int charPos) { if (charPos<0) charPos = 0; if (line < 0) line = 0; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Start); cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, line-1); if (cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::MoveAnchor)) { if (cursor.columnNumber() < charPos) charPos = 0; } cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, charPos+1); setTextCursor(cursor); setFocus(Qt::ShortcutFocusReason); }
29.272436
104
0.6609
[ "model" ]
1a332c0aa57408d2863c35e2fe3e07ee4297fdda
8,058
cpp
C++
src/calculator.cpp
svenslaggare/termcalc
1bdc4c873003b636ccd73f86400d87808560b822
[ "MIT" ]
4
2019-06-11T11:17:08.000Z
2020-09-18T18:28:37.000Z
src/calculator.cpp
svenslaggare/termcalc
1bdc4c873003b636ccd73f86400d87808560b822
[ "MIT" ]
1
2017-11-11T11:32:27.000Z
2017-11-18T08:57:49.000Z
src/calculator.cpp
svenslaggare/termcalc
1bdc4c873003b636ccd73f86400d87808560b822
[ "MIT" ]
null
null
null
#include "calculator.h" #include "calculation/numberhelpers.h" #include "visitors/printvisitor.h" #include <cmath> #include <iostream> #include <fstream> #include <sstream> #include <algorithm> Calculator::Calculator(std::ostream& os) : mOutputStream(os), mEngine(os), mEnvironment(mEngine.defaultEnvironment()) { std::string leadingWhitespace = " "; mEngine.setEvalMode(ResultValueType::FLOAT); mEnvironment.setEvalMode(mEngine.evalMode()); mCommands = { { "help", [=](Args args) { mOutputStream << "Commands:" << std::endl; mOutputStream << leadingWhitespace << ":exit|:q|:quit Exits the program." << std::endl; mOutputStream << leadingWhitespace << ":mode Sets the evaluation mode: float (default), int or complex." << std::endl; mOutputStream << leadingWhitespace << ":display Sets to display the result in the given base." << std::endl; mOutputStream << leadingWhitespace << ":polar Sets if complex numbers are printed in polar form." << std::endl; mOutputStream << leadingWhitespace << ":vars Prints the defined variables." << std::endl; mOutputStream << leadingWhitespace << ":funcs Prints the defined functions." << std::endl; return false; } }, { "exit", [](Args args) { return true; } }, { "display", [&](Args args) { if (args.size() == 1) { setPrintNumBase(std::stoi(args[0])); } else { mOutputStream << "Expected one argument (int >= 2)." << std::endl; } return false; } }, { "mode", [&](Args args) { if (args.size() == 1) { ResultValueType evalMode = ResultValueType::NONE; if (args[0] == "float") { evalMode = ResultValueType::FLOAT; } else if (args[0] == "int") { evalMode = ResultValueType::INTEGER; } else if (args[0] == "complex") { evalMode = ResultValueType::COMPLEX; } else { mOutputStream << "'" << args[0] << "' is not a valid value. Valid values are: float, int and complex." << std::endl; } if (evalMode != ResultValueType::NONE) { setEvalMode(evalMode); } } else { mOutputStream << "Expected one argument (float or int)." << std::endl; } return false; } }, { "polar", [&](Args args) { if (args.size() == 1) { if (args[0] == "true" || args[0] == "1") { setPrintInPolar(true); } else if (args[0] == "false" || args[0] == "0") { setPrintInPolar(false); } else { mOutputStream << "Invalid value. Valid values are: true or false." << std::endl; } } else { mOutputStream << "Expected one argument (true or false)." << std::endl; } return false; } }, { "vars", [&](Args args) { for (auto var : mEnvironment.variables()) { mOutputStream << var.first << ": " << var.second << std::endl; } return false; } }, { "funcs", [this, leadingWhitespace](Args args) { //Compute the length of the longest function signature int maxFuncLength = 0; std::vector<std::string> funcStrs; for (auto& current : mEnvironment.functions()) { std::stringstream stream; auto& func = current.second; stream << func; funcStrs.push_back(stream.str()); stream.seekg(0, std::ios::end); maxFuncLength = std::max(maxFuncLength, (int)stream.tellg()); } maxFuncLength += 3; std::size_t i = 0; bool anyUserDefined = false; mOutputStream << "Built-in:" << std::endl; for (auto& current : mEnvironment.functions()) { auto& func = current.second; if (!func.isUserDefined()) { auto funcStr = funcStrs[i]; std::string spaceStr(maxFuncLength - funcStr.length(), ' '); mOutputStream << leadingWhitespace << funcStr << spaceStr << func.infoText() << std::endl; } else { anyUserDefined = true; } i++; } //Check if any user defined functions if (anyUserDefined) { mOutputStream << "User defined:" << std::endl; i = 0; for (auto& current : mEnvironment.functions()) { auto& func = current.second; if (func.isUserDefined()) { auto funcStr = funcStrs[i]; // mOutStream << leadingWhitespace << funcStr << " = " << func.body()->toString() << std::endl; mOutputStream << leadingWhitespace << funcStr << " = " << PrintVisitor::toString(mEngine, func.userFunction()->body()) << std::endl; } i++; } } return false; } }, }; //Aliases mCommands["q"] = mCommands["exit"]; mCommands["quit"] = mCommands["exit"]; mCommands["h"] = mCommands["help"]; } namespace { const std::vector<std::string> subscripts { "\xe2\x82\x80", "\xe2\x82\x81", "\xe2\x82\x82", "\xe2\x82\x83", "\xe2\x82\x84", "\xe2\x82\x85", "\xe2\x82\x86", "\xe2\x82\x87", "\xe2\x82\x88", "\xe2\x82\x89" }; //Returns the given number as a subscript std::string getSubscript(std::int64_t num) { std::string str = std::to_string(num); std::string subscriptStr; for (char c : str) { subscriptStr += subscripts[c - '0']; } return subscriptStr; } //Splits the given string std::vector<std::string> splitString(std::string str, const std::string& delimiter) { std::vector<std::string> parts; std::size_t pos = 0; std::string token; while ((pos = str.find(delimiter)) != std::string::npos) { token = str.substr(0, pos); parts.push_back(token); str.erase(0, pos + delimiter.length()); } parts.push_back(str); return parts; } } void Calculator::setPrintNumBase(int base) { try { if (base >= 2 && base <= 36) { mPrintNumBase = base; } else { mOutputStream << "The base must be >= 2 and <= 36." << std::endl; } } catch (std::exception& e) { mOutputStream << "The base must be an integer." << std::endl; } } void Calculator::setEvalMode(ResultValueType evalMode) { mEngine.setEvalMode(evalMode); mEnvironment.setEvalMode(evalMode); } void Calculator::setPrintInPolar(bool printInPolar) { mPrintInPolar = printInPolar; } void Calculator::loadFile(const std::string& fileName, bool printIfNotFound) { std::ifstream stream(fileName); if (stream.is_open()) { std::string line; while (!stream.eof()) { std::getline(stream, line); execute(line, false); } } else if (printIfNotFound) { mOutputStream << "Could not open the file '" << fileName << "'." << std::endl; } } bool Calculator::execute(const std::string& line, bool printResult) { if (line.size() > 1 && line[0] == ':') { auto parts = splitString(line.substr(1), " "); std::string cmd = parts[0]; if (mCommands.count(cmd) > 0) { parts.erase(parts.begin()); return mCommands[cmd](parts); } else { mOutputStream << "There exists no command called '" + cmd + "'. Type ':help' for a list of commands." << std::endl; } return false; } if (line.empty()) { return false; } try { auto res = mEngine.evaluate(line, mEnvironment); if (res.type() != ResultValueType::NONE) { if (printResult) { if (res.type() == ResultValueType::INTEGER) { switch (mPrintNumBase) { case 2: mOutputStream << NumberHelpers::toBase(res.intValue(), 2, "0b") << std::endl; break; case 10: mOutputStream << res.intValue() << std::endl; break; case 16: mOutputStream << NumberHelpers::toBase(res.intValue(), 16, "0x") << std::endl; break; default: std::string baseSubscript = "_" + std::to_string(mPrintNumBase); #ifdef __unix__ baseSubscript = getSubscript(mPrintNumBase); #endif mOutputStream << NumberHelpers::toBase(res.intValue(), mPrintNumBase) << baseSubscript << std::endl; break; } } else if (res.type() == ResultValueType::COMPLEX && mPrintInPolar) { mOutputStream << std::abs(res.complexValue()) << " * e^(" << std::arg(res.complexValue()) << "i)" << std::endl; } else { mOutputStream << res << std::endl; } mEnvironment.set("ans", res); } } } catch (std::exception& e) { mOutputStream << "Error: " << e.what() << std::endl; } return false; }
27.882353
134
0.60201
[ "vector" ]
1a3397b23ffee583d3dd32f6cbefc6de29094a3a
3,301
hpp
C++
CmnIP/module/group/inc/group/images_combined.hpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/module/group/inc/group/images_combined.hpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/module/group/inc/group/images_combined.hpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
/** * @file organized_images.hpp * @brief Header to display some organized images * * @section LICENSE * * 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 AUTHOR/AUTHORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Alessandro Moro <alessandromoro.italy@gmail.com> * @bug No known bugs. * @version 1.0.0.0 * */ #ifndef CMNIP_GROUP_IMAGESCOMBINED_HPP__ #define CMNIP_GROUP_IMAGESCOMBINED_HPP__ #include <map> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" namespace CmnIP { namespace group { /*! Class to combine multiple images together and make a single image \brief Combine multiple images together. */ class ImagesCombined { public: /** This function put together several images. @param[in] v_images Vector with the images to group. @param[in] nx Number of images in the horizontal axe. The value must be always positive. @param[in] ny Number of images in the vertical axe. The value must be always positive. @param[in] width Width of the output image. @param[in] height Height of the output image. @return Return the grouped images. */ static cv::Mat combine(std::vector<cv::Mat> &v_images, int nx, int ny, int width, int height); /** This function put together several images. @param[in] v_images Vector with the images to group. @param[in] nx Number of images in the horizontal axe. The value must be always positive. @param[in] ny Number of images in the vertical axe. The value must be always positive. @param[in] v_images_width Width of the input images. The size is already defined. @param[in] v_images_height Height of the input images. The size is already defined. @param[in] width Width of the output image. @param[in] height Height of the output image. @return Return the grouped images. */ static cv::Mat combine(std::vector<cv::Mat> &v_images, int nx, int ny, int v_images_width, int v_images_height, int img_w, int img_h); /** Compose a set of images. Size of the image must be equal to size All the images in input are sum together. Only the points not black are put together. It preserve the original intensity and color. */ static cv::Mat compose(std::vector<cv::Mat> &v_compose, cv::Size &size); /** Convert a map of images with title, in a big image @param[in] m_images Map of images. First: image title, Second: image @param[out] composed image */ static void map_images_to_image(const std::map<std::string, cv::Mat > &m_images, cv::Mat &out, cv::Point &position, int format, float size, cv::Scalar &color); }; } // namespace group } // namespace CmnIP #endif /* CMNIP_GROUP_IMAGESCOMBINED_HPP__ */
34.747368
89
0.750985
[ "vector" ]
1a45c1a6f958cb6dc1ea1ceeaa882f91c4391e53
5,286
cpp
C++
source/omni/core/model/if_statement.cpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
33
2015-03-21T04:12:45.000Z
2021-04-18T21:44:33.000Z
source/omni/core/model/if_statement.cpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
null
null
null
source/omni/core/model/if_statement.cpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
2
2016-03-05T12:57:05.000Z
2017-09-12T10:11:52.000Z
#include <omni/core/model/if_statement.hpp> #include <omni/core/context.hpp> #include <omni/core/model/expression.hpp> #include <omni/core/model/block.hpp> #include <llvm/IR/BasicBlock.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/NoFolder.h> // See meta_info.cpp for initialization. namespace omniMetaImpl { extern omni::core::model::meta_info if_statementMetaInfo; } /** Initializes this if_statement with the given condition and the given true- and elseBlocks. @param condition The condition depending on which either the trueBlock or the elseBlock will be executed. The condition must be provided. @param trueBlock The block that will be executed when the condition is true. The trueBlock must be provided. @param elseBlock The block that will be executed when the condition is false. The elseBlock is optional and can be nullptr. **/ omni::core::model::if_statement::if_statement (std::shared_ptr <expression> condition, std::shared_ptr <block> trueBlock, std::shared_ptr <block> elseBlock) : statement () { setCondition (condition); setTrueBlock (trueBlock); setElseBlock (elseBlock); } omni::core::model::meta_info & omni::core::model::if_statement::getStaticMetaInfo () { return omniMetaImpl::if_statementMetaInfo; } omni::core::model::meta_info & omni::core::model::if_statement::getMetaInfo () const { return getStaticMetaInfo (); } omni::core::domain omni::core::model::if_statement::getDomain () const { return domain::if_statement; } void omni::core::model::if_statement::setCondition (std::shared_ptr <omni::core::model::expression> condition) { setComponent (domain::expression, "condition", condition); } /** @return Returns the condition depending on which either the trueBlock or the elseBlock will be excuted. **/ std::shared_ptr <omni::core::model::expression> omni::core::model::if_statement::getCondition () { return getComponentAs <expression> (domain::expression, "condition"); } /** @return Returns the condition depending on which either the trueBlock or the elseBlock will be excuted. **/ const std::shared_ptr <omni::core::model::expression> omni::core::model::if_statement::getCondition () const { return getComponentAs <expression> (domain::expression, "condition"); } void omni::core::model::if_statement::setTrueBlock (std::shared_ptr <omni::core::model::block> trueBlock) { setComponent (domain::block, "trueBlock", trueBlock); } /** @return Returns the block that will be execute when the condition is true. Is never nullptr. **/ std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getTrueBlock () { return getComponentAs <block> (domain::block, "trueBlock"); } /** @return Returns the block that will be execute when the condition is true. Is never nullptr. **/ const std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getTrueBlock () const { return getComponentAs <block> (domain::block, "trueBlock"); } void omni::core::model::if_statement::setElseBlock (std::shared_ptr <omni::core::model::block> elseBlock) { setComponent (domain::block, "elseBlock", elseBlock); } /** @return Returns the block that will be execute when the condition is false. Can be nullptr. **/ std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getElseBlock () { return getComponentAs <block> (domain::block, "elseBlock"); } /** @return Returns the block that will be execute when the condition is false. Can be nullptr. **/ const std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getElseBlock () const { return getComponentAs <block> (domain::block, "elseBlock"); } /** @internal **/ omni::core::statement_emit_result omni::core::model::if_statement::llvmEmit (llvm::BasicBlock * llvmBasicBlock) { llvm::BasicBlock * llvmTrueBlock = getTrueBlock ()->llvmEmit (llvmBasicBlock).getContinueBlock (); llvm::BasicBlock * llvmFalseBlock = nullptr; bool terminatorNeeded = false; std::shared_ptr <block> elseBlock = getElseBlock (); if (elseBlock != nullptr) { llvmFalseBlock = elseBlock->llvmEmit (llvmBasicBlock).getContinueBlock (); if (llvmFalseBlock->getTerminator () == nullptr) { terminatorNeeded = true; } } if (llvmTrueBlock->getTerminator () == nullptr) { terminatorNeeded = true; } llvm::BasicBlock * result = llvmBasicBlock; if (terminatorNeeded) { result = llvm::BasicBlock::Create (llvmBasicBlock->getContext (), "", llvmBasicBlock->getParent ()); if (llvmTrueBlock->getTerminator () == nullptr) { llvm::IRBuilder <true, llvm::NoFolder> builder (llvmTrueBlock); builder.CreateBr (result); } if (llvmFalseBlock != nullptr && llvmFalseBlock->getTerminator () == nullptr) { llvm::IRBuilder <true, llvm::NoFolder> builder (llvmFalseBlock); builder.CreateBr (result); } } llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock); builder.CreateCondBr (getCondition ()->llvmEmit (llvmBasicBlock).getValue (), llvmTrueBlock, llvmFalseBlock); return statement_emit_result (result, nullptr); }
35.006623
137
0.701665
[ "model" ]
1a4898dcbaebdf0e6ac78272b70d23059fbb64f6
5,213
cpp
C++
examples/03-pruning.cpp
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
1
2020-05-08T08:55:55.000Z
2020-05-08T08:55:55.000Z
examples/03-pruning.cpp
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
1
2020-01-16T23:22:52.000Z
2020-01-16T23:22:52.000Z
examples/03-pruning.cpp
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
2
2020-07-01T01:35:55.000Z
2022-03-09T14:58:27.000Z
#include <Rcpp.h> #include "../include/pruner.hpp" #include "03-pruning.hpp" using namespace Rcpp; class TreeData { public: uint nstates; uint n; uint nfuns; // Annotations pruner::vv_uint A; pruner::v_uint Ntype; // Temporal storage ---------------------------------------------------------- vv_uint states; vv_dbl PSI, MU; vv_dbl Pr; v_dbl Pi; // Model parameters v_dbl mu, psi, eta; double pi; double ll; void set_mu(const v_dbl & mu) {prob_mat(mu, this->MU);return;} void set_psi(const v_dbl & psi) {prob_mat(psi, this->PSI);return;} void set_eta(const v_dbl & eta) {this->eta = eta;return;} void set_pi(double pi) {root_node_pr(this->Pi, pi, states);return;} // Destructor and constructor ------------------------------------------------ ~TreeData() {}; TreeData(vv_uint A, v_uint Ntype) { // Initializing data this->A = A; this->Ntype = Ntype; // Getting meta info, and initializing containers this->nfuns = A[0].size(); this->n = A.size(); this->states = states_mat(this->nfuns); this->nstates = this->states.size(); this->Pr = new_vector_array(this->n, this->nstates, 1.0); // Initializing parameter containers mu.resize(2u, 0.0); psi.resize(2u, 0.0); eta.resize(2u, 0.0); Pi.resize(nstates, 0.0); pi = 0.0; MU = prob_mat(mu); PSI = prob_mat(psi); ll = 0.0; }; }; void aphylo( TreeData * D, pruner::TreeIterator<TreeData> & n ) { if (n.is_tip()) { // Iterating through the states for (uint s = 0u; s < D->states.size(); ++s) { // Throught the functions D->Pr[*n][s] = 1.0; // Initializing for (uint p = 0u; p < D->nfuns; ++p) { // ETA PARAMETER if (D->A[*n][p] == 9u) { D->Pr[*n][s] *= (1.0 - D->eta[0u]) * D->PSI[D->states[s][p]][0u] + (1.0 - D->eta[1u]) * D->PSI[D->states[s][p]][1u] ; } else { D->Pr[*n][s] *= D->PSI[D->states[s][p]][D->A[*n][p]]* D->eta[D->A[*n][p]]; } } } } else { v_uint::const_iterator o_n; uint p, s_n, p_n; double offspring_ll, s_n_sum; // Looping through states for (uint s = 0u; s < D->nstates; ++s) { // Now through offspring D->Pr[*n][s] = 1.0; for (o_n = n.begin_off(); o_n != n.end_off(); ++o_n) { // Offspring state integration offspring_ll = 0.0; for (s_n = 0u; s_n < D->nstates; ++s_n) { s_n_sum = 1.0; for (p_n = 0u; p_n < D->nfuns; ++p_n) s_n_sum *= D->MU[D->states[s][p]][D->states[s_n][p]]; // Multiplying by off's probability offspring_ll += (s_n_sum) * D->Pr[*o_n][s_n]; } // Getting the joint conditional. D->Pr[*n][s] *= offspring_ll; } } // Computing the joint likelihood if (*n == n.back()) { D->ll = 0.0; for (uint s = 0; s < D->nstates; ++s) D->ll += D->Pi[s] * D->Pr[*n][s]; } } return; } class AphyloPruner: public pruner::Tree<TreeData> { public: TreeData D; AphyloPruner( const pruner::vv_uint & A, const pruner::v_uint & Ntype, const pruner::v_uint & source, const pruner::v_uint & target, pruner::uint & res ) : D(A, Ntype), Tree(source, target, res) { this->args = &D; this->fun = aphylo; return; }; ~AphyloPruner() { this->args = nullptr; } }; // Now the fun begins ---------------------------------------------------------- // [[Rcpp::export]] SEXP tree_new( const vv_uint & edgelist, const vv_uint & A, const v_uint & Ntype ) { // Initializing the tree uint res; Rcpp::XPtr< AphyloPruner > xptr( new AphyloPruner(A, Ntype, edgelist[0], edgelist[1], res), true); xptr->print(false); return wrap(xptr); } // [[Rcpp::export]] SEXP tree_print(SEXP tree_ptr) { Rcpp::XPtr< pruner::Tree<TreeData> > p(tree_ptr); p->print(); return tree_ptr; } // [[Rcpp::export]] List tree_ll( SEXP tree_ptr, const v_dbl & mu, const v_dbl & psi, const v_dbl & eta, const double & pi ) { Rcpp::XPtr< pruner::Tree<TreeData> > p(tree_ptr); // Setting the parameters p->args->set_mu(mu); p->args->set_psi(psi); p->args->set_pi(pi); p->args->set_eta(eta); p->prune_postorder(); return List::create( _["Pr"] = wrap(p->args->Pr), _["ll"] = wrap(p->args->ll) ); } /***R set.seed(1) dat <- aphylo::raphylo(50) A <- rbind(dat$tip.annotation, dat$node.annotation)[,1] mu <- c(.1, .05) psi <- c(.2, .07) eta <- c(.8, .9) Pi <- .5 tree_ptr <- tree_new( edgelist = with(dat$tree, list(edge[,1] - 1, edge[,2] - 1)), A = as.list(A), Ntype = A ) aphylo_ll <- aphylo::LogLike microbenchmark::microbenchmark( new = tree_ll(tree_ptr, mu = mu, psi = psi, eta = eta, pi = Pi), old = aphylo_ll(dat, psi = psi, mu_d = mu, mu_s = mu, Pi = Pi, eta = eta), times = 100, unit = "relative" ) */
21.191057
80
0.50681
[ "model" ]
1a4932690e81c4dcdd37997640d958efa8a5bd34
40,937
hpp
C++
src/api/dcps/isocpp/include/spec/dds/core/policy/TCorePolicy.hpp
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
133
2017-11-09T02:10:00.000Z
2022-03-29T09:45:10.000Z
src/api/dcps/isocpp/include/spec/dds/core/policy/TCorePolicy.hpp
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
131
2017-11-07T14:48:43.000Z
2022-03-13T15:30:47.000Z
src/api/dcps/isocpp/include/spec/dds/core/policy/TCorePolicy.hpp
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
94
2017-11-09T02:26:19.000Z
2022-02-24T06:38:25.000Z
#ifndef OMG_TDDS_CORE_POLICY_CORE_POLICY_HPP_ #define OMG_TDDS_CORE_POLICY_CORE_POLICY_HPP_ /* Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Corp. * Copyright 2010, Real-Time Innovations, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <dds/core/detail/conformance.hpp> #include <dds/core/LengthUnlimited.hpp> #include <dds/core/Value.hpp> #include <dds/core/policy/PolicyKind.hpp> //============================================================================== // DDS Policy Classes namespace dds { namespace core { namespace policy { //============================================================================== /** * \copydoc DCPS_QoS_UserData */ template <typename D> class TUserData : public dds::core::Value<D> { public: /** * Creates a UserData QoS instance with an empty UserData */ TUserData(); /** * Creates a UserData QoS instance * * @param sequence the sequence of octets */ explicit TUserData(const dds::core::ByteSeq& sequence); /** * Creates a UserData QoS instance * * @param value_begin a pointer to the beginning of a sequence * of octets * @param value_end a pointer to the end of a sequence * of octets */ TUserData(const uint8_t* value_begin, const uint8_t* value_end); /** * Copies a UserData QoS instance * * @param other the UserData QoS instance to copy */ TUserData(const TUserData& other); public: /** * Sets the sequence * * @param sequence a sequence of octets */ TUserData& value(const dds::core::ByteSeq& sequence); /** * Sets the sequence * * @param begin an iterator pointing to the beginning of a sequence * of octets * @param end an iterator pointing to the end of a sequence of octets */ template <typename OCTET_ITER> TUserData& value(OCTET_ITER begin, OCTET_ITER end); /** * Gets the sequence * * @return a sequence of octets */ const dds::core::ByteSeq value() const; /** * Gets a pointer to the first octet in the sequence * * @return a pointer to the first octet in the sequence */ const uint8_t* begin() const; /** * Gets a pointer to the last octet in the sequence * * @return a pointer to the first octet in the sequence */ const uint8_t* end() const; }; //============================================================================== /** * \copydoc DCPS_QoS_GroupData */ template <typename D> class TGroupData : public dds::core::Value<D> { public: /** * Creates a GroupData QoS instance */ TGroupData(); /** * Creates a GroupData QoS instance * * @param sequence the sequence of octets representing the GroupData */ explicit TGroupData(const dds::core::ByteSeq& sequence); /** * Copies a GroupData QoS instance * * @param other the GroupData QoS instance to copy */ TGroupData(const TGroupData& other); /** * Creates a GroupData QoS instance * * @param value_begin a pointer to the beginning of a sequence * of octets * @param value_end a pointer to the end of a sequence * of octets */ TGroupData(const uint8_t* value_begin, const uint8_t* value_end); public: /** * Set the sequence * * @param sequence a sequence of octets */ TGroupData& value(const dds::core::ByteSeq& sequence); /** * Set the sequence * * @param begin an iterator pointing to the beginning of a sequence * of octets * @param end an iterator pointing to the end of a sequence of octets */ template <typename OCTET_ITER> TGroupData& value(OCTET_ITER begin, OCTET_ITER end); /** * Get the sequence * * @return a sequence of octets */ const dds::core::ByteSeq value() const; /** * Gets a pointer to the first octet in the sequence * * @return a pointer to the first octet in the sequence */ const uint8_t* begin() const; /** * Gets a pointer to the last octet in the sequence * * @return a pointer to the last octet in the sequence */ const uint8_t* end() const; }; //============================================================================== /** * \copydoc DCPS_QoS_TopicData */ template <typename D> class TTopicData : public dds::core::Value<D> { public: /** * Creates a TopicData QoS instance */ TTopicData(); /** * Creates a TopicData QoS instance * * @param sequence the sequence of octets representing the TopicData */ explicit TTopicData(const dds::core::ByteSeq& sequence); /** * Copies a TopicData QoS instance * * @param other the TopicData QoS instance to copy */ TTopicData(const TTopicData& other); /** * Creates a TopicData QoS instance * * @param value_begin a pointer to the beginning of a sequence * of octets * @param value_end a pointer to the end of a sequence * of octets */ TTopicData(const uint8_t* value_begin, const uint8_t* value_end); public: /** * Set the sequence * * @param sequence a sequence of octets */ TTopicData& value(const dds::core::ByteSeq& sequence); /** * Set the sequence * * @param begin an iterator pointing to the beginning of a sequence * of octets * @param end an iterator pointing to the end of a sequence of octets */ template <typename OCTET_ITER> TTopicData& value(OCTET_ITER begin, OCTET_ITER end); /** * Get the sequence * * @return a sequence of octets */ const dds::core::ByteSeq value() const; /** * Gets a pointer to the first octet in the sequence * * @return a pointer to the first octet in the sequence */ const uint8_t* begin() const; /** * Gets a pointer to the last octet in the sequence * * @return a pointer to the last octet in the sequence */ const uint8_t* end() const; }; //============================================================================== /** * \copydoc DCPS_QoS_EntityFactory */ template <typename D> class TEntityFactory : public dds::core::Value<D> { public: /** * Creates an EntityFactory QoS instance * * @param autoenable_created_entities boolean indicating whether * created Entities should be automatically enabled */ explicit TEntityFactory(bool autoenable_created_entities = true); /** * Copies an EntityFactory QoS instance * * @param other the EntityFactory QoS instance to copy */ TEntityFactory(const TEntityFactory& other); public: /** * Sets a boolean indicating whether created Entities should be * automatically enabled * * @param autoenable_created_entities boolean indicating whether * created Entities should be automatically enabled */ TEntityFactory& autoenable_created_entities(bool autoenable_created_entities); /** * Gets a boolean indicating whether Entities should be automatically enabled * * @return boolean indicating whether created Entities should be automatically * enabled */ bool autoenable_created_entities() const; public: /** * @return an EntityFactory QoS instance with autoenable_created_entities * set to true */ static TEntityFactory AutoEnable(); /** * @return an EntityFactory QoS instance with autoenable_created_entities * set to false */ static TEntityFactory ManuallyEnable(); }; //============================================================================== /** * \copydoc DCPS_QoS_TransportPriority */ template <typename D> class TTransportPriority : public dds::core::Value<D> { public: /** * Creates a TransportPriority QoS instance * * @param priority the priority value */ explicit TTransportPriority(int32_t priority = 0); /** * Copies a TransportPriority QoS instance * * @param other the TransportPriority QoS instance to copy */ TTransportPriority(const TTransportPriority& other); public: /** * Sets the priority value * * @param priority the priority value */ TTransportPriority& value(int32_t priority); /** * Gets the priority value * * @return the priority value */ int32_t value() const; }; //============================================================================== /** * \copydoc DCPS_QoS_Lifespan */ template <typename D> class TLifespan : public dds::core::Value<D> { public: /** * Creates a Lifespan QoS instance * * @param duration Lifespan expiration duration */ explicit TLifespan(const dds::core::Duration& duration = dds::core::Duration::infinite()); /** * Copies a Lifespan QoS instance * * @param other the Lifespan QoS instance to copy */ TLifespan(const TLifespan& other); public: /** * Sets the expiration duration * * @param duration expiration duration */ TLifespan& duration(const dds::core::Duration& duration); /** * Gets the expiration duration * * @return expiration duration */ const dds::core::Duration duration() const; }; //============================================================================== /** * \copydoc DCPS_QoS_Deadline */ template <typename D> class TDeadline : public dds::core::Value<D> { public: /** * Creates a Deadline QoS instance * * @param period deadline period */ explicit TDeadline(const dds::core::Duration& period = dds::core::Duration::infinite()); /** * Copies a Deadline QoS instance * * @param other the Deadline QoS instance to copy */ TDeadline(const TDeadline& other); public: /** * Sets the deadline period * * @param period deadline period */ TDeadline& period(const dds::core::Duration& period); /** * Gets the deadline period * * @return deadline period */ const dds::core::Duration period() const; }; //============================================================================== /** * \copydoc DCPS_QoS_LatencyBudget */ template <typename D> class TLatencyBudget : public dds::core::Value<D> { public: /** * Creates a LatencyBudget QoS instance * * @param duration duration */ explicit TLatencyBudget(const dds::core::Duration& duration = dds::core::Duration::zero()); /** * Copies a LatencyBudget QoS instance * * @param other the LatencyBudget QoS instance to copy */ TLatencyBudget(const TLatencyBudget& other); public: /** * Sets the duration * * @param duration duration */ TLatencyBudget& duration(const dds::core::Duration& duration); /** * Gets the duration * * @return duration */ const dds::core::Duration duration() const; }; //============================================================================== /** * \copydoc DCPS_QoS_TimeBasedFilter */ template <typename D> class TTimeBasedFilter : public dds::core::Value<D> { public: /** * Creates a TimeBasedFilter QoS instance * * @param period minimum separation period */ explicit TTimeBasedFilter( const dds::core::Duration& period = dds::core::Duration::zero()); /** * Copies a TimeBasedFilter QoS instance * * @param other the TimeBasedFilter QoS instance to copy */ TTimeBasedFilter(const TTimeBasedFilter& other); public: /** * Sets the minimum separation period * * @param period minimum separation period */ TTimeBasedFilter& minimum_separation(const dds::core::Duration& period); /** * Gets the minimum separation period * * @return minimum separation period */ const dds::core::Duration minimum_separation() const; }; //============================================================================== /** * \copydoc DCPS_QoS_Partition */ template <typename D> class TPartition : public dds::core::Value<D> { public: /** * Creates a Partition QoS instance * * @param name partition name */ explicit TPartition(const std::string& name = ""); /** * Creates a Partition QoS instance * * @param names a sequence containing multiple partition names */ explicit TPartition(const dds::core::StringSeq& names); /** * Copies a Partition QoS instance * * @param other the Partition QoS instance to copy */ TPartition(const TPartition& other); public: /** * Sets the partition name * * @param name the partition name */ TPartition& name(const std::string& name); /** * Sets multiple partition names * * @param names a sequence containing multiple partition names */ TPartition& name(const dds::core::StringSeq& names); /** * Gets the partition names * * @return a sequence containing the partition names */ const dds::core::StringSeq name() const; }; //============================================================================== #ifdef OMG_DDS_OWNERSHIP_SUPPORT /** * \copydoc DCPS_QoS_Ownership */ template <typename D> class TOwnership : public dds::core::Value<D> { public: # if defined (__SUNPRO_CC) && defined(SHARED) # undef SHARED # endif /** * Creates an Ownership QoS instance * * @param kind the kind */ explicit TOwnership( dds::core::policy::OwnershipKind::Type kind = dds::core::policy::OwnershipKind::SHARED); /** * Copies an Ownership QoS instance * * @param other the Ownership QoS instance to copy */ TOwnership(const TOwnership& other); public: /** * Set the kind * * @param kind the kind */ TOwnership& kind(dds::core::policy::OwnershipKind::Type kind); /** * Get the kind * * @param kind the kind */ dds::core::policy::OwnershipKind::Type kind() const; public: /** * @return an Ownership QoS instance with the kind set to EXCLUSIVE */ static TOwnership Exclusive(); /** * @return an Ownership QoS instance with the kind set to SHARED */ static TOwnership Shared(); }; //============================================================================== /** * \copydoc DCPS_QoS_OwnershipStrength */ template <typename D> class TOwnershipStrength : public dds::core::Value<D> { public: /** * Creates an OwnershipStrength QoS instance * * @param strength ownership strength */ explicit TOwnershipStrength(int32_t strength = 0); /** * Copies an OwnershipStrength QoS instance * * @param other the OwnershipStrength QoS instance to copy */ TOwnershipStrength(const TOwnershipStrength& other); public: /** * Gets the ownership strength value * * @return the ownership strength value */ int32_t value() const; /** * Sets the ownership strength value * * @param strength the ownership strength value */ TOwnershipStrength& value(int32_t strength); }; #endif // OMG_DDS_OWNERSHIP_SUPPORT //============================================================================== /** * \copydoc DCPS_QoS_WriterDataLifecycle */ template <typename D> class TWriterDataLifecycle : public dds::core::Value<D> { public: /** * Creates a WriterDataLifecycle QoS instance * * @param autodispose_unregistered_instances ownership strength */ explicit TWriterDataLifecycle(bool autodispose_unregistered_instances = false); /** * Copies a WriterDataLifecycle QoS instance * * @param other the WriterDataLifecycle QoS instance to copy */ TWriterDataLifecycle(const TWriterDataLifecycle& other); public: /** * Gets a boolean indicating if unregistered instances should be autodisposed * * @return a boolean indicating if unregistered instances should be autodisposed */ bool autodispose_unregistered_instances() const; /** * Sets a boolean indicating if unregistered instances should be autodisposed * * @param autodispose_unregistered_instances a boolean indicating if unregistered * instances should be autodisposed */ TWriterDataLifecycle& autodispose_unregistered_instances( bool autodispose_unregistered_instances); public: /** * @return a WriterDataLifecycle QoS instance with autodispose_unregistered_instances * set to true */ static TWriterDataLifecycle AutoDisposeUnregisteredInstances(); /** * @return a WriterDataLifecycle QoS instance with autodispose_unregistered_instances * set to false */ static TWriterDataLifecycle ManuallyDisposeUnregisteredInstances(); }; //============================================================================== /** * \copydoc DCPS_QoS_ReaderDataLifecycle */ template <typename D> class TReaderDataLifecycle : public dds::core::Value<D> { public: /** * Creates a ReaderDataLifecycle QoS instance * * @param autopurge_nowriter_samples_delay the autopurge nowriter samples delay * @param autopurge_disposed_samples_delay the autopurge disposed samples delay */ TReaderDataLifecycle( const dds::core::Duration& autopurge_nowriter_samples_delay = dds::core::Duration::infinite(), const dds::core::Duration& autopurge_disposed_samples_delay = dds::core::Duration::infinite()); /** * Copies a ReaderDataLifecycle QoS instance * * @param other the ReaderDataLifecycle QoS instance to copy */ TReaderDataLifecycle(const TReaderDataLifecycle& other); public: /** * Gets the autopurge nowriter samples delay * * @return the autopurge nowriter samples delay */ const dds::core::Duration autopurge_nowriter_samples_delay() const; /** * Sets the autopurge nowriter samples delay * * @param autopurge_nowriter_samples_delay the autopurge nowriter samples delay */ TReaderDataLifecycle& autopurge_nowriter_samples_delay( const dds::core::Duration& autopurge_nowriter_samples_delay); /** * Gets the autopurge_disposed_samples_delay * * @return the autopurge disposed samples delay */ const dds::core::Duration autopurge_disposed_samples_delay() const; /** * Sets the autopurge_disposed_samples_delay * * @return the autopurge disposed samples delay */ TReaderDataLifecycle& autopurge_disposed_samples_delay( const dds::core::Duration& autopurge_disposed_samples_delay); public: /** * @return a ReaderDataLifecycle QoS instance which will not autopurge disposed * samples */ static TReaderDataLifecycle NoAutoPurgeDisposedSamples(); /** * @param autopurge_disposed_samples_delay the autopurge disposed samples delay * @return a ReaderDataLifecycle QoS instance with autopurge_disposed_samples_delay * set to a specified value */ static TReaderDataLifecycle AutoPurgeDisposedSamples( const dds::core::Duration& autopurge_disposed_samples_delay); }; //============================================================================== /** * \copydoc DCPS_QoS_Durability */ template <typename D> class TDurability : public dds::core::Value<D> { public: /** * Creates a Durability QoS instance * * @param kind the kind */ explicit TDurability( dds::core::policy::DurabilityKind::Type kind = dds::core::policy::DurabilityKind::VOLATILE); /** * Copies a Durability QoS instance * * @param other the Durability QoS instance to copy */ TDurability(const TDurability& other); public: /** * Set the kind * * @param kind the kind */ TDurability& kind(dds::core::policy::DurabilityKind::Type kind); /** * Get the kind * * @param kind the kind */ dds::core::policy::DurabilityKind::Type kind() const; public: /** * @return a Durability QoS instance with the kind set to VOLATILE */ static TDurability Volatile(); /** * @return a Durability QoS instance with the kind set to TRANSIENT_LOCAL */ static TDurability TransientLocal(); /** * @return a Durability QoS instance with the kind set to TRANSIENT */ static TDurability Transient(); /** * @return a Durability QoS instance with the kind set to PERSISTENT */ static TDurability Persistent(); }; //============================================================================== /** * \copydoc DCPS_QoS_Presentation */ template <typename D> class TPresentation : public dds::core::Value<D> { public: /** * Creates a Presentation QoS instance * * @param access_scope the access_scope kind * @param coherent_access the coherent_access setting * @param ordered_access the ordered_access setting */ TPresentation( dds::core::policy::PresentationAccessScopeKind::Type access_scope = dds::core::policy::PresentationAccessScopeKind::INSTANCE, bool coherent_access = false, bool ordered_access = false); /** * Copies a Presentation QoS instance * * @param other the Presentation QoS instance to copy */ TPresentation(const TPresentation& other); public: /** * Sets the access_scope kind * * @param access_scope the access_scope kind */ TPresentation& access_scope(dds::core::policy::PresentationAccessScopeKind::Type access_scope); /** * Gets the access_scope kind * * @return the access_scope kind */ dds::core::policy::PresentationAccessScopeKind::Type access_scope() const; /** * Sets the coherent_access setting * * @param coherent_access the coherent_access setting */ TPresentation& coherent_access(bool coherent_access); /** * Gets the coherent_access setting * * @return the coherent_access setting */ bool coherent_access() const; /** * Sets the ordered_access setting * * @param ordered_access the ordered_access setting */ TPresentation& ordered_access(bool ordered_access); /** * Gets the ordered_access setting * * @return the ordered_access setting */ bool ordered_access() const; public: /** * @param coherent_access the coherent_access setting * @param ordered_access the ordered_access setting * * @return a Presentation QoS instance with a GROUP access_score and coherent_access * and ordered_access set to the specified values */ static TPresentation GroupAccessScope(bool coherent_access = false, bool ordered_access = false); /** * @param coherent_access the coherent_access setting * @param ordered_access the ordered_access setting * * @return a Presentation QoS instance with a INSTANCE access_score and coherent_access * and ordered_access set to the specified values */ static TPresentation InstanceAccessScope(bool coherent_access = false, bool ordered_access = false); /** * @param coherent_access the coherent_access setting * @param ordered_access the ordered_access setting * * @return a Presentation QoS instance with a TOPIC access_score and coherent_access * and ordered_access set to the specified values */ static TPresentation TopicAccessScope(bool coherent_access = false, bool ordered_access = false); }; //============================================================================== /** * \copydoc DCPS_QoS_Reliability */ template <typename D> class TReliability : public dds::core::Value<D> { public: /** * Creates a Reliability QoS instance * * @param kind the kind * @param max_blocking_time the max_blocking_time */ TReliability( dds::core::policy::ReliabilityKind::Type kind = dds::core::policy::ReliabilityKind::BEST_EFFORT, const dds::core::Duration& max_blocking_time = dds::core::Duration::from_millisecs(100)); /** * Copies a Reliability QoS instance * * @param other the Reliability QoS instance to copy */ TReliability(const TReliability& other); public: /** * Sets the kind * * @param kind the kind */ TReliability& kind(dds::core::policy::ReliabilityKind::Type kind); /** * Gets the kind * * @return the kind */ dds::core::policy::ReliabilityKind::Type kind() const; /** * Sets the max_blocking_time * * @param max_blocking_time the max_blocking_time */ TReliability& max_blocking_time(const dds::core::Duration& max_blocking_time); /** * Gets the max_blocking_time * * @return the max_blocking_time */ const dds::core::Duration max_blocking_time() const; public: /** * @param the max_blocking_time * @return a Reliability QoS instance with the kind set to RELIABLE and the max_blocking_time * set to the supplied value */ static TReliability Reliable(const dds::core::Duration& max_blocking_time = dds::core::Duration::from_millisecs(100)); /** * @return a Reliability QoS instance with the kind set to BEST_EFFORT */ static TReliability BestEffort(const dds::core::Duration& max_blocking_time = dds::core::Duration::from_millisecs(100)); }; //============================================================================== /** * \copydoc DCPS_QoS_DestinationOrder */ template <typename D> class TDestinationOrder : public dds::core::Value<D> { public: /** * Creates a DestinationOrder QoS instance * * @param kind the kind */ explicit TDestinationOrder( dds::core::policy::DestinationOrderKind::Type kind = dds::core::policy::DestinationOrderKind::BY_RECEPTION_TIMESTAMP); /** * Copies a DestinationOrder QoS instance * * @param other the Reliability QoS instance to copy */ TDestinationOrder(const TDestinationOrder& other); public: /** * Sets the kind * * @param kind the kind */ TDestinationOrder& kind(dds::core::policy::DestinationOrderKind::Type kind); /** * Gets the kind * * @return the kind */ dds::core::policy::DestinationOrderKind::Type kind() const; public: /** * @return a DestinationOrder QoS instance with the kind set to BY_SOURCE_TIMESTAMP */ static TDestinationOrder SourceTimestamp(); /** * @return a DestinationOrder QoS instance with the kind set to BY_RECEPTION_TIMESTAMP */ static TDestinationOrder ReceptionTimestamp(); }; //============================================================================== /** * \copydoc DCPS_QoS_History */ template <typename D> class THistory : public dds::core::Value<D> { public: /** * Creates a History QoS instance * * @param kind the kind * @param depth the history depth */ THistory(dds::core::policy::HistoryKind::Type kind = dds::core::policy::HistoryKind::KEEP_LAST, int32_t depth = 1); /** * Copies a History QoS instance * * @param other the History QoS instance to copy */ THistory(const THistory& other); public: /** * Gets the kind * * @return the kind */ dds::core::policy::HistoryKind::Type kind() const; /** * Sets the kind * * @param kind the kind */ THistory& kind(dds::core::policy::HistoryKind::Type kind); /** * Gets the history depth * * @return the history depth */ int32_t depth() const; /** * Sets the history depth * * @param the history depth */ THistory& depth(int32_t depth); public: /** * @return a History QoS instance with the kind set to KEEP_ALL */ static THistory KeepAll(); /** * @param depth the history depth * @return a History QoS instance with the kind set to KEEP_LAST and the * depth set to the supplied value */ static THistory KeepLast(uint32_t depth); }; //============================================================================== /** * \copydoc DCPS_QoS_ResourceLimits */ template <typename D> class TResourceLimits : public dds::core::Value<D> { public: /** * Creates a ResourceLimits QoS instance * * @param max_samples the max_samples value * @param max_instances the max_instances value * @param max_samples_per_instance the max_samples_per_instance value */ TResourceLimits(int32_t max_samples = dds::core::LENGTH_UNLIMITED, int32_t max_instances = dds::core::LENGTH_UNLIMITED, int32_t max_samples_per_instance = dds::core::LENGTH_UNLIMITED); /** * Copies a ResourceLimits QoS instance * * @param other the ResourceLimits QoS instance to copy */ TResourceLimits(const TResourceLimits& other); public: /** * Sets the max_samples value * * @param max_samples the max_samples value */ TResourceLimits& max_samples(int32_t max_samples); /** * Gets the max_samples value * * @return the max_samples value */ int32_t max_samples() const; /** * Sets the max_instances value * * @param max_instances the max_instances value */ TResourceLimits& max_instances(int32_t max_instances); /** * Gets the max_instances value * * @return the max_instances value */ int32_t max_instances() const; /** * Sets the max_samples_per_instance value * * @param max_samples_per_instance the max_samples_per_instance value */ TResourceLimits& max_samples_per_instance(int32_t max_samples_per_instance); /** * Gets the max_samples_per_instance value * * @return the max_samples_per_instance value */ int32_t max_samples_per_instance() const; }; //============================================================================== /** * \copydoc DCPS_QoS_Liveliness */ template <typename D> class TLiveliness : public dds::core::Value<D> { public: /** * Creates a Liveliness QoS instance * * @param kind the kind * @param lease_duration the lease_duration */ TLiveliness( dds::core::policy::LivelinessKind::Type kind = dds::core::policy::LivelinessKind::AUTOMATIC, const dds::core::Duration& lease_duration = dds::core::Duration::infinite()); /** * Copies a Liveliness QoS instance * * @param other the Liveliness QoS instance to copy */ TLiveliness(const TLiveliness& other); public: /** * Sets the kind * * @param kind the kind */ TLiveliness& kind(dds::core::policy::LivelinessKind::Type kind); /** * Gets the kind * * @return the kind */ dds::core::policy::LivelinessKind::Type kind() const; /** * Sets the lease_duration * * @return the lease_duration */ TLiveliness& lease_duration(const dds::core::Duration& lease_duration); /** * Gets the lease_duration * * @return the lease_duration */ const dds::core::Duration lease_duration() const; public: /** * @return a Liveliness QoS instance with the kind set to AUTOMATIC */ static TLiveliness Automatic(); /** * @return a Liveliness QoS instance with the kind set to MANUAL_BY_PARTICIPANT * and the lease_duration set to the supplied value */ static TLiveliness ManualByParticipant(const dds::core::Duration& lease_duration = dds::core::Duration::infinite()); /** * @return a Liveliness QoS instance with the kind set to MANUAL_BY_TOPIC * and the lease_duration set to the supplied value */ static TLiveliness ManualByTopic(const dds::core::Duration& lease_duration = dds::core::Duration::infinite()); }; //============================================================================== #ifdef OMG_DDS_PERSISTENCE_SUPPORT /** * \copydoc DCPS_QoS_DurabilityService */ template <typename D> class TDurabilityService : public dds::core::Value<D> { public: /** * Creates a DurabilityService QoS instance * * @param service_cleanup_delay the service_cleanup_delay * @param history_kind the history_kind value * @param history_depth the history_depth value * @param max_samples the max_samples value * @param max_instances the max_instances value * @param max_samples_per_instance the max_samples_per_instance value */ TDurabilityService( const dds::core::Duration& service_cleanup_delay = dds::core::Duration::zero(), dds::core::policy::HistoryKind::Type history_kind = dds::core::policy::HistoryKind::KEEP_LAST, int32_t history_depth = 1, int32_t max_samples = dds::core::LENGTH_UNLIMITED, int32_t max_instances = dds::core::LENGTH_UNLIMITED, int32_t max_samples_per_instance = dds::core::LENGTH_UNLIMITED); /** * Copies a DurabilityService QoS instance * * @param other the DurabilityService QoS instance to copy */ TDurabilityService(const TDurabilityService& other); public: /** * Sets the service_cleanup_delay value * * @param service_cleanup_delay the service_cleanup_delay value */ TDurabilityService& service_cleanup_delay(const dds::core::Duration& service_cleanup_delay); /** * Gets the service_cleanup_delay value * * @return the service_cleanup_delay */ const dds::core::Duration service_cleanup_delay() const; /** * Sets the history_kind * * @param the history_kind */ TDurabilityService& history_kind(dds::core::policy::HistoryKind::Type history_kind); /** * Gets the history_kind * * @return history_kind */ dds::core::policy::HistoryKind::Type history_kind() const; /** * Sets the history_depth value * * @param history_depth the history_depth value */ TDurabilityService& history_depth(int32_t history_depth); /** * Gets the history_depth value * * @return history_depth */ int32_t history_depth() const; /** * Sets the max_samples value * * @param max_samples the max_samples value */ TDurabilityService& max_samples(int32_t max_samples); /** * Gets the max_samples value * * @return the max_samples value */ int32_t max_samples() const; /** * Sets the max_instances value * * @param max_instances the max_instances value */ TDurabilityService& max_instances(int32_t max_instances); /** Gets the max_instances value * * @return the max_instances value */ int32_t max_instances() const; /** * Sets the max_samples_per_instance value * * @param max_samples_per_instance the max_samples_per_instance value */ TDurabilityService& max_samples_per_instance(int32_t max_samples_per_instance); /** * Gets the max_samples_per_instance value * * @return the max_samples_per_instance value */ int32_t max_samples_per_instance() const; }; #endif // OMG_DDS_PERSISTENCE_SUPPORT //============================================================================== /** */ template <typename D> class TShare : public dds::core::Value<D> { public: /** * Creates a Share QoS instance * * @param name the name * @param enable state */ TShare(const std::string& name = "", bool enable = false); /** * Copies a Share QoS instance * * @param other the TShare QoS instance to copy */ TShare(const TShare& other); public: /** * Sets the name * * @param name the name */ TShare& name(const std::string& name); /** * Gets the name * * @return the name */ std::string name() const; /** * Sets enable state * * @param enable state */ TShare& enable(bool enable); /** * Gets enable state * * @return enable state */ bool enable() const; }; //============================================================================== /** */ template <typename D> class TProductData : public dds::core::Value<D> { public: /** * Creates a ProductData QoS instance * * @param value the value */ TProductData(const std::string& value = ""); /** * Copies a ProductData QoS instance * * @param other the TProductData QoS instance to copy */ TProductData(const TProductData& other); public: /** * Sets the value * * @param value the value */ TProductData& value(const std::string& value); /** * Gets the value * * @return the value */ std::string value() const; }; //============================================================================== /** */ template <typename D> class TSubscriptionKey : public dds::core::Value<D> { public: /** * Creates a SubscriptionKey QoS instance * * @param use_key_list use the key list or not * @param key a single key */ explicit TSubscriptionKey(bool use_key_list = false, const std::string& key = ""); /** * Creates a SubscriptionKey QoS instance * * @param use_key_list use the key list or not * @param keys a sequence containing multiple keys */ explicit TSubscriptionKey(bool use_key_list, const dds::core::StringSeq& keys); /** * Copies a SubscriptionKey QoS instance * * @param other the TSubscriptionKey QoS instance to copy */ TSubscriptionKey(const TSubscriptionKey& other); public: /** * Sets the key * * @param key the key */ TSubscriptionKey& key(const std::string& key); /** * Sets multiple keys * * @param names a sequence containing multiple keys */ TSubscriptionKey& key(const dds::core::StringSeq& keys); /** * Gets the keys * * @return a sequence containing the keys */ const dds::core::StringSeq key() const; /** * Sets use_key_list state * * @param use_key_list state */ TSubscriptionKey& use_key_list(bool use_key_list); /** * Gets use_key_list state * * @return use_key_list state */ bool use_key_list() const; }; //============================================================================ #ifdef OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT template <typename D> class TDataRepresentation : public dds::core::Value<D> { public: explicit TDataRepresentation( const dds::core::policy::DataRepresentationIdSeq& value); TDataRepresentation(const TDataRepresentation& other) : dds::core::Value<D>(other.value()) { } public: TDataRepresentation& value(const dds::core::policy::DataRepresentationIdSeq& value); const dds::core::policy::DataRepresentationIdSeq value() const; dds::core::policy::DataRepresentationIdSeq& }; #endif // defined(OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT) //============================================================================ #ifdef OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT template <typename D> class TTypeConsistencyEnforcement : public dds::core::Value<D> { public: explicit TTypeConsistencyEnforcement(dds::core::policy::TypeConsistencyEnforcementKind::Type kind); public: TTypeConsistencyEnforcement& kind(dds::core::policy::TypeConsistencyEnforcementKind::Type kind); dds::core::policy::TypeConsistencyEnforcementKind::Type kind() const; }; #endif // defined(OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT) //============================================================================== } } } #endif /* OMG_TDDS_CORE_POLICY_CORE_POLICY_HPP_ */
25.145577
124
0.612746
[ "object" ]
1a5462ef01c17072814741aaf826d70ad539bf05
596
cpp
C++
Hackerrank/ProblemSolving/Dynamic Array.cpp
willingtonortiz/CPSolutions
66c48995ba0f8658e000a1ef828ab5759549975e
[ "MIT" ]
null
null
null
Hackerrank/ProblemSolving/Dynamic Array.cpp
willingtonortiz/CPSolutions
66c48995ba0f8658e000a1ef828ab5759549975e
[ "MIT" ]
null
null
null
Hackerrank/ProblemSolving/Dynamic Array.cpp
willingtonortiz/CPSolutions
66c48995ba0f8658e000a1ef828ab5759549975e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int size, queries, type, a, b, lastA = 0; cin >> size >> queries; vector<vector<int>> list(size, vector<int>()); for(int i = 0; i < queries; ++i){ cin >> type >> a >> b; // cout << type << " " << a << " " << b << endl; if(type == 1){ list[(a ^ lastA) % size].push_back(b); } else{ int sz = list[(a ^ lastA) % size].size(); lastA = list[(a ^ lastA) % size][b % sz]; cout << lastA << endl; } } return 0; }
22.074074
56
0.422819
[ "vector" ]
1a61f046cb9ae399f6c0b315391410b444a5597f
8,485
cpp
C++
bot/botState.cpp
rdujardin/Ara
ae045d4477b80f66329b4686bc4b052e44433d1c
[ "BSD-2-Clause" ]
null
null
null
bot/botState.cpp
rdujardin/Ara
ae045d4477b80f66329b4686bc4b052e44433d1c
[ "BSD-2-Clause" ]
null
null
null
bot/botState.cpp
rdujardin/Ara
ae045d4477b80f66329b4686bc4b052e44433d1c
[ "BSD-2-Clause" ]
null
null
null
/* bot_vals[cpp (part of Ara, https://github.com/rdujardin/Ara) Copyright (c) 2016, Raphaël Dujardin (rdujardin) & Jean Boehm (jboehm1) 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. */ #include "botState.h" using namespace std; double conv(unsigned int servo,bool unit,double input) { //servo = 0:_theta0, 1:_alpha1, 2:_alpha2, 3:_alpha3, 4:_theta3 //unit : true=computed to real ; false=real to computed //COMPUTED // theta0 : 0 complètement à droite, 180 à gauche // theta3 : 0 dans le prolongement, 90 à gauche (angle droit) // alpha1 : 0 à l'horizontale devant, 90 en haut // alpha2 : 0 dans le prolongement, 90 angle droit vers le haut, -90 angle droit vers le bas // alpha3 : 0 dans le prolongement, 90 angle droit vers le haut, -90 angle droit vers le bas //REAL // theta0 : 0-140, 0 à droite (pas complètement), 70 en face (à multiplier par 180/140 pour envoyer au servo) //en fait c'est 0 à gauche ! // theta3 : 90 dans le prolongement, (0 ??) // alpha1 : 0-140, 140 à l'horizontale arrière (à multiplier par 180/140 pour envoyer au servo) // alpha2 : 0-180, 0 replié par le bas sur la première pièce, 180 dans le prolongement // alpha3 : 0-180, 90 dans le prolongement, (0 ??) if(unit) { if(servo==0) return (ALPHA1_2_RANGE-(input*180/M_PI-(180-ALPHA1_2_RANGE)/2))*M_PI/180; else if(servo==4) return input+90*M_PI/180; //+90° si 0 à droite, 90°-_theta3 si 0 à gauche else if(servo==1) return input-(180-ALPHA1_2_RANGE)*M_PI/180; else if(servo==2) return input+180*M_PI/180; else return input+90*M_PI/180; //+90° si 0 en bas, 90°-_alpha3 si 0 en haut } else { if(servo==0) return (180-(input*180/M_PI+(180-ALPHA1_2_RANGE)/2))*M_PI/180; else if(servo==4) return input-90*M_PI/180; //-90° si 0 à droite, 90°-_theta3 si 0 à gauche else if(servo==1) return input+(180-ALPHA1_2_RANGE)*M_PI/180; else if(servo==2) return input-180*M_PI/180; else return input-90*M_PI/180; //-90° si 0 en bas, 90°-_alpha3 si 0 en haut } } BotState::BotState() { for(unsigned int i=0;i<=12;++i) _vals.push_back(0); } BotState BotState::readyPos() { BotState s; s.set(angles,theta0,rad(ALPHA1_2_RANGE/2.0),alpha1,rad(87.0),alpha2,rad(70.0),alpha3,rad(13.0),theta3,rad(90.0)); return s; } BotState BotState::offPos() { BotState s; s.setUnsafe(angles,theta0,rad(ALPHA1_2_RANGE/2.0),alpha1,rad(ALPHA1_2_RANGE),alpha2,rad(0.0),alpha3,rad(90.0),theta3,rad(180.0)); return s; } /* void BotState::setFrom(BotState& s) { _vals.clear(); for(unsigned int i=0;i<=12;++i) _vals.push_back(s._vals[i]); } */ void BotState::setFrom(BotState s) { _vals.clear(); for(unsigned int i=0;i<=12;++i) _vals.push_back(s._vals[i]); } double BotState::get(unsigned int i) { return _vals[i]; } bool BotState::set(unsigned int type,unsigned int i1,double v1,unsigned int i2,double v2,unsigned i3,double v3,unsigned i4,double v4,unsigned i5,double v5,unsigned i6,double v6,unsigned i7,double v7,unsigned i8,double v8,unsigned i9,double v9,unsigned i10,double v10,unsigned i11,double v11) { vector<double> sv=_vals; setUnsafe(type,i1,v1,i2,v2,i3,v3,i4,v4,i5,v5,i6,v6,i7,v7,i8,v8,i9,v9,i10,v10,i11,v11); if(!checkWorkingZone()) { _vals=sv; return false; } else return true; } void BotState::setUnsafe(unsigned int type,unsigned int i1,double v1,unsigned int i2,double v2,unsigned i3,double v3,unsigned i4,double v4,unsigned i5,double v5,unsigned i6,double v6,unsigned i7,double v7,unsigned i8,double v8,unsigned i9,double v9,unsigned i10,double v10,unsigned i11,double v11) { map<unsigned int,double> v; v[0]=0; v[i1]=v1; v[i2]=v2; v[i3]=v3; v[i4]=v4; v[i5]=v5; v[i6]=v6; v[i7]=v7; v[i8]=v8; v[i9]=v9; v[i10]=v10; v[i11]=v11; for(map<unsigned int,double>::iterator it=v.begin();it!=v.end();++it) { _vals[it->first]=it->second; } if(type==angles) computeCartesian(); else computeAngles(); } bool BotState::check(unsigned int i) { if(i==theta0) return _vals[theta0]>=0*M_PI/180 && _vals[theta0]<=125*M_PI/180; else if(i==alpha1) return _vals[alpha1]>=0*M_PI/180 && _vals[alpha1]<=125*M_PI/180; else if(i==alpha2) return _vals[alpha2]>=0*M_PI/180 && _vals[alpha2]<=180*M_PI/180; else if(i==alpha3) return _vals[alpha3]>=0*M_PI/180 && _vals[alpha3]<=180*M_PI/180; else if(i==theta3) return _vals[theta3]>=0*M_PI/180 && _vals[theta3]<=180*M_PI/180; else if(i==terminalY) return _vals[terminalY]>0+_terminalYOffset; else if(i==terminalZ) return _vals[terminalZ]>=20 && _vals[terminalZ]<55; else if(i==wristY) return _vals[wristY]>0; else return true; } bool BotState::checkWorkingZone() { bool w=true; for(unsigned int i=0;i<=12;++i) w=w && check(i); return w; } void BotState::computeAngles() { //Angles computing : _vals[theta0]=atan2((_vals[terminalZ]-_length3*cos(_terminalAbsAlpha)*cos(_terminalAbsTheta)),(_vals[terminalX]+_length3*cos(_terminalAbsAlpha)*sin(_terminalAbsTheta))); _vals[theta3]=M_PI/2-_terminalAbsTheta-_vals[theta0]; _vals[length3Al]=_length3*cos(_vals[theta3]); _vals[wristX]=(_vals[terminalX]+_length3*cos(_terminalAbsAlpha)*sin(_terminalAbsTheta))/cos(_vals[theta0]); _vals[wristY]=_vals[terminalY]-_length3*sin(_terminalAbsAlpha); _vals[terminalXTh]=_vals[wristX]+_vals[length3Al]*cos(_terminalAbsAlpha); //cf 379.pdf : double cosAlpha2=(_vals[wristX]*_vals[wristX]+_vals[wristY]*_vals[wristY]-_length1*_length1-_length2*_length2)/(2*_length1*_length2); double sinAlpha2=-sqrt(1-cosAlpha2*cosAlpha2); double cosAlpha1=(_vals[wristX]*(_length1+_length2*cosAlpha2)+_vals[wristY]*_length2*sinAlpha2)/(_vals[wristX]*_vals[wristX]+_vals[wristY]*_vals[wristY]); double sinAlpha1=sqrt(1-cosAlpha1*cosAlpha1); _vals[alpha1]=atan2(sinAlpha1,cosAlpha1); _vals[alpha2]=atan2(sinAlpha2,cosAlpha2); _vals[alpha3]=_terminalAbsAlpha-_vals[alpha1]-_vals[alpha2]; //Conversion : computed->real _vals[theta0]=conv(0,true,_vals[theta0]); _vals[alpha1]=conv(1,true,_vals[alpha1]); _vals[alpha2]=conv(2,true,_vals[alpha2]); _vals[alpha3]=conv(3,true,_vals[alpha3]); _vals[theta3]=conv(4,true,_vals[theta3]); } void BotState::computeCartesian() { _vals[length3Al]=_length3*cos(conv(4,false,_vals[theta3])); _vals[wristX]=_length1*cos(conv(1,false,_vals[alpha1]))+_length2*cos(conv(1,false,_vals[alpha1])+conv(2,false,_vals[alpha2])); _vals[wristY]=_length1*sin(conv(1,false,_vals[alpha1]))+_length2*sin(conv(1,false,_vals[alpha1])+conv(2,false,_vals[alpha2])); _vals[terminalXTh]=_vals[wristX]+_vals[length3Al]*cos(_terminalAbsAlpha); _vals[terminalX]=_vals[wristX]*cos(conv(0,false,_vals[theta0]))+_length3Th*cos(conv(0,false,_vals[theta0])+conv(4,false,_vals[theta3])); _vals[terminalY]=_length1*sin(conv(1,false,_vals[alpha1]))+_length2*sin(conv(1,false,_vals[alpha1])+conv(2,false,_vals[alpha2]))+_vals[length3Al]*sin(conv(1,false,_vals[alpha1])+conv(2,false,_vals[alpha2])+conv(3,false,_vals[alpha3])); _vals[terminalZ]=_vals[wristX]*sin(conv(0,false,_vals[theta0]))+_length3Th*sin(conv(0,false,_vals[theta0])+conv(4,false,_vals[theta3])); } string BotState::stringify() { ostringstream oss; oss << "[x " << _vals[terminalX] << " | y " << _vals[terminalY] << " | z " << _vals[terminalZ] << " | th0 " << _vals[theta0] << " | al1 " << _vals[alpha1] << " | al2 " << _vals[alpha2] << " | al3 " << _vals[alpha3] << " | th3 " << _vals[theta3] << "]"; return oss.str(); }
44.424084
299
0.728108
[ "vector" ]
1a6c3f3498d6681ad0dc596657f3e50728f9e8b1
19,289
cpp
C++
src/providers/internal/InternalStorageProvider.cpp
webosose/com.webos.service.storageaccess
9d1c912c5654ff9df33206d0d367359b04e03e22
[ "Apache-2.0" ]
null
null
null
src/providers/internal/InternalStorageProvider.cpp
webosose/com.webos.service.storageaccess
9d1c912c5654ff9df33206d0d367359b04e03e22
[ "Apache-2.0" ]
1
2021-06-22T22:18:47.000Z
2021-06-22T22:18:47.000Z
src/providers/internal/InternalStorageProvider.cpp
webosose/com.webos.service.storageaccess
9d1c912c5654ff9df33206d0d367359b04e03e22
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2021 LG Electronics, Inc. * * Confidential computer software. Valid license from LG required for * possession, use or copying. Consistent with FAR 12.211 and 12.212, * Commercial Computer Software, Computer Software Documentation, and * Technical Data for Commercial Items are licensed to the U.S. Government * under vendor's standard commercial license. * * LICENSE@@@ */ #include <functional> #include <future> #include <pbnjson.hpp> #include "SA_Common.h" #include "SAFLunaService.h" #include "InternalStorageProvider.h" #include "SAFUtilityOperation.h" #include "UpnpDiscover.h" #include <libxml/tree.h> using namespace std; InternalStorageProvider::InternalStorageProvider() : mQuit(false) { mDispatcherThread = std::thread(std::bind(&InternalStorageProvider::dispatchHandler, this)); mDispatcherThread.detach(); } InternalStorageProvider::~InternalStorageProvider() { mQuit = true; if (mDispatcherThread.joinable()) { mDispatcherThread.join(); } } void InternalStorageProvider::listFolderContents(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::string driveId = reqData->params["driveId"].asString(); pbnjson::JValue respObj = pbnjson::Object(); std::string path = reqData->params["path"].asString(); std::string sessionId = reqData->sessionId; if(!SAFUtilityOperation::getInstance().validateInternalPath(path, sessionId)) { respObj.put("errorCode", SAFErrors::PERMISSION_DENIED); respObj.put("errorText", "Permission Denied"); reqData->cb(respObj, reqData->subs); return; } if(DEFAULT_INTERNAL_STORAGE_ID != driveId) { respObj.put("errorCode", SAFErrors::INVALID_PARAM); respObj.put("errorText", "Invalid DriveID"); reqData->cb(respObj, reqData->subs); return; } int offset = reqData->params["offset"].asNumber<int>(); int limit = reqData->params["limit"].asNumber<int>(); bool status = false; int totalCount = 0; std::string fullPath; pbnjson::JValue contenResArr = pbnjson::Array(); std::unique_ptr<FolderContents> contsPtr = SAFUtilityOperation::getInstance().getListFolderContents(path); fullPath = contsPtr->getPath(); totalCount = contsPtr->getTotalCount(); if (contsPtr->getStatus() >= 0) { auto contVec = contsPtr->getContents(); int start = (offset > (int)contVec.size())?(contVec.size() + 1):(offset - 1); start = (start < 0)?(contVec.size() + 1):(start); int end = ((limit + offset - 1) > contVec.size())?(contVec.size()):(limit + offset - 1); end = (end < 0)?(contVec.size()):(end); LOG_DEBUG_SAF("%s: start:%d, end: %d", __FUNCTION__,start,end); for (int index = start; index < end; ++index) { std::string size_str = std::to_string(contVec[index]->getSize()); pbnjson::JValue contentObj = pbnjson::Object(); contentObj.put("name", contVec[index]->getName()); contentObj.put("path", contVec[index]->getPath()); contentObj.put("type", contVec[index]->getType()); contentObj.put("size", size_str); contenResArr.append(contentObj); } status = true; } respObj.put("returnValue", status); if (status) { respObj.put("files", contenResArr); respObj.put("totalCount", totalCount); respObj.put("fullPath", fullPath); } else { auto errorCode = getInternalErrorCode(contsPtr->getStatus()); auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); } reqData->cb(respObj, reqData->subs); } void InternalStorageProvider::getProperties(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::string driveId = reqData->params["driveId"].asString(); pbnjson::JValue respObj = pbnjson::Object(); if(DEFAULT_INTERNAL_STORAGE_ID != driveId) { respObj.put("errorCode", SAFErrors::INVALID_PARAM); respObj.put("errorText", "Invalid DriveID"); reqData->cb(respObj, reqData->subs); return; } std::string path; if (reqData->params.hasKey("path")) path = reqData->params["path"].asString(); if (path.empty()) path = SAFUtilityOperation::getInstance().getInternalPath(reqData->sessionId); if(!SAFUtilityOperation::getInstance().validateInternalPath(path, reqData->sessionId)) { auto errorCode = SAFErrors::SAFErrors::INVALID_PATH; auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); reqData->cb(respObj, reqData->subs); return; } std::unique_ptr<InternalSpaceInfo> propPtr = SAFUtilityOperation::getInstance().getProperties(path); bool status = (propPtr->getStatus() < 0)?(false):(true); respObj.put("returnValue", status); if (status) { pbnjson::JValue attributesArr = pbnjson::Array(); if (reqData->params.hasKey("storageType")) respObj.put("storageType", reqData->params["storageType"].asString()); respObj.put("writable", propPtr->getIsWritable()); respObj.put("deletable", propPtr->getIsDeletable()); pbnjson::JValue attrObj = pbnjson::Object(); attrObj.put("LastModTimeStamp", propPtr->getLastModTime()); attributesArr.append(attrObj); respObj.put("attributes", attributesArr); if (path == SAFUtilityOperation::getInstance().getInternalPath(reqData->sessionId)) { respObj.put("totalSpace", int(propPtr->getCapacityMB())); respObj.put("freeSpace", int(propPtr->getFreeSpaceMB())); } } else { auto errorCode = getInternalErrorCode(propPtr->getStatus()); auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); } reqData->cb(respObj, reqData->subs); } void InternalStorageProvider::copy(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::string driveId = reqData->params["srcDriveId"].asString(); pbnjson::JValue respObj = pbnjson::Object(); if(DEFAULT_INTERNAL_STORAGE_ID != driveId) { respObj.put("errorCode", SAFErrors::INVALID_PARAM); respObj.put("errorText", "Invalid DriveID"); reqData->cb(respObj, reqData->subs); return; } std::string srcPath = reqData->params["srcPath"].asString(); std::string destPath = reqData->params["destPath"].asString(); if(!SAFUtilityOperation::getInstance().validateInterProviderOperation(reqData)) return; bool overwrite = false; if (reqData->params.hasKey("overwrite")) overwrite = reqData->params["overwrite"].asBool(); std::unique_ptr<InternalCopy> copyPtr = SAFUtilityOperation::getInstance().copy(srcPath, destPath, overwrite); int retStatus = -1; int prevStatus = -20; while(1) { retStatus = copyPtr->getStatus(); LOG_DEBUG_SAF("%s: statussss : %d", __FUNCTION__, retStatus); bool status = (retStatus < 0)?(false):(true); respObj.put("returnValue", status); if (status) { respObj.put("progress", retStatus); } else { auto errorCode = getInternalErrorCode(copyPtr->getStatus()); auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); } if (retStatus != prevStatus) reqData->cb(respObj, reqData->subs); if ((retStatus >= 100) || (retStatus < 0)) break; else std::this_thread::sleep_for(std::chrono::milliseconds(1000)); prevStatus = retStatus; } } void InternalStorageProvider::move(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::string driveId = reqData->params["srcDriveId"].asString(); pbnjson::JValue respObj = pbnjson::Object(); if(DEFAULT_INTERNAL_STORAGE_ID != driveId) { respObj.put("errorCode", SAFErrors::INVALID_PARAM); respObj.put("errorText", "Invalid DriveID"); reqData->cb(respObj, reqData->subs); return; } std::string srcPath = reqData->params["srcPath"].asString(); std::string destPath = reqData->params["destPath"].asString(); if(!SAFUtilityOperation::getInstance().validateInterProviderOperation(reqData)) return; bool overwrite = false; if (reqData->params.hasKey("overwrite")) overwrite = reqData->params["overwrite"].asBool(); std::unique_ptr<InternalMove> movePtr = SAFUtilityOperation::getInstance().move(srcPath, destPath, overwrite); int retStatus = -1; int prevStatus = -20; while(1) { retStatus = movePtr->getStatus(); LOG_DEBUG_SAF("%s: statussss : %d", __FUNCTION__, retStatus); bool status = (retStatus < 0)?(false):(true); respObj.put("returnValue", status); if (status) { respObj.put("progress", retStatus); } else { auto errorCode = getInternalErrorCode(movePtr->getStatus()); auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); } if (retStatus != prevStatus) reqData->cb(respObj, reqData->subs); if ((retStatus >= 100) || (retStatus < 0)) break; else std::this_thread::sleep_for(std::chrono::milliseconds(1000)); prevStatus = retStatus; } } void InternalStorageProvider::remove(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::string driveId = reqData->params["driveId"].asString(); pbnjson::JValue respObj = pbnjson::Object(); std::string path = reqData->params["path"].asString(); std::string sessionId = reqData->sessionId; if(!SAFUtilityOperation::getInstance().validateInternalPath(path, sessionId)) { respObj.put("errorCode", SAFErrors::PERMISSION_DENIED); respObj.put("errorText", "Permission Denied"); reqData->cb(respObj, reqData->subs); return; } if(DEFAULT_INTERNAL_STORAGE_ID != driveId) { respObj.put("errorCode", SAFErrors::INVALID_PARAM); respObj.put("errorText", "Invalid DriveID"); reqData->cb(respObj, reqData->subs); return; } std::unique_ptr<InternalRemove> remPtr = SAFUtilityOperation::getInstance().remove(path); bool status = (remPtr->getStatus() < 0)?(false):(true); respObj.put("returnValue", status); if (!status) { auto errorCode = getInternalErrorCode(remPtr->getStatus()); auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); } reqData->cb(respObj, reqData->subs); } void InternalStorageProvider::rename(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::string driveId = reqData->params["driveId"].asString(); pbnjson::JValue respObj = pbnjson::Object(); std::string srcPath = reqData->params["path"].asString(); std::string sessionId = reqData->sessionId; if(!SAFUtilityOperation::getInstance().validateInternalPath(srcPath, sessionId)) { respObj.put("errorCode", SAFErrors::PERMISSION_DENIED); respObj.put("errorText", "Permission Denied"); reqData->cb(respObj, reqData->subs); return; } if(DEFAULT_INTERNAL_STORAGE_ID != driveId) { respObj.put("errorCode", SAFErrors::INVALID_PARAM); respObj.put("errorText", "Invalid DriveID"); reqData->cb(respObj, reqData->subs); return; } std::string destPath = reqData->params["newName"].asString(); std::unique_ptr<InternalRename> renamePtr = SAFUtilityOperation::getInstance().rename(srcPath, destPath); bool status = (renamePtr->getStatus() < 0)?(false):(true); respObj.put("returnValue", status); if (!status) { auto errorCode = getInternalErrorCode(renamePtr->getStatus()); auto errorStr = SAFErrors::InternalErrors::getInternalErrorString(errorCode); respObj.put("errorCode", errorCode); respObj.put("errorText", errorStr); } reqData->cb(respObj, reqData->subs); } void InternalStorageProvider::eject(std::shared_ptr<RequestData> reqData) { pbnjson::JValue respObj = pbnjson::Object(); respObj.put("returnValue", false); respObj.put("errorCode", SAFErrors::SAFErrors::UNKNOWN_ERROR); respObj.put("errorText", "Not supported yet"); reqData->params.put("response", respObj); reqData->cb(reqData->params, std::move(reqData->subs)); } void InternalStorageProvider::listStoragesMethod(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); pbnjson::JValue respObj = pbnjson::Object(); pbnjson::JValue internalResArr = pbnjson::Array(); pbnjson::JValue internalRes = pbnjson::Object(); internalRes.put("driveName", DEFAULT_INTERNAL_DRIVE_NAME); internalRes.put("driveId", DEFAULT_INTERNAL_STORAGE_ID); internalRes.put("path", SAFUtilityOperation::getInstance().getInternalPath(reqData->sessionId)); internalResArr.append(internalRes); respObj.put("internal", internalResArr); reqData->params.put("response", respObj); reqData->cb(reqData->params, std::move(reqData->subs)); return; } void InternalStorageProvider::addRequest(std::shared_ptr<RequestData>& reqData) { mQueue.push_back(std::move(reqData)); mCondVar.notify_one(); } bool InternalStorageProvider::onReply(LSHandle *sh, LSMessage *message , void *ctx) { LOG_DEBUG_SAF("%s: [%s]", __FUNCTION__, LSMessageGetPayload(message)); LSError lserror; (void)LSErrorInit(&lserror); LSCallCancel(sh, NULL, &lserror); ReqContext *ctxPtr = static_cast<ReqContext*>(ctx); pbnjson::JSchema parseSchema = pbnjson::JSchema::AllSchema(); pbnjson::JDomParser parser; std::string payload = LSMessageGetPayload(message); if (parser.parse(payload, parseSchema)) { pbnjson::JValue root = parser.getDom(); if (!ctxPtr->reqData->params.hasKey("response")) { pbnjson::JValue respArray = pbnjson::Array(); ctxPtr->reqData->params.put("response", respArray); } pbnjson::JValue respArray = ctxPtr->reqData->params["response"]; respArray.append(root); ctxPtr->reqData->params.put("response", respArray); if (ctxPtr->reqData->params.hasKey("nextReq") && ctxPtr->reqData->params["nextReq"].isArray() && (ctxPtr->reqData->params["nextReq"].arraySize() > 0)) { std::string uri = ctxPtr->reqData->params["nextReq"][0]["uri"].asString(); std::string payload = ctxPtr->reqData->params["nextReq"][0]["payload"].asString(); pbnjson::JValue nextReqArr = pbnjson::Array(); for (int i=1; i< ctxPtr->reqData->params["nextReq"].arraySize(); ++i) nextReqArr.append(ctxPtr->reqData->params["nextReq"][i]); ctxPtr->reqData->params.put("nextReq", nextReqArr); LSCall(SAFLunaService::lsHandle, uri.c_str(), payload.c_str(), InternalStorageProvider::onReply, ctxPtr, NULL, &lserror); } else ctxPtr->reqData->cb(ctxPtr->reqData->params["response"], ctxPtr->reqData->subs); } return true; } void InternalStorageProvider::handleRequests(std::shared_ptr<RequestData> reqData) { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); switch(reqData->methodType) { case MethodType::LIST_METHOD: { LOG_DEBUG_SAF("%s : MethodType::LIST_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->listFolderContents(reqData); }); (void)fut; } break; case MethodType::GET_PROP_METHOD: { LOG_DEBUG_SAF("%s : MethodType::GET_PROP_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->getProperties(reqData); }); (void)fut; } break; case MethodType::COPY_METHOD: { LOG_DEBUG_SAF("%s : MethodType::COPY_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->copy(reqData); }); (void)fut; } break; case MethodType::MOVE_METHOD: { LOG_DEBUG_SAF("%s : MethodType::MOVE_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->move(reqData); }); (void)fut; } break; case MethodType::REMOVE_METHOD: { LOG_DEBUG_SAF("%s : MethodType::REMOVE_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->remove(reqData); }); (void)fut; } break; case MethodType::EJECT_METHOD: { LOG_DEBUG_SAF("%s : MethodType::EJECT_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->eject(reqData); }); (void)fut; } break; case MethodType::RENAME_METHOD: { LOG_DEBUG_SAF("%s : MethodType::RENAME_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->rename(reqData); }); (void)fut; } break; case MethodType::LIST_STORAGES_METHOD: { LOG_DEBUG_SAF("%s : MethodType::LIST_STORAGES_METHOD", __FUNCTION__); auto fut = std::async(std::launch::async, [this, reqData]() { return this->listStoragesMethod(reqData); }); (void)fut; } break; default: LOG_DEBUG_SAF("%s : MethodType::UNKNOWN", __FUNCTION__); break; } } void InternalStorageProvider::dispatchHandler() { LOG_DEBUG_SAF("Entering function %s", __FUNCTION__); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::unique_lock < std::mutex > lock(mMutex); do { mCondVar.wait(lock, [this] { return (mQueue.size() || mQuit); }); LOG_DEBUG_SAF("Dispatch notif received : %d, mQuit: %d", mQueue.size(), mQuit); if (mQueue.size() && !mQuit) { lock.unlock(); handleRequests(std::move(mQueue.front())); mQueue.erase(mQueue.begin()); lock.lock(); } } while (!mQuit); }
37.970472
119
0.63461
[ "object" ]
1a6f5541dd08de026dc3bf24caf1d86198f5c1df
45,823
cpp
C++
tao/src/taoModule.cpp
guoxiaoyong/simple-useful
63f483250cc5e96ef112aac7499ab9e3a35572a8
[ "CC0-1.0" ]
null
null
null
tao/src/taoModule.cpp
guoxiaoyong/simple-useful
63f483250cc5e96ef112aac7499ab9e3a35572a8
[ "CC0-1.0" ]
null
null
null
tao/src/taoModule.cpp
guoxiaoyong/simple-useful
63f483250cc5e96ef112aac7499ab9e3a35572a8
[ "CC0-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// /* This file is a part of an interpreter for Tao, a high level object-oriented computing and scripting language. Copyright (C) 2004-2005, Fu Limin. Contact: fu.limin.tao@gmail.com, limin.fu@ircc.it This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <sstream> #include <stdio.h> #include "taoArith.h" #include "taoChain.h" #include "taoClass.h" #include "taoConst.h" #include "taoDatatype.h" #include "taoEnumer.h" #include "taoExtdata.h" #include "taoFuncall.h" #include "taoModule.h" #include "taoObject.h" #include "taoPhrase.h" #include "taoRegex.h" #include "taoScript.h" #include "taoUtility.h" #include "taoLoadlib.h" #include "taoPlugin.h" short TaoModule::RTTI = TAO_Module; short TaoModule::rtti() const { return RTTI; } TaoKeyModWord TaoModule::modKey; TaoKeyModWord::TaoKeyModWord() { rightUnary["++"] = TAO_PPLUS; rightUnary["--"] = TAO_MMINUS; rightUnary["'"] = TAO_TRANSPOSE; rightUnary["~"] = TAO_INVERSE; rightUnary["$"] = TAO_IMAGINARY; leftUnary["++"] = TAO_PPLUS; leftUnary["--"] = TAO_MMINUS; leftUnary["!"] = TAO_NOT; leftUnary["+"] = TAO_PLUS; leftUnary["-"] = TAO_MINUS; leftUnary["$"] = TAO_IMAGINARY; const char *ariopers[] = {"=~", "!~", "~~", "?", ":", ":=", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "&&", "||", "<", ">", "==", "!=", "<=", ">=", "+", "-", "*", "/", "<*>", "</>", "%", "^", "=?", "!?"}; int i; for (i = 0; i < 32; i++) { arithOpers.push_back(ariopers[i]); arithTypes.push_back(i); } arithOpers.insert(arithOpers.begin() + 5, "="); arithTypes.insert(arithTypes.begin() + 5, 5); const char *math[] = {"abs", "acos", "asin", "atan", "cos", "cosh", "exp", "log", "sin", "sinh", "sqrt", "tan", "tanh", "arg", "norm", "rand", "randgs", "srand"}; for (i = 0; i < 18; i++) funcIntern[math[i]] = i + 1; const char *matharr[] = {"max", "min", "mean", "stdev", "varn", "sum", "prod", "count", "permute", "invpermute", "convolute"}; for (i = 0; i < 11; i++) funcIntern[matharr[i]] = i + 20; const char *magic[] = {"apply", "noapply", "iterate", "iterget", "repeat", "sort", "which", "numarray"}; for (i = 0; i < 8; i++) funcIntern[magic[i]] = i + 40; const char *util[] = {"about", "compile", "eval", "import", "load", "system", "type", "number", "pack", "unpack", "time", "astime", "asctime"}; for (i = 0; i < 13; i++) funcIntern[util[i]] = i + 60; const char *inmeth[] = {"erase", "flat", "insert", "keys", "reshape", "resize", "size", "values"}; for (int k = 0; k < 8; k++) methIntern[inmeth[k]] = k + 80; const char *ntype[] = {"byte", "short", "int", "float", "double"}; for (int m = 0; m < 5; m++) numTypeKey[ntype[m]] = m + 1; } TaoModule::TaoModule() { varToNameSpace = 0; routine = 0; routMade = 0; superClass = 0; parsed = 0; infoKit = 0; typeNumeric = TAO_DoubleArray; } void TaoModule::print(ostream *out) { getRoutine()->print(out); } void TaoModule::parseParams() { for (size_t i = 0; i < paramNames.size(); i++) { TaoParamRefer *refer = new TaoParamRefer(); myData[paramNames[i]] = refer; } } TaoRoutine *TaoModule::makeRoutine() { TaoRoutine *pnew = new TaoRoutine(); pnew->name = name; pnew->infoKit = infoKit; pnew->routProto = this; pnew->myData.swap(myData); pnew->myPhrases.swap(myPhrases); pnew->paramNames.swap(paramNames); pnew->setupStatus(); return pnew; } TaoRoutine *TaoModule::getRoutine() { if (!routine) routine = makeRoutine(); return routine; } TaoReference *TaoModule::getClassData(string &dname) { int type; if (superClass) { type = superClass->getDataType(dname); if (type > 0) { return superClass->giveClassData(dname); } else { TaoClass *pclass = superClass; while (pclass->superClass) { pclass = pclass->superClass; type = pclass->getDataType(dname); if (type > 1) return pclass->giveClassData(dname); } } } return 0; } TaoModule *TaoModule::getClassMethod(string &rname) { int type; if (superClass) { type = superClass->getMethType(rname); if (type > 0) { return superClass->getClassMethod(rname); } else { TaoClass *pclass = superClass; while (pclass->superClass) { pclass = pclass->superClass; type = pclass->getMethType(rname); if (type > 1) return pclass->getClassMethod(rname); } } } return 0; } void TaoModule::declareVariable(string &name, int pos) { if (name[0] == '@') { error_general(srcFName, posLine[pos], "transient variables shouldn't be used here"); } if (varType == 1) { // constant data: if (myData.find(name) == myData.end()) { TaoConstRefer *ref = new TaoConstRefer(); myData[name] = ref; outNameSpace->nsData[name] = ref; } } else if (varType == 2) { // shared data: if (TaoReference *ref = inNameSpace->findDataShared(name)) { myData[name] = ref; outNameSpace->nsData[name] = ref; } else { ref = new TaoShareRefer(); myData[name] = ref; outNameSpace->nsDataShared[name] = ref; outNameSpace->nsData[name] = ref; } } else if (varType == 3) { // extern data: if (TaoReference *ref = inNameSpace->findData(name)) { myData[name] = ref; outNameSpace->nsData[name] = ref; } else { error_undefined(srcFName, posLine[pos], "extern data"); } } else if (varType == 4) { // local data: // if(myData.find(name)==myData.end()){ varLocal[scopeLevel][name] = new TaoReference(); //} } else if (myData.find(name) == myData.end()) { if (myWords[pos + 1] == "=" && (myWords[pos + 2] == "open" || myWords[pos + 2] == "compile" || myWords[pos + 2] == "eval" || myWords[pos + 2] == "import" || myWords[pos + 2] == "load")) { TaoConstRefer *ref = new TaoConstRefer(); myData[name] = ref; outNameSpace->nsData[name] = ref; } else { TaoReference *ref = new TaoReference(); myData[name] = ref; if (varToNameSpace) outNameSpace->nsData[name] = ref; } } } TaoReference *TaoModule::getVariable(string &name) { if (varTransient.find(name) != varTransient.end()) { tranUsed++; return varTransient[name]; } for (int i = scopeLevel; i >= 0; i--) { if (varLocal[i].find(name) != varLocal[i].end()) return varLocal[i][name]; } if (myData.find(name) != myData.end()) { return myData[name]; } return 0; } TaoReference *TaoModule::makeVarTransient(int i) { // For transient variables: int id = i; if (id < 0) id = varTransient.size() + 1; stringstream s; s << id; string name = "@" + s.str(); TaoReference *ref = new TaoReference(); varTransient[name] = ref; return ref; } TaoReference *TaoModule::makeVarTransient(const string &name) { TaoReference *ref = new TaoReference(); varTransient[name] = ref; return ref; } bool TaoModule::parsePhrase() { map<string, short> &numTypeKey = modKey.numTypeKey; parsed = 1; // cout<<"parsing routine \""<<name<<"\".\n"; TaoConstRefer *ref = new TaoConstRefer(outNameSpace); myData["this"] = ref; int rbrack; int end; if (myWords.size() == 0) return 1; size_t start = 0; while (start < myWords.size() - 1) { if (myWords[start + 1] != "(") { TaoReference *pbase = getClassData(myWords[start]); // Don't do this: // if( !pbase ) pbase = inNameSpace->findData( myWords[start] ); if (pbase) { myData[myWords[start]] = new TaoDataRefer(pbase); } else { // Use routine or class as variables: TaoBase *p = outNameSpace->findModule(myWords[start]); if (!p) p = inNameSpace->findModule(myWords[start]); if (!p) p = outNameSpace->findClass(myWords[start]); if (!p) p = inNameSpace->findClass(myWords[start]); if (p) { myData[myWords[start]] = new TaoConstRefer(p); } } } else if (start == 0 || (start > 0 && (myWords[start - 1] != "." || myWords[start - 1] != "::"))) { // myWords[start+1]="(" TaoModule *module = getClassMethod(myWords[start]); if (!module) module = outNameSpace->findModule(myWords[start]); if (!module) module = inNameSpace->findModule(myWords[start]); if (module) { preRoutine[myWords[start]] = module; classRoutNames[myWords[start]] = 1; } } start++; } #ifdef DEBUG size_t i; cout << "TaoModule::parsePhrase:\t"; for (i = 0; i < myWords.size(); i++) cout << myWords[i] << " "; cout << "END\n"; #endif varLocal.push_back(map<string, TaoReference *>()); scopeLevel = 0; regexScope.push(0); start = 0; while (start >= 0 && start < myWords.size()) { infoKit = new TaoInfoKit(srcFName, posLine[start]); if (myWords[start] == "while") { TaoWhile *control = new TaoWhile(); if ((rbrack = makeLogicLoop(control, start)) < 0) return 0; start = rbrack + 1; continue; } else if (myWords[start] == "if") { TaoIf *control = new TaoIf(); if ((rbrack = makeLogicLoop(control, start)) < 0) return 0; start = rbrack + 1; continue; } else if (myWords[start] == "else" && myWords[start + 1] == "if") { TaoElseIf *control = new TaoElseIf(); if ((rbrack = makeLogicLoop(control, start)) < 0) return 0; start = rbrack + 1; continue; } else if (myWords[start] == "else") { TaoElse *control = new TaoElse(); myPhrases.push_back(control); control->stepTo = myPhrases.size(); start++; continue; } else if (myWords[start] == "foreach") { TaoForEach *foreach = new TaoForEach(); if ((rbrack = makeForEach(foreach, start)) < 0) return 0; start = rbrack + 1; continue; } else if (myWords[start] == "for") { TaoFor *tfor = new TaoFor; myPhrases.push_back(tfor); int rbrack = wordPair(myWords, "(", ")", start); vector<int> seps(3); seps[0] = findCleanWord(myWords, ",", start + 2, rbrack); seps[1] = findCleanWord(myWords, ";", start + 2, rbrack); seps[2] = findCleanWord(myWords, ":", start + 2, rbrack); sort(seps.begin(), seps.end()); if (seps[1] >= 0 || seps[2] < 0) infoKit->warning("invalid separator in for(...)"); vector<TaoArithBase *> ariths; if (!makeArithArray(ariths, start + 1, rbrack, myWords[seps[2]])) return 0; if (ariths.size() != 3) infoKit->warning("invalid expressions in for(...)"); tfor->first = ariths[0]; tfor->condition = ariths[1]; tfor->step = ariths[2]; tfor->stepTo = myPhrases.size(); tfor->jumpTo = myPhrases.size(); start = rbrack + 1; continue; } else if (myWords[start] == "skip") { TaoSkip *skip = new TaoSkip(); myPhrases.push_back(skip); start += 2; continue; } else if (myWords[start] == "break") { TaoBreak *brk = new TaoBreak(); myPhrases.push_back(brk); start += 2; continue; } if (myWords[start] == "{") { scopeLevel++; varLocal.resize(scopeLevel + 1); LBrace *lb = new LBrace(); myPhrases.push_back(lb); lb->stepTo = myPhrases.size(); start++; continue; } else if (myWords[start] == "}") { scopeLevel--; varLocal.resize(scopeLevel + 1); RBrace *rb = new RBrace(); myPhrases.push_back(rb); rb->stepTo = myPhrases.size(); rb->jumpTo = myPhrases.size(); start++; continue; } if (myWords[start] == "import") { string fname = myWords[start + 3]; if (fname[0] != '"') { cout << "Invalid path\n"; return 0; } fname.erase(fname.end() - 1); fname.erase(fname.begin()); TaoScript tao; tao.readSource(fname.c_str()); TaoNameSpace *ns = new TaoNameSpace(); myData[myWords[start + 1]] = new TaoConstRefer(ns); outNameSpace->nameSpace["imported"] = ns; tao.setNameSpace(ns, ns); if (!tao.compile()) { error_general(srcFName, posLine[start], "importing " + myWords[start + 2] + " failed"); return 0; } start += 5; continue; } if (myWords[start] == "load") { string lbname = myWords[start + 3]; lbname.erase(lbname.end() - 1); lbname.erase(lbname.begin()); TaoLibrary *lib = new TaoLibrary; myData[myWords[start + 1]] = new TaoConstRefer(lib); if (!Tao_DynLoad_Lib(lib, lbname)) { error_general(srcFName, posLine[start + 1], "Cpp Module " + myWords[start + 3] + " loading failed"); return 0; } outNameSpace->nsLibrary[lib->libHandler] = lib; start += 5; continue; } end = findCleanWord(myWords, ";", start); if (end < 0) { error_general(srcFName, posLine[start], "un-parenthesised or ended phrase.\n"); exit(0); } if (myWords[start] == "return" || myWords[start] == "yield") { TaoReturn *retn = 0; if (myWords[start] == "return") retn = new TaoReturn(); else retn = new TaoYield(); retn->infoKit = infoKit; if (!makeArithArray(retn->returnAriths, start, end)) return 0; myPhrases.push_back(retn); retn->stepTo = myPhrases.size(); start = end + 1; continue; } // Parse: // var1,var2,var3; // share var1,var2; varType = 0; if (myWords[start] == "const") { varType = 1; start++; } else if (myWords[start] == "share") { varType = 2; start++; } else if (myWords[start] == "extern") { varType = 3; start++; } else if (myWords[start] == "local") { varType = 4; start++; } bool declare = 0; if (myWords[start + 1] == ",") declare = 1; for (int i = start + 3; i < end; i += 2) { if (myWords[i] != ",") { declare = 0; break; } } if (myWords[start + 1] == ";" || declare) { for (int i = start; i < end; i += 2) { declareVariable(myWords[i], i); } start = end + 1; continue; } int equal; equal = findCleanWord(myWords, "=", start, end); TaoChain *lchain = 0; vector<TaoChain *> chains; varTransient.clear(); if (equal >= 0) { if (myWords[start] == "[" && myWords[equal - 1] == "]") { // For multi-assignment: // [a,b,c]=something; if (!makeChainArray(chains, start, equal - 1)) return 0; for (size_t k = 0; k < chains.size(); k++) { chains[k]->subIdxArray = 0; chains[k]->subIdxNumArray = 0; } } else { // For normal assigment: lchain = new TaoChain(); lchain->subIdxArray = 0; lchain->subIdxNumArray = 0; if ((int)start == equal - 1) declareVariable(myWords[equal - 1], equal - 1); if (!makeChain(lchain, start, equal - 1)) return 0; } // For Parsing: // // a=[10]: "test"; int workpos = equal + 1; ///////////////////////////////////////////////////////////// vector<TaoArithBase *> dimAriths; dimAriths.clear(); // Compile dimension specifier: // {dim1}{dim2}{...} or: // int[dim1][dim2][...] // double[dim1][dim2][...] short typeDim = TAO_DoubleArray; if (numTypeKey.find(myWords[workpos]) != numTypeKey.end()) { typeDim = numTypeKey[myWords[workpos]]; workpos++; } bool isDim = 0; if (myWords[workpos] == "[") { int rb = wordPair(myWords, "[", "]", workpos, end); if (myWords[rb + 1] == "[" || myWords[rb + 1] == ":") isDim = 1; } if (myWords[workpos] == "{" || (myWords[workpos] == "[" && isDim)) { // a={5}: 10; // b={5}: "adf"; // Or: // a=[5][5]: 10; string lchar = "["; string rchar = "]"; if (myWords[workpos] == "{") { lchar = "{"; rchar = "}"; typeDim = 0; } int rb = wordPair(myWords, lchar, rchar, workpos, end); if (rb < 0) { error_unpaired(srcFName, posLine[workpos], lchar + rchar); return 0; } if (rb + 1 < end) { TaoArithBase *dim = makeArithTree(workpos + 1, rb - 1); if (!dim) return 0; dimAriths.push_back(dim); while (myWords[rb + 1] == lchar) { workpos = rb + 1; rb = wordPair(myWords, lchar, rchar, workpos, end); if (rb < 0) { error_unpaired(srcFName, posLine[workpos], lchar + rchar); return 0; } dim = makeArithTree(workpos + 1, rb - 1); if (!dim) return 0; dimAriths.push_back(dim); } if (myWords[rb + 1] != ":") { error_general(srcFName, posLine[rb + 1], "\":\" not found"); return 0; } workpos = rb + 2; } } TaoAssign *assign = new TaoAssign(); TaoArithBase *proto = makeArithTree(workpos, end - 1); if (!proto) return 0; if (varType == 1 || myWords[workpos] == "open" || myWords[workpos] == "compile" || myWords[workpos] == "eval" || myWords[workpos] == "import" || myWords[workpos] == "load") assign->keepConst = 0; assign->rightArith = proto; assign->leftChain = lchain; assign->typeNumeric = typeDim; assign->infoKit = infoKit; assign->dimAriths.swap(dimAriths); assign->lchainArray.swap(chains); myPhrases.push_back(assign); assign->stepTo = myPhrases.size(); start = end + 1; } else { TaoArithPhrase *arithFrase = new TaoArithPhrase(); arithFrase->myArith = makeArithTree(start, end - 1); if (!arithFrase->myArith) return 0; arithFrase->infoKit = infoKit; myPhrases.push_back(arithFrase); arithFrase->stepTo = myPhrases.size(); start = end + 1; } } return setupLogicLoop(); } bool TaoModule::setupLogicLoop() { size_t i; for (i = 0; i < myPhrases.size(); i++) { short rtti = myPhrases[i]->rtti(); if (rtti == TAO_Return || rtti == TAO_Yield) myPhrases[i]->jumpTo = myPhrases.size(); if (rtti == TAO_While || rtti == TAO_ForEach || rtti == TAO_For) { int j = phrasePair(i + 1); // It's checked before, safe now: myPhrases[i]->jumpTo = j + 1; myPhrases[j]->jumpTo = i; } if (rtti == TAO_If || rtti == TAO_ElseIf) { int j = phrasePair(i + 1); myPhrases[i]->jumpTo = j + 1; // It's checked before, safe now: size_t k = j; while (k >= 0 && k < myPhrases.size() - 1 && (myPhrases[k + 1]->rtti() == TAO_ElseIf || myPhrases[k + 1]->rtti() == TAO_Else)) { k = phrasePair(k + 1); if (k >= myPhrases.size() - 1) break; } myPhrases[j]->jumpTo = k + 1; } if (rtti == TAO_Else) { int j = phrasePair(i + 1); myPhrases[j]->jumpTo = j + 1; } } for (i = 0; i < myPhrases.size(); i++) { short type = myPhrases[i]->rtti(); if (type == TAO_Break || type == TAO_Skip) { for (int j = i; j >= 0; j--) { if (myPhrases[j]->rtti() == TAO_While || myPhrases[j]->rtti() == TAO_ForEach || myPhrases[j]->rtti() == TAO_For) { if (type == TAO_Break) myPhrases[i]->jumpTo = myPhrases[j]->jumpTo; if (type == TAO_Skip) myPhrases[i]->jumpTo = j; break; } } } } return 1; } int TaoModule::makeLogicLoop(TaoControl *control, int start) { int lbrack, rbrack; int stop = findWord(myWords, "{", start); lbrack = findWord(myWords, "(", start, stop); rbrack = wordPair(myWords, "(", ")", lbrack, stop); if (lbrack < 0 || rbrack < 0) { error_unpaired(srcFName, posLine[start], "()"); return -1; } control->condition = makeArithTree(lbrack + 1, rbrack - 1); if (!control->condition) return -1; control->infoKit = infoKit; myPhrases.push_back(control); control->stepTo = myPhrases.size(); return rbrack; } bool TaoModule::makeRegex(TaoRegex *regex, int start, int end) { int i, j; string word; for (i = start; i <= end; i++) { if ((myWords[i] == "@" && myWords[i + 1] == "{") || myWords[i] == "[" || myWords[i] == "{" || myWords[i] == "+" || myWords[i] == "*" || myWords[i] == "?" || myWords[i] == "." || myWords[i] == "(") { if (word.length() > 0) { TaoRgxWord *matchWord = new TaoRgxWord(); matchWord->setWord(word); regex->rgxUnit.push_back(matchWord); word.erase(); } if (myWords[i] == "@" && myWords[i + 1] == "{") { TaoRgxArith *match = new TaoRgxArith(); j = wordPair(myWords, "{", "}", i, end); if (j < 0) { error_unpaired(srcFName, posLine[i], "{}"); return 0; } TaoArithBase *arith = makeArithTree(i + 2, j - 1); if (!arith) return 0; match->myArith = arith; regex->rgxUnit.push_back(match); i = j; } else if (myWords[i] == "[") { TaoRgxCharEnum *match = new TaoRgxCharEnum(); j = wordPair(myWords, "[", "]", i, end); if (j < 0) { error_unpaired(srcFName, posLine[i], "[]"); return 0; } string str; for (int k = i + 1; k < j; k++) str += myWords[k]; match->makeStrClass(str, infoKit); regex->rgxUnit.push_back(match); i = j; } else if (myWords[i] == "(") { j = wordPair(myWords, "(", ")", i, end); TaoRgxGroup *group = new TaoRgxGroup(); int last = i + 1; if (myWords[last][0] == '@') { group->transient = makeVarTransient(myWords[last]); last += 2; } int k = findCleanWord(myWords, "|", last, j); while (k >= 0) { TaoRegex *rgx = new TaoRegex; makeRegex(rgx, last, k - 1); group->myRegex.push_back(rgx); last = k + 1; k = findCleanWord(myWords, "|", last, j); } TaoRegex *rgx = new TaoRegex; makeRegex(rgx, last, j - 1); group->myRegex.push_back(rgx); regex->rgxUnit.push_back(group); i = j; } else if (myWords[i] == "{") { j = wordPair(myWords, "{", "}", i, end); if (j < 0) { error_unpaired(srcFName, posLine[i], "{}"); return 0; } int comma = findWord(myWords, ",", i, j); if (comma >= 0) { TaoArithBase *min = makeArithTree(i + 1, comma - 1); if (!min) return 0; regex->rgxUnit[regex->rgxUnit.size() - 1]->minArith = min; if (comma + 1 <= j - 1) { TaoArithBase *max = makeArithTree(comma + 1, j - 1); if (!max) return 0; regex->rgxUnit[regex->rgxUnit.size() - 1]->maxArith = max; } else { regex->rgxUnit[regex->rgxUnit.size() - 1]->repMax = MAX_REPEAT_MATCH; } } else { TaoArithBase *min = makeArithTree(i + 1, j - 1); if (!min) return 0; regex->rgxUnit[regex->rgxUnit.size() - 1]->minArith = min; } i = j; } else if (myWords[i] == "?") { regex->rgxUnit[regex->rgxUnit.size() - 1]->ignorable = 1; regex->rgxUnit[regex->rgxUnit.size() - 1]->repMin = 1; regex->rgxUnit[regex->rgxUnit.size() - 1]->repMax = 1; } else if (myWords[i] == "*") { regex->rgxUnit[regex->rgxUnit.size() - 1]->ignorable = 1; regex->rgxUnit[regex->rgxUnit.size() - 1]->repMin = 1; regex->rgxUnit[regex->rgxUnit.size() - 1]->repMax = MAX_REPEAT_MATCH; } else if (myWords[i] == "+") { regex->rgxUnit[regex->rgxUnit.size() - 1]->repMin = 1; regex->rgxUnit[regex->rgxUnit.size() - 1]->repMax = MAX_REPEAT_MATCH; } else if (myWords[i] == ".") { TaoRgxCharClass *charClass = new TaoRgxCharClass(); charClass->set_escape_char(myWords[i][0]); regex->rgxUnit.push_back(charClass); } } else if (myWords[i] == "\\d" || myWords[i] == "\\D" || myWords[i] == "\\w" || myWords[i] == "\\W" || myWords[i] == "\\c" || myWords[i] == "\\C" || myWords[i] == "\\s" || myWords[i] == "\\S" || myWords[i] == "\\t" || myWords[i] == "\\n") { if (word.length() > 0) { TaoRgxWord *matchWord = new TaoRgxWord(); matchWord->setWord(word); regex->rgxUnit.push_back(matchWord); word.erase(); } TaoRgxCharClass *charClass = new TaoRgxCharClass(); charClass->set_escape_char(myWords[i][1]); regex->rgxUnit.push_back(charClass); } else { if (myWords[i][0] == '\\') word += myWords[i][1]; else word += myWords[i]; } } if (word.length() > 0) { TaoRgxWord *matchWord = new TaoRgxWord(); matchWord->setWord(word); regex->rgxUnit.push_back(matchWord); word.erase(); } return 1; } bool TaoModule::makeChain(TaoChain *chain, int left, int right) { // cout<<"TaoModule::makeChain\t"; // for(int i=left;i<=right;i++) // cout<<myWords[i]<<" "; // cout<<endl; int rbrack; int start = left; chain->infoKit = infoKit; chain->firstName = myWords[left]; // if: func()... // else: obj-> , objs[]... if (myWords[left + 1] == "(") { if (classRoutNames.find(myWords[left]) != classRoutNames.end()) chain->isClassRout = 1; rbrack = wordPair(myWords, "(", ")", left, right); if (rbrack < 0) { error_unpaired(srcFName, posLine[left], "()"); return 0; } TaoFunCall *fun = new TaoFunCall(); fun->funName = myWords[left]; if (!makeFunCall(fun, left, rbrack)) return 0; chain->myChain.push_back(fun); start = rbrack + 1; } else { TaoReference *ref = getVariable(myWords[left]); if (ref) chain->myChain.push_back(ref); else infoKit->error_undefined(myWords[left]); start++; } while (start <= right) { if (myWords[start] == "(") { // obj->FUNCTION(A,B)->more: // ~~~~~~~~~~~~ TaoFunCall *fun = new TaoFunCall(); fun->funName = myWords[start - 1]; rbrack = wordPair(myWords, "(", ")", start, right); if (rbrack < 0) { error_unpaired(srcFName, posLine[start], "()"); return 0; } if (!makeFunCall(fun, start - 1, rbrack)) return 0; chain->myChain.pop_back(); chain->myChain.push_back(fun); start = rbrack + 1; } else if (myWords[start] == "[") { // hash|vector[i]: rbrack = wordPair(myWords, "[", "]", start, right); typeNumeric = TAO_IntArray; if (rbrack < 0) { error_unpaired(srcFName, posLine[left], "[]"); return 0; } TaoArithArray *index = new TaoArithArray(); if (!makeArithArray(index->arithArray, start, rbrack)) return 0; typeNumeric = TAO_DoubleArray; chain->myChain.push_back(index); start = rbrack + 1; } else if (myWords[start] == "." || myWords[start] == "::") { chain->myChain.push_back(new TaoBase()); start++; } else if (myWords[start] == ".?") { chain->myChain.push_back(new TaoOperType()); start++; } else if (myWords[start] == ".#") { chain->myChain.push_back(new TaoOperSizeID()); start++; } else if (myWords[start] == ".&") { chain->myChain.push_back(new TaoOperDerefer()); start++; } else if (myWords[start] == ".%") { chain->myChain.push_back(new TaoOperHashKey()); start++; } else if (myWords[start] == ".@") { chain->myChain.push_back(new TaoOperHashValue()); start++; } else if (myWords[start] == "=~" || myWords[start] == "!~" || myWords[start] == "~~") { TaoRgxMatch *rgx = new TaoRgxMatch(); if (myWords[start] == "=~") rgx->rgxType = 1; else if (myWords[start] == "!~") rgx->rgxType = 2; else if (myWords[start] == "~~") rgx->rgxType = 3; start++; if (myWords[start] == "s") { rgx->replace = 1; start++; } else if (myWords[start] == "gs") { rgx->replaceAll = 1; start++; } if (myWords[start] != "/") error_general(srcFName, posLine[start], "regular expression expected here"); int pos = findCleanWord(myWords, "/", start + 1, right); if (pos < 0) error_general(srcFName, posLine[start], "invalid regular expression"); if (regexScope.size() > 0) { if (regexScope.top() > 0) rgx->restart = 1; regexScope.top()++; } TaoRegex *regular = new TaoRegex; makeRegex(regular, start + 1, pos - 1); rgx->regex = regular; regexScope.top()--; int pos2 = findCleanWord(myWords, "/", pos + 1, right); if (rgx->replace && pos2 < 0) infoKit->warning("invalid regex substitution form"); int pos3 = -1; if (pos2 >= 0) pos3 = findCleanWord(myWords, "/", pos2 + 1, right); if (pos3 >= 0) infoKit->warning("ambigous regex slashes, the last is used"); while (pos3 >= 0) { pos2 = pos3; pos3 = findCleanWord(myWords, "/", pos2 + 1, right); } if (rgx->replace || pos2 > 0) { TaoArithBase *arith = makeArithTree(pos + 1, pos2 - 1); if (!arith) return 0; rgx->strArith = arith; pos = pos2; } chain->myChain.push_back(rgx); start = pos + 1; } else { TaoString *str = new TaoString(myWords[start]); chain->myChain.push_back(str); start++; } } return 1; } bool TaoModule::makeEnumMatrix(TaoEnumMatrix *matx, int lb, int rb) { int last = lb; int semi = findWord(myWords, ";", lb, rb); matx->nRow = 1; while (semi >= 0) { vector<TaoArithBase *> oneRow; matx->nRow++; if (!makeArithArray(oneRow, last, semi)) return 0; if ((int)oneRow.size() > matx->nColumn) matx->nColumn = oneRow.size(); matx->matxAriths.push_back(oneRow); last = semi; semi = findWord(myWords, ";", last + 1, rb); } vector<TaoArithBase *> oneRow; if (!makeArithArray(oneRow, last, rb)) return 0; if ((int)oneRow.size() > matx->nColumn) matx->nColumn = oneRow.size(); matx->matxAriths.push_back(oneRow); return 1; } bool TaoModule::makeFunCall(TaoFunCall *fun, int left, int right) { map<string, int> &funcIntern = modKey.funcIntern; map<string, int> &methIntern = modKey.methIntern; fun->infoKit = infoKit; fun->funName = myWords[left]; fun->defaultNS = outNameSpace; if (funcIntern.find(myWords[left]) != funcIntern.end() && (left == 0 || (myWords[left - 1] != "." && myWords[left - 1] != "::"))) { fun->isInternal = 1; fun->funType = funcIntern[myWords[left]]; } else if (preRoutine.find(myWords[left]) != preRoutine.end()) { fun->preRoutine = preRoutine[myWords[left]]; } else if (methIntern.find(myWords[left]) != methIntern.end()) { fun->funType = methIntern[myWords[left]]; } else if (myWords[left] == "open") { fun->ioType = 0; fun->funType = TAO_open; } else if (myWords[left] == "print") { fun->ioType = 1; fun->funType = TAO_print; } else if (myWords[left] == "read") { fun->ioType = 2; fun->funType = TAO_read; } else if (outNameSpace->findClass(myWords[left])) { fun->myClass = outNameSpace->findClass(myWords[left]); } else if (inNameSpace->findClass(myWords[left])) { fun->myClass = inNameSpace->findClass(myWords[left]); // }else if( inNameSpace->findPlugin( myWords[left] ) ){ // fun->myPlugin=inNameSpace->findPlugin( myWords[left] ); } else if (left == 0 || (myWords[left - 1] != "." && myWords[left - 1] != "::")) { cout << "Warning: unknown function " << myWords[left] << "().\n"; } left = findWord(myWords, "(", left + 1, right); if (fun->funType == TAO_numarray || fun->funType == TAO_arg || fun->funType == TAO_norm) fun->numarrayMaker = new TaoNumArrayMaker; // For transient variables: if (fun->funType == TAO_iterate || fun->funType == TAO_iterget) { fun->transient.push_back(makeVarTransient()); } else if (fun->funType == TAO_sort) { varTransient.clear(); fun->transient.push_back(makeVarTransient()); fun->transient.push_back(makeVarTransient()); } else if (fun->funType == TAO_which || fun->funType == TAO_numarray || fun->funType == TAO_apply || fun->funType == TAO_noapply) { for (size_t i = 0; i < 9; i++) fun->transient.push_back(makeVarTransient()); fun->transient.insert(fun->transient.begin(), makeVarTransient(0)); } else if (fun->funType == TAO_repeat) { regexScope.push(0); } if (!makeArithArray(fun->paramAriths, left, right)) return 0; if (fun->funType == TAO_repeat) regexScope.pop(); return 1; } bool TaoModule::makeChainArray(vector<TaoChain *> &chains, int left, int right) { if (right > left + 1) { int last = left + 1; int comma = findCleanWord(myWords, ",", left + 1, right); while (comma >= 0) { if (myData.find(myWords[last]) == myData.end()) myData[myWords[last]] = new TaoReference(); TaoChain *chn = new TaoChain(); if (!makeChain(chn, last, comma - 1)) return 0; chains.push_back(chn); last = comma + 1; comma = findCleanWord(myWords, ",", comma + 1, right); } if (myData.find(myWords[last]) == myData.end()) myData[myWords[last]] = new TaoReference(); TaoChain *chn = new TaoChain(); if (!makeChain(chn, last, right - 1)) return 0; chains.push_back(chn); } return 1; } bool TaoModule::makeArithArray(vector<TaoArithBase *> &ariths, int left, int right, const string sep) { // for(int i=left;i<=right;i++) // cout<<myWords[i]<<" "; // cout<<"\n"; if (right > left + 1) { int last = left + 1; int comma = findCleanWord(myWords, sep, left + 1, right); while (comma >= 0) { TaoArithBase *node = 0; if (last <= comma - 1) { node = makeArithTree(last, comma - 1); if (!node) return 0; } else { node = new TaoNullArith(); } ariths.push_back(node); last = comma + 1; comma = findCleanWord(myWords, sep, comma + 1, right); } TaoArithBase *node = 0; if (last <= right - 1) { node = makeArithTree(last, right - 1); if (!node) return 0; } else { node = new TaoNullArith(); } ariths.push_back(node); } return 1; } int TaoModule::makeForEach(TaoForEach *foreach, int start) { int lbrack, rbrack; int stop = findWord(myWords, "{", start); lbrack = findWord(myWords, "(", start, stop); rbrack = wordPair(myWords, "(", ")", lbrack, stop); if (lbrack < 0 || rbrack < 0) { error_unpaired(srcFName, posLine[start], "()"); return -1; } int comma = findWord(myWords, ":", lbrack, rbrack); if (comma < 0) { error_general(srcFName, posLine[start], "\":\" is missing"); return -1; } foreach ->elemName = myWords[rbrack - 1]; foreach ->chainArray = new TaoChain(); if (!makeChain(foreach->chainArray, lbrack + 1, comma - 1)) return -1; map<string, TaoReference *>::iterator iter; iter = myData.find(myWords[rbrack - 1]); if (iter != myData.end()) { short rt = iter->second->rtti(); if (rt != TAO_Reference) cout << "Warning: Data type will be changed!\n"; else foreach ->refElement = (TaoReference *)iter->second; } else { foreach ->refElement = new TaoReference(); // myWords[rbrack-1]); myData[myWords[rbrack - 1]] = foreach->refElement; } foreach ->infoKit = infoKit; myPhrases.push_back(foreach); foreach ->stepTo = myPhrases.size(); return rbrack; } int TaoModule::findRootOper(int start, int end, char *optype) { return findCleanWords(myWords, modKey.arithOpers, modKey.arithTypes, start, end, optype); } TaoArithBase *TaoModule::makeArithLeaf(int start) { TaoArithBase *node = NULL; if (getVariable(myWords[start])) { TaoArithVariable *node2 = new TaoArithVariable; node = node2; node2->refVariable = getVariable(myWords[start]); } else if (myWords[start][0] == '@') { // If the transient variable is valid, it should be // returned by getVariable(): error_general(srcFName, posLine[start], "invalid transient variable " + myWords[start]); } else if (myWords[start][0] == '"') { TaoArithString *node2 = new TaoArithString; node = node2; node2->myChars = myWords[start]; node2->myChars.erase(node->myChars.end() - 1); node2->myChars.erase(node->myChars.begin()); node2->myValue = atof(node->myChars.c_str()); node2->bulean = node2->myValue; } else if (isdigit(myWords[start][0])) { TaoArithNumber *node2 = new TaoArithNumber; node = node2; node2->myChars = myWords[start]; node2->myValue = atof(node->myChars.c_str()); node2->bulean = node2->myValue; } else if (myWords[start] == "$") { TaoArithComplex *node2 = new TaoArithComplex; node = node2; node2->cmplx = complex<double>(0, 1); } else if (myWords[start] == ":") { node = new TaoNullArith; } else if (myWords[start + 1] == ":=" || myWords[start + 1] == "=") { TaoReference *ref = new TaoReference; myData[myWords[start]] = ref; TaoArithVariable *node2 = new TaoArithVariable; node = node2; node2->refVariable = ref; } else { error_undefined(srcFName, posLine[start], myWords[start]); return 0; } return node; } TaoArithBase *TaoModule::makeArithNode(int start, int end) { map<string, char> &rightUnary = modKey.rightUnary; map<string, char> &leftUnary = modKey.leftUnary; TaoArithBase *node = 0; stripWordPair(myWords, "(", ")", start, end); char optype; int pos = findRootOper(start, end, &optype); if (start > end) node = new TaoNullArith; else if (start == end) node = makeArithLeaf(start); else if (pos >= 0) { if (myWords[pos] == "=~" || myWords[pos] == "!~" || myWords[pos] == "~~") node = new TaoArithChain; else if (myWords[pos] == ":") node = new TaoPairArith; else if (myWords[pos] == "?") node = new TaoSwitchArith; else { node = new TaoArithNode; if (myWords[pos] == "=") infoKit->warning("\"=\" is used as assignement inside an arith exprs, " "use \":=\" instead"); } } else if (rightUnary.find(myWords[end]) != rightUnary.end()) node = new TaoArithNode; else if (leftUnary.find(myWords[start]) != leftUnary.end()) node = new TaoArithNode; else if ((myWords[start] == "{" && myWords[end] == "}") || (myWords[start] == "[" && myWords[end] == "]")) node = new TaoEnumArith; else node = new TaoArithChain; return node; } TaoArithBase *TaoModule::makeArithTree(int start, int end) { tranUsed = 0; TaoArithBase *arith = makeArithNode(start, end); if (!makeArithTree(arith, start, end)) { delete arith; return 0; } if (tranUsed > 0) arith->nonTrans = 0; return arith; } bool TaoModule::makeArithTree(TaoArithBase *node2, int start, int end) { map<string, char> &rightUnary = modKey.rightUnary; map<string, char> &leftUnary = modKey.leftUnary; node2->infoKit = infoKit; if (start > end) { // node2 must be TaoNullArith: return 1; } #ifdef DEBUG cout << "TaoModule::makeArithTree\n"; for (int i = start; i <= end; i++) cout << myWords[i] << " "; cout << endl; #endif stripWordPair(myWords, "(", ")", start, end); if (start == end) return 1; char optype; int pos = findRootOper(start, end, &optype); if (pos > start && (myWords[pos] == "=~" || myWords[pos] == "!~" || myWords[pos] == "~~")) { TaoArithChain *node = (TaoArithChain *)node2; TaoChain *chain = new TaoChain(); if (!makeChain(chain, start, end)) return 0; node->myChain = chain; } else if (pos >= start && leftUnary.find(myWords[start]) == leftUnary.end()) { TaoArithNode *node = (TaoArithNode *)node2; string opstr = myWords[pos]; int end2 = pos - 1; int start2 = pos + 1; TaoArithBase *left = makeArithNode(start, end2); TaoArithBase *right = makeArithNode(start2, end); if (!makeArithTree(left, start, end2)) return 0; if (!makeArithTree(right, start2, end)) return 0; node->left = left; node->right = right; left->pro = node; right->pro = node; node->oper = optype; } else if (rightUnary.find(myWords[end]) != rightUnary.end()) { TaoArithNode *node = (TaoArithNode *)node2; TaoArithBase *left = makeArithNode(start, end - 1); if (!makeArithTree(left, start, end - 1)) return 0; node->left = left; left->pro = node; node->oper = rightUnary[myWords[end]]; } else if (leftUnary.find(myWords[start]) != leftUnary.end()) { TaoArithNode *node = (TaoArithNode *)node2; TaoArithBase *right = makeArithNode(start + 1, end); if (!makeArithTree(right, start + 1, end)) return 0; node->right = right; right->pro = node; node->oper = leftUnary[myWords[start]]; } else if ((myWords[start] == "{" && myWords[end] == "}") || (myWords[start] == "[" && myWords[end] == "]")) { TaoEnumArith *node = (TaoEnumArith *)node2; // { "a" : 1, "b" : [] }; // {1,2,10} // {1:2:10} // [1,2,10] // [1:2:10] int lb = start; bool isNumeric = 0; if (myWords[start] == "[") { isNumeric = 1; if (myWords[start + 1] == "byte") { lb++; typeNumeric = TAO_ByteArray; } else if (myWords[start + 1] == "short") { lb++; typeNumeric = TAO_ShortArray; } else if (myWords[start + 1] == "int") { lb++; typeNumeric = TAO_IntArray; } else if (myWords[start + 1] == "float") { lb++; typeNumeric = TAO_FloatArray; } else if (myWords[start + 1] == "double") { lb++; typeNumeric = TAO_DoubleArray; } } int rb = end; int colon = findCleanWord(myWords, ",", lb + 1, rb - 1); int comma1 = findCleanWord(myWords, ":", lb + 1, rb - 1); int semi = findCleanWord(myWords, ";", lb + 1, rb - 1); int comma2 = -1; if (comma1 >= 0) comma2 = findCleanWord(myWords, ":", comma1 + 1, rb - 1); if ((colon >= 0 && comma1 >= 0) || (comma1 >= 0 && comma2 < 0)) { // [ "a" : 1, "b" : [] ]; // [:]; TaoEnumHash *hash = new TaoEnumHash; hash->infoKit = infoKit; node->myEnum = hash; if (!makeArithArray(hash->rightAriths, lb, rb)) return 0; } else if (comma2 >= 0) { // [1:2:10] TaoRangeArray *vectde = new TaoRangeArray(); vectde->isNumeric = isNumeric; vectde->typeNumeric = typeNumeric; vectde->infoKit = infoKit; node->myEnum = vectde; if (!makeArithArray(vectde->rightAriths, lb, rb, ":")) return 0; } else if (semi < 0) { // [a,b,c] TaoEnumArray *vectde = new TaoEnumArray(); vectde->isNumeric = isNumeric; vectde->typeNumeric = typeNumeric; vectde->infoKit = infoKit; node->myEnum = vectde; if (!makeArithArray(vectde->rightAriths, lb, rb)) return 0; } else { // (1,2; 3,4) TaoEnumMatrix *matx = new TaoEnumMatrix(); matx->infoKit = infoKit; matx->typeNumeric = typeNumeric; node->myEnum = matx; if (!makeEnumMatrix(matx, lb, rb)) return 0; } } else { TaoArithChain *node = (TaoArithChain *)node2; TaoChain *chain = new TaoChain(); if (!makeChain(chain, start, end)) return 0; node->myChain = chain; } return 1; } int TaoModule::phrasePair(int left) { int k = 0; for (size_t j = left; j < myPhrases.size(); j++) { if (myPhrases[j]->rtti() == TAO_LBrace) k++; else if (myPhrases[j]->rtti() == TAO_RBrace) { k--; if (k == 0) return j; } } return -1; }
30.447176
80
0.542871
[ "object", "vector" ]
2b2ebe2a5d16d8fb89d02df3c8ee00b12d959b69
887
cc
C++
leetcode/Math/perfect_number.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Math/perfect_number.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Math/perfect_number.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <array> #include <climits> #include <cmath> #include <vector> #include "third_party/gflags/include/gflags.h" #include "third_party/glog/include/logging.h" using namespace std; // Problem: // https://leetcode-cn.com/problems/permutation-sequence/ class Solution { public: bool checkPerfectNumber(int num) { return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; } }; class Solution1 { public: bool checkPerfectNumber(int num) { int sum = 0; for (int i = 1; i <= num / 2; ++i) { if (num % i == 0) sum += i; } if (sum == num) return true; return false; } }; int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, false); Solution solu; bool ret = solu.checkPerfectNumber(28); LOG(INFO) << ret; return 0; }
19.711111
64
0.626832
[ "vector" ]
2b3698401da26dd0fc871bff2b367bea2f5c3c21
1,191
hpp
C++
include/src/OperationApplier.hpp
zeta1999/METL-recursed
495aaa610eb7a98fa720429ebccf9bb98abc3e55
[ "Apache-2.0" ]
10
2018-09-09T04:13:12.000Z
2021-04-20T06:23:11.000Z
include/src/OperationApplier.hpp
zeta1999/METL-recursed
495aaa610eb7a98fa720429ebccf9bb98abc3e55
[ "Apache-2.0" ]
3
2018-10-04T01:56:47.000Z
2020-07-01T15:20:26.000Z
include/src/OperationApplier.hpp
zeta1999/METL-recursed
495aaa610eb7a98fa720429ebccf9bb98abc3e55
[ "Apache-2.0" ]
3
2018-09-28T16:04:46.000Z
2020-01-12T10:55:57.000Z
#pragma once #include "src/Utility/get_each.hpp" #include "src/TypeErasure/UntypedExpression.hpp" #include "src/DataBase/CompilerEntityDataBase.hpp" #include "src/Caster.hpp" #include "src/DataBase/UnaryID.hpp" #include "src/DataBase/BinaryID.hpp" #include "src/DataBase/FunctionID.hpp" #include "src/DataBase/SuffixID.hpp" namespace metl { namespace internal { template<class... Ts> class OperationApplier { using Expression = UntypedExpression<Ts...>; public: OperationApplier(const CompilerEntityDataBase<Ts...>& dataBase); template<class IDLabel> UntypedExpression<Ts...> apply(const OperationID<IDLabel>& id, const std::vector<Expression>& arguments) const; private: template<class IDLabel> OperationSignature<IDLabel> findValidSignature(const OperationID<IDLabel>& id, const std::vector<TYPE>& argTypes)const; std::vector<Expression> castIfNecessary(const std::vector<Expression>& expressions, const std::vector<TYPE> types) const; template<class IDLabel> OperationImpl<IDLabel, Ts...> findImpl(const OperationSignature<IDLabel>& sig) const; const CompilerEntityDataBase<Ts...>& dataBase_; const Caster<Ts...> caster_; }; } }
27.068182
124
0.74979
[ "vector" ]
2b387ad69967ad8d60a9a21ab2716c3e5bd753ee
9,396
cpp
C++
Source/CSBackend/Platform/Windows/Core/Base/Device.cpp
angelahnicole/ChilliSource_ParticleOpt
6bee7e091c7635384d6aefbf730a69bbb5b55721
[ "MIT" ]
null
null
null
Source/CSBackend/Platform/Windows/Core/Base/Device.cpp
angelahnicole/ChilliSource_ParticleOpt
6bee7e091c7635384d6aefbf730a69bbb5b55721
[ "MIT" ]
null
null
null
Source/CSBackend/Platform/Windows/Core/Base/Device.cpp
angelahnicole/ChilliSource_ParticleOpt
6bee7e091c7635384d6aefbf730a69bbb5b55721
[ "MIT" ]
null
null
null
// // Device.cpp // Chilli Source // Created by Ian Copland on 24/04/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifdef CS_TARGETPLATFORM_WINDOWS #include <CSBackend/Platform/Windows/Core/Base/Device.h> #include <CSBackend/Platform/Windows/Core/String/WindowsStringUtils.h> #include <algorithm> //this needs to be included last #include <windows.h> #pragma comment(lib, "version.lib" ) namespace CSBackend { namespace Windows { namespace { const std::string k_defaultLocale = "en_US"; const std::string k_defaultLanguage = "en"; //---------------------------------------------- /// @author Ian Copland /// /// @return The device model name. //---------------------------------------------- std::string GetDeviceModel() { return "Windows"; } //---------------------------------------------- /// @author Ian Copland /// /// @return The device model type name. //---------------------------------------------- std::string GetDeviceModelType() { return "PC"; } //---------------------------------------------- /// @author Ian Copland /// /// @return The device manufacturer name. //---------------------------------------------- std::string GetDeviceManufacturer() { return "Microsoft"; } //---------------------------------------------- /// This reads the version info of the /// kernel32.dll system library and pulls the /// OS version from it, as recommended by /// MSDN: /// /// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx /// /// @author Ian Copland /// /// @return The OS version number string. //---------------------------------------------- std::string GetOSVersion() noexcept { // This is based off the answer given by Chuck Walbourn here: http://stackoverflow.com/questions/22303824/warning-c4996-getversionexw-was-declared-deprecated WCHAR path[_MAX_PATH]; if (!GetSystemDirectoryW(path, _MAX_PATH)) { CS_LOG_FATAL("Failed to get the system directory path."); } wcscat_s(path, L"\\kernel32.dll"); DWORD handle; DWORD len = GetFileVersionInfoSizeExW(FILE_VER_GET_NEUTRAL, path, &handle); CS_ASSERT(len > 0, "Failed to get the kernel32.dll file version info size."); std::unique_ptr<uint8_t> buff(new uint8_t[len]); if (!GetFileVersionInfoExW(FILE_VER_GET_NEUTRAL, path, 0, len, buff.get())) { CS_LOG_FATAL("Failed to get the kernel32.dll file version info."); } VS_FIXEDFILEINFO *vInfo = nullptr; UINT infoSize; if (!VerQueryValueW(buff.get(), L"\\", reinterpret_cast<LPVOID*>(&vInfo), &infoSize)) { CS_LOG_FATAL("Failed to query version info."); } if (infoSize == 0) { CS_LOG_FATAL("Info size is 0."); } return ChilliSource::ToString(HIWORD(vInfo->dwFileVersionMS)) + "." + ChilliSource::ToString(LOWORD(vInfo->dwFileVersionMS)) + "." + ChilliSource::ToString(HIWORD(vInfo->dwFileVersionLS)) + "." + ChilliSource::ToString(LOWORD(vInfo->dwFileVersionLS)); } //---------------------------------------------- /// @author Ian Copland /// /// @return The current locale. //---------------------------------------------- std::string GetLocale() { wchar_t localeName[LOCALE_NAME_MAX_LENGTH] = { 0 }; if (GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH * sizeof(wchar_t))) { std::wstring wideLocale(localeName); std::string locale = WindowsStringUtils::UTF16ToUTF8(wideLocale); std::replace(locale.begin(), locale.end(), '-', '_'); return locale; } return k_defaultLocale; } //---------------------------------------------------- /// Returns the language portion of a locale code. /// /// @author Ian Copland /// /// @param The locale code. /// /// @return The language code. //---------------------------------------------------- std::string ParseLanguageFromLocale(const std::string& in_locale) { std::vector<std::string> strLocaleBrokenUp = ChilliSource::StringUtils::Split(in_locale, "_", 0); if (strLocaleBrokenUp.size() > 0) { return strLocaleBrokenUp[0]; } else { return k_defaultLanguage; } } //---------------------------------------------- /// @author Ian Copland /// /// @return The UDID. //---------------------------------------------- std::string GetUDID() { CS_LOG_ERROR("PlatformSystem::GetDeviceID() has not been implemented!"); return "FAKE ID"; } //---------------------------------------------- /// @author Ian Copland /// /// @return The number of cores. //---------------------------------------------- u32 GetNumberOfCPUCores() { SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); return SysInfo.dwNumberOfProcessors; } } CS_DEFINE_NAMEDTYPE(Device); //---------------------------------------------------- //---------------------------------------------------- Device::Device() : m_locale(k_defaultLocale), m_language(k_defaultLanguage) { m_model = CSBackend::Windows::GetDeviceModel(); m_modelType = CSBackend::Windows::GetDeviceModelType(); m_manufacturer = CSBackend::Windows::GetDeviceManufacturer(); m_locale = CSBackend::Windows::GetLocale(); m_language = CSBackend::Windows::ParseLanguageFromLocale(m_locale); m_osVersion = CSBackend::Windows::GetOSVersion(); m_udid = CSBackend::Windows::GetUDID(); m_numCPUCores = CSBackend::Windows::GetNumberOfCPUCores(); } //------------------------------------------------------- //------------------------------------------------------- bool Device::IsA(ChilliSource::InterfaceIDType in_interfaceId) const { return (ChilliSource::Device::InterfaceID == in_interfaceId || Device::InterfaceID == in_interfaceId); } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetModel() const { return m_model; } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetModelType() const { return m_modelType; } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetManufacturer() const { return m_manufacturer; } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetLocale() const { return m_locale; } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetLanguage() const { return m_language; } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetOSVersion() const { return m_osVersion; } //--------------------------------------------------- //--------------------------------------------------- const std::string& Device::GetUDID() const { return m_udid; } //--------------------------------------------------- //--------------------------------------------------- u32 Device::GetNumberOfCPUCores() const { return m_numCPUCores; } } } #endif
35.191011
162
0.474351
[ "vector", "model" ]
2b451fc8cb2ada99e288bc3a7460da8749397cee
1,741
hpp
C++
engine/GLManager.hpp
InfiniBrains/mobagen
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
[ "WTFPL" ]
32
2017-12-29T16:44:35.000Z
2021-08-06T23:10:28.000Z
engine/GLManager.hpp
InfiniBrains/mobagen
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
[ "WTFPL" ]
66
2017-12-29T16:37:35.000Z
2019-04-19T23:57:20.000Z
engine/GLManager.hpp
InfiniBrains/mobagen
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
[ "WTFPL" ]
7
2017-12-29T16:49:53.000Z
2021-08-06T23:10:35.000Z
#pragma once #if defined(GLES2) #include <GLES2/gl2.h> #elif defined(GLES3) #include <GLES3/gl3.h> #else #include <GL/glew.h> #endif #include <vector> #include "Renderer.hpp" #include "SimpleRenderer.hpp" #include "Shader.hpp" #include "Entity.hpp" #include "Window.hpp" #include "Line.hpp" #include "components/Camera.hpp" #include "components/DirectionalLight.hpp" #include "components/PointLight.hpp" #include "components/SpotLight.hpp" namespace mobagen { class GLManager { public: GLManager(std::unique_ptr<Renderer> renderer, const glm::vec2 &windowSize); ~GLManager(void); void setDrawSize(const glm::vec2 &size); void bindRenderTarget(void) const; void renderScene(Entity *entity); void setActiveCamera(std::shared_ptr<Camera> camera); void addDirectionalLight(std::shared_ptr<DirectionalLight> light); void addPointLight(std::shared_ptr<PointLight> light); void addSpotLight(std::shared_ptr<SpotLight> light); void removeDirectionalLight(std::shared_ptr<DirectionalLight> light); void removePointLight(std::shared_ptr<PointLight> light); void removeSpotLight(std::shared_ptr<SpotLight> light); glm::mat4 getViewMatrix(void); glm::mat4 getProjectionMatrix(void); void drawEntity(Entity *entity); void drawLine(Line line); int width, height; GLuint lineBuffer; GLuint VertexArrayID; private: std::unique_ptr<Renderer> m_renderer; std::unique_ptr<SimpleRenderer> m_simpleRenderer; std::shared_ptr<Camera> m_activeCamera; std::vector<std::shared_ptr<DirectionalLight>> m_directionalLights; std::vector<std::shared_ptr<PointLight>> m_pointLights; std::vector<std::shared_ptr<SpotLight>> m_spotLights; }; }
23.527027
79
0.73521
[ "vector" ]
2b466ade2ee98fb31ea4a8194852044a6ee4b553
15,113
cc
C++
src/copy/tasks/scatter_by_slice.cc
marcinz/legate.pandas
94c21c436f59c06cfba454c6569e9f5d7109d839
[ "Apache-2.0" ]
67
2021-04-12T18:06:55.000Z
2022-03-28T06:51:05.000Z
src/copy/tasks/scatter_by_slice.cc
marcinz/legate.pandas
94c21c436f59c06cfba454c6569e9f5d7109d839
[ "Apache-2.0" ]
2
2021-06-22T00:30:36.000Z
2021-07-01T22:12:43.000Z
src/copy/tasks/scatter_by_slice.cc
marcinz/legate.pandas
94c21c436f59c06cfba454c6569e9f5d7109d839
[ "Apache-2.0" ]
6
2021-04-14T21:28:00.000Z
2022-03-22T09:45:25.000Z
/* Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "copy/tasks/scatter_by_slice.h" #include "copy/copy.h" #include "column/detail/column.h" #include "util/allocator.h" #include "util/type_dispatch.h" namespace legate { namespace pandas { namespace copy { using namespace Legion; using ScatterBySliceArg = ScatterBySliceTask::ScatterBySliceTaskArgs::ScatterBySliceArg; void ScatterBySliceTask::ScatterBySliceTaskArgs::sanity_check(void) { auto target_range = range.intersection(requests.front().target.shape()); auto target_volume = target_range.volume(); for (auto &req : requests) { if (!input_is_scalar) assert(req.input.code() == req.target.code()); assert(req.target.shape() == req.output.shape()); if (!input_is_scalar) assert(req.input.num_elements() == target_volume); } } using ColumnView = pandas::detail::Column; namespace detail { struct UpdateRange { coord_t start{0}; coord_t stop{0}; }; UpdateRange compute_update_range(const Rect<1> &target_bounds, const Rect<1> &target_range) { UpdateRange to_update{}; if (!target_bounds.intersection(target_range).empty()) { auto target_range_start = std::min(target_bounds.hi[0], std::max(target_bounds.lo[0], target_range.lo[0])); auto target_range_stop = std::max(target_bounds.lo[0], std::min(target_bounds.hi[0], target_range.hi[0])); to_update.start = target_range_start - target_bounds.lo[0]; to_update.stop = target_range_stop - target_bounds.lo[0] + 1; } return to_update; } template <typename TargetAccessor, typename InputAccessor> struct range_scatter_fn : public thrust::unary_function<coord_t, typename TargetAccessor::value_type> { range_scatter_fn(const UpdateRange &to_update, TargetAccessor &&target, InputAccessor &&input) : to_update_(to_update), target_(target), input_(input) { } typename TargetAccessor::value_type operator()(coord_t idx) { if (to_update_.start <= idx && idx < to_update_.stop) return input_(idx - to_update_.start); else return target_(idx); } UpdateRange to_update_; TargetAccessor target_; InputAccessor input_; }; template <typename TargetAccessor, typename InputAccessor> decltype(auto) make_range_scatter_fn(const UpdateRange &to_update, TargetAccessor &&target, InputAccessor &&input) { return range_scatter_fn<TargetAccessor, InputAccessor>( to_update, std::forward<TargetAccessor>(target), std::forward<InputAccessor>(input)); } template <typename OutputIterator, typename TargetAccessor, typename InputAccessor> void copy_range(OutputIterator &&output, UpdateRange &to_update, TargetAccessor &&target, InputAccessor &&input, size_t size) { auto fn = make_range_scatter_fn( to_update, std::forward<TargetAccessor>(target), std::forward<InputAccessor>(input)); auto start = thrust::make_counting_iterator<coord_t>(0); auto stop = thrust::make_counting_iterator<coord_t>(size); thrust::transform(thrust::host, start, stop, output, fn); } template <typename TargetAccessor, typename InputAccessor> int32_t sum(UpdateRange &to_update, TargetAccessor &&target, InputAccessor &&input, size_t size) { auto fn = make_range_scatter_fn( to_update, std::forward<TargetAccessor>(target), std::forward<InputAccessor>(input)); auto start = thrust::make_transform_iterator(thrust::make_counting_iterator<coord_t>(0), fn); auto stop = thrust::make_transform_iterator(thrust::make_counting_iterator<coord_t>(size), fn); return thrust::reduce(thrust::host, start, stop); } struct CopyRange { template <TypeCode CODE, std::enable_if_t<is_primitive_type<CODE>::value> * = nullptr> ColumnView operator()(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const ColumnView &input, alloc::Allocator &allocator) { using VAL = pandas_type_of<CODE>; auto size = target.size(); auto p_out = allocator.allocate_elements<VAL>(size); auto to_update = compute_update_range(target_bounds, target_range); copy_range(p_out, to_update, accessor_fn<VAL>(target), accessor_fn<VAL>(input), size); auto p_out_b = static_cast<Bitmask::AllocType *>(nullptr); if (target.nullable()) { p_out_b = allocator.allocate_elements<Bitmask::AllocType>(size); if (input.nullable()) copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), bitmask_accessor_fn(input.bitmask()), size); else copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), broadcast_fn<Bitmask::AllocType>(true), size); } return ColumnView(CODE, p_out, size, p_out_b); } template <TypeCode CODE, std::enable_if_t<CODE == TypeCode::STRING> * = nullptr> ColumnView operator()(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const ColumnView &input, alloc::Allocator &allocator) { auto size = target.size(); auto to_update = compute_update_range(target_bounds, target_range); auto num_chars = sum(to_update, size_accessor_fn(target.child(0)), size_accessor_fn(input.child(0)), size); auto p_out_o = allocator.allocate_elements<int32_t>(size + 1); auto p_out_c = allocator.allocate_elements<int8_t>(num_chars); copy_range(p_out_o, to_update, size_accessor_fn(target.child(0)), size_accessor_fn(input.child(0)), size); p_out_o[size] = 0; thrust::exclusive_scan(thrust::host, p_out_o, p_out_o + size + 1, p_out_o); auto fn = make_range_scatter_fn( to_update, accessor_fn<std::string>(target), accessor_fn<std::string>(input)); auto ptr = p_out_c; for (coord_t idx = 0; idx < size; ++idx) { std::string value = fn(idx); memcpy(ptr, value.c_str(), value.size()); ptr += value.size(); } #ifdef DEBUG_PANDAS assert(ptr - p_out_c == num_chars); #endif auto p_out_b = static_cast<Bitmask::AllocType *>(nullptr); if (target.nullable()) { p_out_b = allocator.allocate_elements<Bitmask::AllocType>(size); if (input.nullable()) copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), bitmask_accessor_fn(input.bitmask()), size); else copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), broadcast_fn<Bitmask::AllocType>(true), size); } return ColumnView(TypeCode::STRING, nullptr, size, p_out_b, {ColumnView(TypeCode::INT32, p_out_o, size + 1), ColumnView(TypeCode::INT8, p_out_c, num_chars)}); } template <TypeCode CODE, std::enable_if_t<CODE == TypeCode::CAT32> * = nullptr> ColumnView operator()(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const ColumnView &input, alloc::Allocator &allocator) { assert(false); return ColumnView(); } }; struct BroadcastCopyRange { template <TypeCode CODE, std::enable_if_t<is_primitive_type<CODE>::value> * = nullptr> ColumnView operator()(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const Scalar &input, alloc::Allocator &allocator) { using VAL = pandas_type_of<CODE>; auto size = target.size(); auto p_out = allocator.allocate_elements<VAL>(size); auto to_update = compute_update_range(target_bounds, target_range); copy_range( p_out, to_update, accessor_fn<VAL>(target), broadcast_fn<VAL>(input.value<VAL>()), size); auto p_out_b = static_cast<Bitmask::AllocType *>(nullptr); if (target.nullable()) { p_out_b = allocator.allocate_elements<Bitmask::AllocType>(size); if (input.valid()) copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), broadcast_fn<Bitmask::AllocType>(true), size); else copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), broadcast_fn<Bitmask::AllocType>(false), size); } return ColumnView(CODE, p_out, size, p_out_b); } template <TypeCode CODE, std::enable_if_t<CODE == TypeCode::STRING> * = nullptr> ColumnView operator()(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const Scalar &scalar_input, alloc::Allocator &allocator) { auto size = target.size(); auto input = scalar_input.valid() ? scalar_input.value<std::string>() : std::string(""); auto to_update = compute_update_range(target_bounds, target_range); auto num_chars = sum(to_update, size_accessor_fn(target.child(0)), broadcast_fn<int32_t>(input.size()), size); auto p_out_o = allocator.allocate_elements<int32_t>(size + 1); auto p_out_c = allocator.allocate_elements<int8_t>(num_chars); copy_range(p_out_o, to_update, size_accessor_fn(target.child(0)), broadcast_fn<int32_t>(input.size()), size); p_out_o[size] = 0; thrust::exclusive_scan(thrust::host, p_out_o, p_out_o + size + 1, p_out_o); auto fn = make_range_scatter_fn( to_update, accessor_fn<std::string>(target), broadcast_fn<std::string>(input)); int8_t *ptr = p_out_c; for (coord_t idx = 0; idx < size; ++idx) { std::string value = fn(idx); memcpy(ptr, value.c_str(), value.size()); ptr += value.size(); } #ifdef DEBUG_PANDAS assert(ptr - p_out_c == num_chars); #endif auto p_out_b = static_cast<Bitmask::AllocType *>(nullptr); if (target.nullable()) { p_out_b = allocator.allocate_elements<Bitmask::AllocType>(size); if (scalar_input.valid()) copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), broadcast_fn<Bitmask::AllocType>(true), size); else copy_range(p_out_b, to_update, bitmask_accessor_fn(target.bitmask()), broadcast_fn<Bitmask::AllocType>(false), size); } return ColumnView(TypeCode::STRING, nullptr, size, p_out_b, {ColumnView(TypeCode::INT32, p_out_o, size + 1), ColumnView(TypeCode::INT8, p_out_c, num_chars)}); } template <TypeCode CODE, std::enable_if_t<CODE == TypeCode::CAT32> * = nullptr> ColumnView operator()(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const Scalar &scalar_input, alloc::Allocator &allocator) { assert(false); return ColumnView(); } }; ColumnView copy_range(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const ColumnView &input, alloc::Allocator &allocator) { return type_dispatch( target.code(), CopyRange{}, target_bounds, target_range, target, input, allocator); } ColumnView copy_range(const Rect<1> &target_bounds, const Rect<1> &target_range, const ColumnView &target, const Scalar &scalar_input, alloc::Allocator &allocator) { return type_dispatch(target.code(), BroadcastCopyRange{}, target_bounds, target_range, target, scalar_input, allocator); } } // namespace detail /*static*/ void ScatterBySliceTask::cpu_variant(const Task *task, const std::vector<PhysicalRegion> &regions, Context context, Runtime *runtime) { Deserializer ctx{task, regions}; ScatterBySliceTaskArgs args; deserialize(ctx, args); #ifdef DEBUG_PANDAS assert(args.requests.size() > 0); #endif if (args.requests.front().target.empty()) { for (auto &req : args.requests) req.output.make_empty(true); return; } const auto &bounds = args.requests.front().target.shape(); alloc::DeferredBufferAllocator allocator; for (auto &req : args.requests) { ColumnView result; if (args.input_is_scalar) result = detail::copy_range(bounds, args.range, req.target.view(), req.scalar_input, allocator); else result = detail::copy_range(bounds, args.range, req.target.view(), req.input.view(), allocator); req.output.return_from_view(allocator, result); } } void deserialize(Deserializer &ctx, ScatterBySliceTask::ScatterBySliceTaskArgs &args) { deserialize(ctx, args.input_is_scalar); FromFuture<Rect<1>> range; deserialize(ctx, range); args.range = range.value(); uint32_t num_values = 0; deserialize(ctx, num_values); for (uint32_t i = 0; i < num_values; ++i) { args.requests.push_back(ScatterBySliceArg{}); ScatterBySliceArg &arg = args.requests.back(); deserialize(ctx, arg.output); deserialize(ctx, arg.target); if (args.input_is_scalar) deserialize(ctx, arg.scalar_input); else deserialize(ctx, arg.input); } #ifdef DEBUG_PANDAS args.sanity_check(); #endif } static void __attribute__((constructor)) register_tasks(void) { ScatterBySliceTask::register_variants(); } } // namespace copy } // namespace pandas } // namespace legate
34.115124
99
0.619401
[ "shape", "vector", "transform" ]
2b4d6eb79f3e5080e4bc7876595ae43d95670f24
1,122
cpp
C++
PacManView/src/texture/Texture.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
5
2019-12-23T22:45:46.000Z
2021-11-11T06:27:12.000Z
PacManView/src/texture/Texture.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
null
null
null
PacManView/src/texture/Texture.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
1
2021-11-11T06:27:14.000Z
2021-11-11T06:27:14.000Z
#include "stdafx.h" #include "texture/Texture.h" namespace pacman { namespace view { Texture::Texture(std::unique_ptr<sdl::IResourceWrapper<SDL_Texture>> p_tex, sdl::IDispatcher* p_dispatcher) : _p_tex_resource(std::move(p_tex)), _p_dispatcher(p_dispatcher) { } SDL_Rect Texture::GetDimensions() const { SDL_Rect result; result.x = 0; result.y = 0; this->_p_dispatcher->QueryTexture(this->_p_tex_resource->GetResource(), NULL, NULL, &result.w, &result.h); return result; } void Texture::Render(IRenderer& renderer, SDL_Rect& clip, SDL_Rect& dst, float angle, bool flip_horizontally, bool flip_vertically) const { renderer.RenderCopy(this->_p_tex_resource->GetResource(), &clip, &dst, angle, flip_horizontally, flip_vertically); } } }
23.87234
75
0.502674
[ "render" ]
2b4eb35d15c87df0ada81b85e33db42e187fb7cc
19,289
cpp
C++
agif.cpp
moseymosey/ichabod
3c738daa8734f3daefb0c7da79c98cfead9aff0f
[ "MIT" ]
null
null
null
agif.cpp
moseymosey/ichabod
3c738daa8734f3daefb0c7da79c98cfead9aff0f
[ "MIT" ]
null
null
null
agif.cpp
moseymosey/ichabod
3c738daa8734f3daefb0c7da79c98cfead9aff0f
[ "MIT" ]
null
null
null
#include <stdio.h> #include "agif.h" #include <gif_lib.h> #include "quant.h" #include <iostream> #include <cassert> #include <vector> #include <algorithm> #include <map> #include <QColor> #include <QRgb> #include <QHash> #include <QMultiMap> #include <QPainter> #include <QVariant> typedef QList< QPair<QRgb, int> > QgsColorBox; //Color / number of pixels typedef QMultiMap< int, QgsColorBox > QgsColorBoxMap; // sum of pixels / color box bool redCompare( const QPair<QRgb, int>& c1, const QPair<QRgb, int>& c2 ) { return qRed( c1.first ) < qRed( c2.first ); } bool greenCompare( const QPair<QRgb, int>& c1, const QPair<QRgb, int>& c2 ) { return qGreen( c1.first ) < qGreen( c2.first ); } bool blueCompare( const QPair<QRgb, int>& c1, const QPair<QRgb, int>& c2 ) { return qBlue( c1.first ) < qBlue( c2.first ); } bool alphaCompare( const QPair<QRgb, int>& c1, const QPair<QRgb, int>& c2 ) { return qAlpha( c1.first ) < qAlpha( c2.first ); } bool minMaxRange( const QgsColorBox& colorBox, int& redRange, int& greenRange, int& blueRange, int& alphaRange ) { if ( colorBox.size() < 1 ) { return false; } int rMin = INT_MAX; int gMin = INT_MAX; int bMin = INT_MAX; int aMin = INT_MAX; int rMax = INT_MIN; int gMax = INT_MIN; int bMax = INT_MIN; int aMax = INT_MIN; int currentRed = 0; int currentGreen = 0; int currentBlue = 0; int currentAlpha = 0; QgsColorBox::const_iterator colorBoxIt = colorBox.constBegin(); for ( ; colorBoxIt != colorBox.constEnd(); ++colorBoxIt ) { currentRed = qRed( colorBoxIt->first ); if ( currentRed > rMax ) { rMax = currentRed; } if ( currentRed < rMin ) { rMin = currentRed; } currentGreen = qGreen( colorBoxIt->first ); if ( currentGreen > gMax ) { gMax = currentGreen; } if ( currentGreen < gMin ) { gMin = currentGreen; } currentBlue = qBlue( colorBoxIt->first ); if ( currentBlue > bMax ) { bMax = currentBlue; } if ( currentBlue < bMin ) { bMin = currentBlue; } currentAlpha = qAlpha( colorBoxIt->first ); if ( currentAlpha > aMax ) { aMax = currentAlpha; } if ( currentAlpha < aMin ) { aMin = currentAlpha; } } redRange = rMax - rMin; greenRange = gMax - gMin; blueRange = bMax - bMin; alphaRange = aMax - aMin; return true; } QRgb boxColor( const QgsColorBox& box, int boxPixels ) { double avRed = 0; double avGreen = 0; double avBlue = 0; double avAlpha = 0; QRgb currentColor; int currentPixel; double weight; QgsColorBox::const_iterator colorBoxIt = box.constBegin(); for ( ; colorBoxIt != box.constEnd(); ++colorBoxIt ) { currentColor = colorBoxIt->first; currentPixel = colorBoxIt->second; weight = ( double )currentPixel / boxPixels; avRed += ( qRed( currentColor ) * weight ); avGreen += ( qGreen( currentColor ) * weight ); avBlue += ( qBlue( currentColor ) * weight ); avAlpha += ( qAlpha( currentColor ) * weight ); } return qRgba( avRed, avGreen, avBlue, avAlpha ); } void splitColorBox( QgsColorBox& colorBox, QgsColorBoxMap& colorBoxMap, QMap<int, QgsColorBox>::iterator colorBoxMapIt ) { if ( colorBox.size() < 2 ) { return; //need at least two colors for a split } //a,r,g,b ranges int redRange = 0; int greenRange = 0; int blueRange = 0; int alphaRange = 0; if ( !minMaxRange( colorBox, redRange, greenRange, blueRange, alphaRange ) ) { return; } //sort color box for a/r/g/b if ( redRange >= greenRange && redRange >= blueRange && redRange >= alphaRange ) { qSort( colorBox.begin(), colorBox.end(), redCompare ); } else if ( greenRange >= redRange && greenRange >= blueRange && greenRange >= alphaRange ) { qSort( colorBox.begin(), colorBox.end(), greenCompare ); } else if ( blueRange >= redRange && blueRange >= greenRange && blueRange >= alphaRange ) { qSort( colorBox.begin(), colorBox.end(), blueCompare ); } else { qSort( colorBox.begin(), colorBox.end(), alphaCompare ); } //get median double halfSum = colorBoxMapIt.key() / 2.0; int currentSum = 0; int currentListIndex = 0; QgsColorBox::iterator colorBoxIt = colorBox.begin(); for ( ; colorBoxIt != colorBox.end(); ++colorBoxIt ) { currentSum += colorBoxIt->second; if ( currentSum >= halfSum ) { break; } ++currentListIndex; } if ( currentListIndex > ( colorBox.size() - 2 ) ) //if the median is contained in the last color, split one item before that { --currentListIndex; currentSum -= colorBoxIt->second; } else { ++colorBoxIt; //the iterator needs to point behind the last item to remove } //do split: replace old color box, insert new one QgsColorBox newColorBox1 = colorBox.mid( 0, currentListIndex + 1 ); colorBoxMap.insert( currentSum, newColorBox1 ); colorBox.erase( colorBox.begin(), colorBoxIt ); QgsColorBox newColorBox2 = colorBox; colorBoxMap.erase( colorBoxMapIt ); colorBoxMap.insert( halfSum * 2.0 - currentSum, newColorBox2 ); } void imageColors( QHash<QRgb, int>& colors, const QImage& image ) { colors.clear(); int width = image.width(); int height = image.height(); const QRgb* currentScanLine = 0; QHash<QRgb, int>::iterator colorIt; for ( int i = 0; i < height; ++i ) { currentScanLine = ( const QRgb* )( image.scanLine( i ) ); for ( int j = 0; j < width; ++j ) { colorIt = colors.find( currentScanLine[j] ); if ( colorIt == colors.end() ) { colors.insert( currentScanLine[j], 1 ); } else { colorIt.value()++; } } } } void medianCut( QVector<QRgb>& colorTable, int nColors, const QImage& inputImage ) { QHash<QRgb, int> inputColors; imageColors( inputColors, inputImage ); if ( inputColors.size() <= nColors ) //all the colors in the image can be mapped to one palette color { colorTable.resize( inputColors.size() ); int index = 0; QHash<QRgb, int>::const_iterator inputColorIt = inputColors.constBegin(); for ( ; inputColorIt != inputColors.constEnd(); ++inputColorIt ) { colorTable[index] = inputColorIt.key(); ++index; } return; } //create first box QgsColorBox firstBox; //QList< QPair<QRgb, int> > int firstBoxPixelSum = 0; QHash<QRgb, int>::const_iterator inputColorIt = inputColors.constBegin(); for ( ; inputColorIt != inputColors.constEnd(); ++inputColorIt ) { firstBox.push_back( qMakePair( inputColorIt.key(), inputColorIt.value() ) ); firstBoxPixelSum += inputColorIt.value(); } QgsColorBoxMap colorBoxMap; //QMultiMap< int, ColorBox > colorBoxMap.insert( firstBoxPixelSum, firstBox ); QMap<int, QgsColorBox>::iterator colorBoxMapIt = colorBoxMap.end(); //split boxes until number of boxes == nColors or all the boxes have color count 1 bool allColorsMapped = false; while ( colorBoxMap.size() < nColors ) { //start at the end of colorBoxMap and pick the first entry with number of colors < 1 colorBoxMapIt = colorBoxMap.end(); while ( true ) { --colorBoxMapIt; if ( colorBoxMapIt.value().size() > 1 ) { splitColorBox( colorBoxMapIt.value(), colorBoxMap, colorBoxMapIt ); break; } if ( colorBoxMapIt == colorBoxMap.begin() ) { allColorsMapped = true; break; } } if ( allColorsMapped ) { break; } else { continue; } } //get representative colors for the boxes int index = 0; colorTable.resize( colorBoxMap.size() ); QgsColorBoxMap::const_iterator colorBoxIt = colorBoxMap.constBegin(); for ( ; colorBoxIt != colorBoxMap.constEnd(); ++colorBoxIt ) { colorTable[index] = boxColor( colorBoxIt.value(), colorBoxIt.key() ); ++index; } } std::map<QRgb,int> g_nearest; int nearestColor( int r, int g, int b, const QColor *palette, int size ) { if (palette == 0) return 0; QRgb rgb(qRgb(r, g, b )); if ( g_nearest.find(rgb) != g_nearest.end() ) { return g_nearest[rgb]; } int dr = palette[0].red() - r; int dg = palette[0].green() - g; int db = palette[0].blue() - b; int minDist = dr*dr + dg*dg + db*db; int nearest = 0; for (int i = 1; i < size; i++ ) { dr = palette[i].red() - r; dg = palette[i].green() - g; db = palette[i].blue() - b; int dist = dr*dr + dg*dg + db*db; if ( dist < minDist ) { minDist = dist; nearest = i; } } //g_nearest[rgb] = nearest; return nearest; } QImage& dither(QImage &img, const QColor *palette, int size) { if (img.width() == 0 || img.height() == 0 || palette == 0 || img.depth() <= 8) return img; QImage dImage( img.width(), img.height(), QImage::Format_Indexed8 ); int i; dImage.setNumColors( size ); for ( i = 0; i < size; i++ ) dImage.setColor( i, palette[ i ].rgb() ); int *rerr1 = new int [ img.width() * 2 ]; int *gerr1 = new int [ img.width() * 2 ]; int *berr1 = new int [ img.width() * 2 ]; memset( rerr1, 0, sizeof( int ) * img.width() * 2 ); memset( gerr1, 0, sizeof( int ) * img.width() * 2 ); memset( berr1, 0, sizeof( int ) * img.width() * 2 ); int *rerr2 = rerr1 + img.width(); int *gerr2 = gerr1 + img.width(); int *berr2 = berr1 + img.width(); for ( int j = 0; j < img.height(); j++ ) { uint *ip = (uint * )img.scanLine( j ); uchar *dp = dImage.scanLine( j ); for ( i = 0; i < img.width(); i++ ) { rerr1[i] = rerr2[i] + qRed( *ip ); rerr2[i] = 0; gerr1[i] = gerr2[i] + qGreen( *ip ); gerr2[i] = 0; berr1[i] = berr2[i] + qBlue( *ip ); berr2[i] = 0; ip++; } *dp++ = nearestColor( rerr1[0], gerr1[0], berr1[0], palette, size ); for ( i = 1; i < img.width()-1; i++ ) { int indx = nearestColor( rerr1[i], gerr1[i], berr1[i], palette, size ); *dp = indx; int rerr = rerr1[i]; rerr -= palette[indx].red(); int gerr = gerr1[i]; gerr -= palette[indx].green(); int berr = berr1[i]; berr -= palette[indx].blue(); // diffuse red error rerr1[ i+1 ] += ( rerr * 7 ) >> 4; rerr2[ i-1 ] += ( rerr * 3 ) >> 4; rerr2[ i ] += ( rerr * 5 ) >> 4; rerr2[ i+1 ] += ( rerr ) >> 4; // diffuse green error gerr1[ i+1 ] += ( gerr * 7 ) >> 4; gerr2[ i-1 ] += ( gerr * 3 ) >> 4; gerr2[ i ] += ( gerr * 5 ) >> 4; gerr2[ i+1 ] += ( gerr ) >> 4; // diffuse red error berr1[ i+1 ] += ( berr * 7 ) >> 4; berr2[ i-1 ] += ( berr * 3 ) >> 4; berr2[ i ] += ( berr * 5 ) >> 4; berr2[ i+1 ] += ( berr ) >> 4; dp++; } *dp = nearestColor( rerr1[i], gerr1[i], berr1[i], palette, size ); } delete [] rerr1; delete [] gerr1; delete [] berr1; img = dImage; g_nearest.clear(); return img; } void makeIndexedImage( const QuantizeMethod method, QImage& img, const QVector<QRgb>& current_color_table = QVector<QRgb>() ) { //img.save("/tmp/out_orig.png", "png", 50); switch (method) { case QuantizeMethod_DIFFUSE: { img = img.convertToFormat(QImage::Format_Indexed8, Qt::DiffuseDither); break; } case QuantizeMethod_THRESHOLD: img = img.convertToFormat(QImage::Format_Indexed8, Qt::ThresholdDither); break; case QuantizeMethod_ORDERED: img = img.convertToFormat(QImage::Format_Indexed8, Qt::OrderedDither); break; case QuantizeMethod_MEDIANCUT: case QuantizeMethod_MEDIANCUT_FLOYD: { if ( current_color_table.size() ) { img = img.convertToFormat( QImage::Format_Indexed8, current_color_table ); } else { img = quantize_mediancut(img, (method == QuantizeMethod_MEDIANCUT_FLOYD)); img = img.convertToFormat( QImage::Format_Indexed8 ); } break; } default: assert(false); // everything must be handled break; } if ( img.colorCount() != 256 ) { //std::cerr << "WARNING: forcing color count (" << img.colorCount() << ") to 256" << std::endl; img.setColorCount( 256 ); } } ColorMapObject makeColorMapObject( const QImage& idx8 ) { // color table QVector<QRgb> colorTable = idx8.colorTable(); ColorMapObject cmap; // numColors must be a power of 2 int numColors = 1 << GifBitSize(idx8.colorCount()); cmap.ColorCount = numColors; //std::cout << "numColors:" << numColors << std::endl; cmap.BitsPerPixel = idx8.depth();// should always be 8 if ( cmap.BitsPerPixel != 8 ) { std::cerr << "Incorrect bit depth" << std::endl; return cmap; } GifColorType* colorValues = (GifColorType*)malloc(cmap.ColorCount * sizeof(GifColorType)); cmap.Colors = colorValues; int c = 0; for(; c < idx8.colorCount(); ++c) { //std::cout << "color " << c << " has " << qRed(colorTable[c]) << "," << qGreen(colorTable[c]) << "," << qBlue(colorTable[c]) << std::endl; colorValues[c].Red = qRed(colorTable[c]); colorValues[c].Green = qGreen(colorTable[c]); colorValues[c].Blue = qBlue(colorTable[c]); } // In case we had an actual number of colors that's not a power of 2, // fill the rest with something (black perhaps). for (; c < numColors; ++c) { colorValues[c].Red = 0; colorValues[c].Green = 0; colorValues[c].Blue = 0; } return cmap; } bool gifWrite ( const QuantizeMethod method, const QVector<QImage> & images, const QVector<int>& delays, const QVector<QRect>& crops, const QString& filename, bool loop ) { if ( !images.size() ) { return false; } if ( images.size() != delays.size() ) { std::cerr << "Internal error: images:delays mismatch" << std::endl; return false; } if ( images.size() != crops.size() ) { std::cerr << "Internal error: images:crops mismatch" << std::endl; return false; } QImage initial = images.at(0); QImage base_indexed = initial; makeIndexedImage(method, base_indexed); QVector<QRgb> first_color_table = base_indexed.colorTable(); /* for( QVector<QRgb>::iterator it = first_color_table.begin(); it != first_color_table.end(); ++it ) { QColor c(*it); //std::cout << c.red() << ":" << c.blue() << ":" << c.green() << std::endl; } std::cout << "first_color_table size:" << first_color_table.size() << std::endl; */ int error = 0; GifFileType *gif = EGifOpenFileName(filename.toLocal8Bit().constData(), false, &error); if (!gif) return false; EGifSetGifVersion(gif, true); // global color map ColorMapObject cmap = makeColorMapObject(base_indexed); if (EGifPutScreenDesc(gif, base_indexed.width(), base_indexed.height(), 8, 0, &cmap) == GIF_ERROR) { std::cerr << "EGifPutScreenDesc returned error" << std::endl; return false; } free(cmap.Colors); if ( loop ) { unsigned char nsle[12] = "NETSCAPE2.0"; unsigned char subblock[3]; int loop_count = 0; subblock[0] = 1; subblock[1] = loop_count % 256; subblock[2] = loop_count / 256; if (EGifPutExtensionLeader(gif, APPLICATION_EXT_FUNC_CODE) == GIF_ERROR || EGifPutExtensionBlock(gif, 11, nsle) == GIF_ERROR || EGifPutExtensionBlock(gif, 3, subblock) == GIF_ERROR || EGifPutExtensionTrailer(gif) == GIF_ERROR) { std::cerr << "Error writing loop extension" << std::endl; return false; } } for ( QVector<QImage>::const_iterator it = images.begin(); it != images.end() ; ++it ) { QImage sub; int idx = it-images.begin(); const QRect& crop = crops[idx]; if ( crop.isValid() ) { sub = it->copy( crop ); } else { sub = *it; } makeIndexedImage(method, sub, first_color_table); /* QVector<QRgb> sub_color_table = sub.colorTable(); for( QVector<QRgb>::iterator it = sub_color_table.begin(); it != sub_color_table.end(); ++it ) { QColor c(*it); //std::cout << c.red() << ":" << c.blue() << ":" << c.green() << std::endl; } std::cout << "sub_color_table size:" << sub_color_table.size() << std::endl; if ( sub_color_table != first_color_table ) { std::cerr << "WARNING: sub_color_table table does NOT match first_color_table!" << std::endl; } */ // animation delay int msec_delay = delays.at( idx ); static unsigned char ExtStr[4] = { 0x04, 0x00, 0x00, 0xff }; ExtStr[0] = (false) ? 0x06 : 0x04; ExtStr[1] = msec_delay % 256; ExtStr[2] = msec_delay / 256; EGifPutExtension(gif, GRAPHICS_EXT_FUNC_CODE, 4, ExtStr); // local color map ColorMapObject lcmap = makeColorMapObject(sub); // local image description int local_x = 0; int local_y = 0; int local_w = sub.width(); int local_h = sub.height(); if ( crop.isValid() ) { local_x = crop.x(); local_y = crop.y(); } if (EGifPutImageDesc(gif, local_x, local_y, local_w, local_h, 0, &lcmap) == GIF_ERROR) { std::cerr << "EGifPutImageDesc returned error" << std::endl; } free(lcmap.Colors); int lc = sub.height(); for (int l = 0; l < lc; ++l) { uchar* line = sub.scanLine(l); if (EGifPutLine(gif, (GifPixelType*)line, local_w) == GIF_ERROR) { std::cerr << "EGifPutLine returned error: " << gif->Error << std::endl; } } } EGifCloseFile(gif); return true; }
29.181543
148
0.543419
[ "vector" ]
2b4fc6db4b613cb7a77d89e67154cbf1d1f5587e
7,808
hh
C++
tools/spi_barrier_test/HaloExchange.hh
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
33
2018-12-12T20:05:06.000Z
2021-09-26T13:30:16.000Z
tools/spi_barrier_test/HaloExchange.hh
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
5
2019-04-25T11:34:43.000Z
2021-11-14T04:35:37.000Z
tools/spi_barrier_test/HaloExchange.hh
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
15
2018-12-21T22:44:59.000Z
2021-08-29T10:30:25.000Z
#ifndef HALO_EXCHANGE_HH #define HALO_EXCHANGE_HH #include <vector> #include <cassert> #include "CommTable.hh" #include <iostream> #include "PerformanceTimers.hh" using namespace std; #ifdef SPI #include "spi_impl.h" #endif /** * There are two ways of using this class. The simplest is to call * execute(). This method performs all aspects of the HaloExchange * including tranferring data to the send buffer and leaving the remote * data at the end of the data vector that is passed in. If necessary * the vector will be expanded to make room for the remote elements. * If you call execute() you should not count on any aspect of the * internal state of the HaloExchange * * The other way of calling this class is to do practically everything * yourself. First you need to fill the send buffer. You can either * call fillSendBuffer, or you can get the sendMap and sendBuffer and * do it yourself. Then call startComm() to get the communication going. * Next call wait(). Finally you'll need to getRecvBuf() and put the * data where you actually want it to be. When you're working in this * "advanced" mode the class receives data into an internal buffer * which must be copied out manually before starting the next halo * exchange. */ template <class T, class Allocator = std::allocator<T> > class HaloExchangeBase { public: HaloExchangeBase(const std::vector<int>& sendMap, const CommTable* comm) : width_(sizeof(T)), commTable_(comm), sendMap_(sendMap) { sendBuf_ = new T[commTable_->sendSize()]; recvBuf_ = new T[commTable_->recvSize()*2]; // why 2*? }; ~HaloExchangeBase() { delete [] recvBuf_; delete [] sendBuf_; }; T* getSendBuf() {return sendBuf_;} const vector<int>& getSendMap() const {return sendMap_;} void fillSendBuffer(std::vector<T, Allocator>& data) { startTimer(PerformanceTimers::haloMove2BufTimer); // fill send buffer assert(sendMap_.size() == commTable_->sendSize()); for (unsigned ii=0; ii<sendMap_.size(); ++ii) { sendBuf_[ii]=data[sendMap_[ii]]; } stopTimer(PerformanceTimers::haloMove2BufTimer); }; // void set_recv_buf(int bw) { for (unsigned ii=0; ii<commTable_->recvSize();++ii) {recv_buf_[ii+bw*commTable_->recvSize()]=-1;} } void dumpRecvBuf() { cout << " recv is : "; for (unsigned ii=0; ii<(commTable_->recvSize()) * 2;++ii) {cout << recvBuf_[ii] << " ";} cout << endl; } void dumpSsendBuf() { cout << " send is : "; for (unsigned ii=0; ii<commTable_->sendSize();++ii) {cout << sendBuf_[ii] << " ";} cout << endl; } //virtual void execute(std::vector<T>& data, unsigned nLocal); //virtual void complete(std::vector<T>& data, unsigned nLocal); protected: unsigned width_; const CommTable* commTable_; std::vector<int> sendMap_; T* sendBuf_; T* recvBuf_; }; #ifdef SPI // spi version template <class T, class Allocator = std::allocator<T> > class HaloExchange : public HaloExchangeBase<T, Allocator> { public: HaloExchange(const std::vector<int>& sendMap, const CommTable* comm) : HaloExchangeBase<T, Allocator>(sendMap,comm), bw_(1) { //create mapping table // mapping_table(&spiHdl_); myID=mapping_table_new(&spiHdl_); //setup base address table //search and allocate setup_bat(&spiHdl_,(void*)recvBuf_,commTable_->recvSize()*width_); //setup injection memory fifo //search,allocate,initialize,activate setup_inj_fifo(&spiHdl_); //setup descriptor setup_descriptors(commTable_->_offsets, &(commTable_->_putTask[0]), &(commTable_->_putIdx[0]), commTable_->_putTask.size(), (void*)sendBuf_, commTable_->sendSize(), &spiHdl_,width_); barrier(); }; ~HaloExchange() { free_spi(&spiHdl_); }; T* getRecvBuf() { return &(recvBuf_[bw_*commTable_->recvSize()]); }; void startComm() { bw_=1-bw_; #pragma omp critical execute_spi_alter(&spiHdl_,commTable_->_putTask.size(),bw_); } void execute(vector<T, Allocator>& data, int nLocal) { fillSendBuffer(data); data.resize(nLocal + commTable_->recvSize()); startComm(); wait(); for (int ii=0; ii<commTable_->recvSize(); ++ii) data[nLocal+ii] = recvBuf_[ii]; }; // void execute() // { // bw_=1-bw_; // execute_spi_alter(&spiHdl_,commTable_->_putTask.size(),bw_); // }; void wait() { #pragma omp critical //complete_spi_alter(&spiHdl_, commTable_->_recvTask.size(), commTable_->_offsets[3], bw_, width_ ); complete_spi_alter_monitor(&spiHdl_, commTable_->_recvTask.size(), commTable_->_offsets[3], commTable_->_offsets[4], bw_, width_, myID ); }; // void execute3() {execute_spi(&spiHdl_,commTable_->_putTask.size());}; // void execute2() {execute_spi_2(&spiHdl_,commTable_->_putTask.size());}; // void complete2() {complete_spi(&spiHdl_, commTable_->_recvTask.size());}; // void dump_mapping_table() { spi_dump_mapping( &spiHdl_); }; void barrier() {global_sync(&spiHdl_);}; void barrierWithTimeout(uint64_t timeout) {global_sync_2(&spiHdl_,timeout);}; private: int bw_; spi_hdl_t spiHdl_; uint32_t myID; }; #else // not SPI // MPI version template <class T, class Allocator = std::allocator<T> > class HaloExchange : public HaloExchangeBase<T, Allocator> { public: using HaloExchangeBase<T, Allocator>::commTable_; using HaloExchangeBase<T, Allocator>::sendBuf_; using HaloExchangeBase<T, Allocator>::recvBuf_; using HaloExchangeBase<T, Allocator>::width_; HaloExchange(const std::vector<int>& sendMap, const CommTable* comm) : HaloExchangeBase<T, Allocator>(sendMap,comm), recvReq_(comm->recvSize()), sendReq_(comm->sendSize()) {}; T* getRecvBuf() {return recvBuf_;} void execute(vector<T>& data, int nLocal) { fillSendBuffer(data); T* tmp = recvBuf_; data.resize(nLocal + commTable_->recvSize()); recvBuf_ = (&data[nLocal]); startComm(); wait(); recvBuf_ = tmp; } void startComm() { #pragma omp critical { char* sendBuf = (char*)sendBuf_; char* recvBuf = (char*)recvBuf_; MPI_Request* recvReq = &recvReq_[0]; const int tag = 151515; for (unsigned ii=0; ii< commTable_->_recvTask.size(); ++ii) { assert(recvBuf); unsigned sender = commTable_->_recvTask[ii]; unsigned nItems = commTable_->_recvOffset[ii+1] - commTable_->_recvOffset[ii]; unsigned len = nItems * width_; char* recvPtr = recvBuf + commTable_->_recvOffset[ii]*width_; MPI_Irecv(recvPtr, len, MPI_CHAR, sender, tag, commTable_->_comm, recvReq+ii); } MPI_Request* sendReq = &sendReq_[0]; for (unsigned ii=0; ii<commTable_->_sendTask.size(); ++ii) { assert(sendBuf); unsigned target = commTable_->_sendTask[ii]; unsigned nItems = commTable_->_sendOffset[ii+1] - commTable_->_sendOffset[ii]; unsigned len = nItems * width_; char* sendPtr = sendBuf + commTable_->_sendOffset[ii]*width_; MPI_Isend(sendPtr, len, MPI_CHAR, target, tag, commTable_->_comm, sendReq+ii); } } }; void wait() { #pragma omp critical { MPI_Waitall(commTable_->_sendTask.size(), &sendReq_[0], MPI_STATUS_IGNORE); MPI_Waitall(commTable_->_recvTask.size(), &recvReq_[0], MPI_STATUS_IGNORE); } }; void barrier() { MPI_Barrier(commTable_->_comm); } private: std::vector<MPI_Request> recvReq_; std::vector<MPI_Request> sendReq_; }; #endif // ifdef SPI #endif
29.801527
143
0.644339
[ "vector" ]
2b559d637aaa9500bd6d18d957916c1bc29a939e
3,203
hpp
C++
src/point_instances.hpp
chamini2/IS-PS
f532ee41b836b0eba7b8e9b690314d1878e34616
[ "MIT" ]
null
null
null
src/point_instances.hpp
chamini2/IS-PS
f532ee41b836b0eba7b8e9b690314d1878e34616
[ "MIT" ]
null
null
null
src/point_instances.hpp
chamini2/IS-PS
f532ee41b836b0eba7b8e9b690314d1878e34616
[ "MIT" ]
null
null
null
// Class to define specific problem point classes // These classes need to extend point_interface. #ifndef __POINT_INSTANCES_HPP__ #define __POINT_INSTANCES_HPP__ // #include <algorithm> #include <cstring> #include <iostream> using std::pair; #include <sstream> using std::ostream; #include <set> using std::set; #include <cassert> #include "point_interface.hpp" #include "classifiers.hpp" extern int g_max_label; // Generic point class. // Template argument: Distance function to use class GenericPoint : public PointInterface<int> { public: GenericPoint(const GenericPoint& obj) { class_label_ = obj.class_label_; attributes_ = obj.attributes_; } GenericPoint() : PointInterface<int>(0, vector<double>()) { } GenericPoint(int class_label, vector<double> attributes) : PointInterface<int> (class_label, attributes) { g_max_label = std::max(g_max_label, class_label); } ~GenericPoint() {} float distance(const PointInterface<int>& obj) { return EuclideanDistance(attributes_, obj.attributes()); } static set<GenericPoint> load(const char* filename) { FILE *fp; char *line = NULL; size_t len = 0; int read_chars; set<GenericPoint> points; fp = fopen(filename, "r"); assert(fp != NULL); while ((read_chars = getline(&line, &len, fp)) != -1) { // '^ *@' is the regular expression for comment lines int pos = 0; while (line[pos] == ' ') { ++pos; } // If it's a comment or an empty line if (line[pos] == '@' || pos + 1 == read_chars) { continue; } auto inst_pair = ParseCSV(line); points.insert(GenericPoint(inst_pair.first, inst_pair.second)); } fclose(fp); fp = NULL; free(line); line = NULL; return points; } private: static pair<int, vector<double> > ParseCSV(char* line) { char *next, *field; vector<double> attributes; field = strtok(line, ","); next = strtok(NULL, ","); while (next != NULL) { attributes.push_back(atof(field)); field = next; next = strtok(NULL, ","); } field[strlen(field)-1] = '\0'; int classLabel = atoi(field); return make_pair(classLabel, attributes); } }; inline bool operator<(const GenericPoint& lhs, const GenericPoint& rhs) { int size = lhs.attributes().size(); for (int i = 0; i < size; ++i) { if (lhs.attributes()[i] != rhs.attributes()[i]) { return lhs.attributes()[i] < rhs.attributes()[i]; } } return lhs.ClassLabel() < rhs.ClassLabel(); } inline bool operator==(const GenericPoint& lhs, const GenericPoint& rhs) { if (lhs.attributes().size() != rhs.attributes().size()) return false; int size = lhs.attributes().size(); for (int i = 0; i < size; ++i) { if (lhs.attributes()[i] != rhs.attributes()[i]) { return false; } } return lhs.ClassLabel() == rhs.ClassLabel(); } #endif
24.265152
75
0.573213
[ "vector" ]
2b59dbc67d02c8756b410115b6b219ec20fa25fc
6,799
hpp
C++
develop/v0.2/Ngen/include/Ngen.Type.hpp
archendian/ngensdk
0d8b8e21e00ba71f0596e228dd073017e1c785ed
[ "MIT" ]
1
2017-01-29T09:27:32.000Z
2017-01-29T09:27:32.000Z
develop/v0.2/Ngen/include/Ngen.Type.hpp
archendian/ngensdk
0d8b8e21e00ba71f0596e228dd073017e1c785ed
[ "MIT" ]
15
2017-01-29T05:49:51.000Z
2018-08-12T22:17:04.000Z
develop/v0.2/Ngen/include/Ngen.Type.hpp
archendian/ngensdk
0d8b8e21e00ba71f0596e228dd073017e1c785ed
[ "MIT" ]
null
null
null
/* _______ ________ \ \ / _____/ ____ ___ / | \/ \ ____/ __ \ / \ / | \ \_\ \ ___/| | \ \____|__ /\______ /\___ >___| / \/ \/ \/ \/ The MIT License (MIT) Copyright (c) 2013 Ngeneers Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __NGEN_TYPE_HPP #define __NGEN_TYPE_HPP #include "Ngen.List.hpp" #include "Ngen.Object.hpp" #include "Ngen.StaticDelegate.hpp" //#include "Ngen.Attribute.hpp" namespace Ngen { class Assembly; /** @brief */ class ngen_api Type { public: virtual ~Type() {} /** @brief operator==(Type* const) */ virtual bool operator==(Type* const rhs) const pure; /** @brief operator!=(Type* const) */ virtual bool operator!=(Type* const rhs) const pure; /** @brief Gets the size (in bytes) of the data structure represented by the Type. */ virtual uword Size() const pure; /** @brief Gets the full reflected name of the Type. */ virtual text FullName() const pure; /** @brief Gets the short name of the Type. */ virtual text Name() const pure; /** @brief Gets a human readable string representing a Object known to be of the same Type. */ //virtual text ToText(const Object& _this) const pure; /** @brief Gets a method known to the Type using the given signature. * @param signature The signature of the method nested within the scope of the type. * @return A delegate representing the method that was found. * @throw MissingReferenceException when the method signature could not be resolved to an actual function. */ virtual Delegate* GetMethod(const mirror& signature) const pure; /** @brief Invokes a method known to the Type using the given signature. */ //virtual Object Invoke(const text& signature, Object _this, Object* params) const pure; /** @brief Creates a new default Object instance of the Type. */ virtual Object NewInstance() const pure; /** @brief Creates a new Object instance of the Type using unknown data. * @param data A pointer representing a the data that will encapsulate the new Object. * @param stackBound Determines if the object is stack bound, or heap bound. */ virtual Object NewInstance(unknown data, bool stackBound = true) const pure; /** @brief Creates a new Object instance of the Type from the copy of another same type Object. */ virtual Object CopyInstance(Object copy) const pure; /** @brief Destroys an Object instance of the Type. */ virtual void DestroyInstance(Object _this) const pure; /** @brief Determines if the Type is a base and does not inherit another type. */ virtual bool IsBase() const pure; /** @brief Determines if the Type is considered a primitive structure. */ virtual bool IsPrimitive() const pure; /** @brief Determines if the Type inherits the given Type. * @param parent A mirror that can be used to identify the type expected in the chain of inheritance. * @return True when the type is a child of the type belonging to the given mirror. */ virtual bool IsChildOf(const mirror& parent) const pure; /** @brief Determines if the Type is inherited by the given Type. * @param child A mirror that can be used to identify the type expected in the chain of inheritance. * @return True when the type is a parent of the type belonging to the given mirror. */ virtual bool IsParentOf(const mirror& child) const pure; /** @brief Determines if the Type can always be constructed as an object. */ virtual bool IsConstructable() const pure; /** @brief Determines if the Type is represented as pure namespace, which is always static and can never be constructed. */ virtual bool IsPureNamespace() const pure; /** @brief Determines if the Type can be copied or only referenced. */ virtual bool IsCopyable() const pure; /** @brief Determines if the type is public. */ virtual bool IsPublic() const pure; /** @brief Determines if the type is protected. */ virtual bool IsProtected() const pure; /** @brief Determines if the type is private. */ virtual bool IsPrivate() const pure; /** @brief Determines if the type is a template for new types. */ virtual bool IsTemplate() const pure; /** @brief Determines if the type is a base abstraction for new types. */ virtual bool IsAbstract() const pure; /** @brief Determines if the type is a virtual interface for new types. */ virtual bool IsVirtual() const pure; /** @brief Determines if the type is hidden from external processes. */ virtual bool IsHidden() const pure; /** @brief Determines if the type is the final abstraction in a chain of inheritance. */ virtual bool IsFinal() const pure; /** @brief Determines if the type is nested inside am upper level scope. */ virtual bool IsNested() const pure; /** @brief Gets the assembly where the type is located. */ virtual Assembly* GetAssembly() const pure; /** @brief Gets all the types that inherit this type. */ virtual Array<Type*> GetChildren() const pure; /** @brief Gets all the types that are inherited by this type. */ virtual Array<Type*> GetParents() const pure; /** @brief Gets all the types nested within this type, including non-constructable namespace types. */ virtual Array<Type*> GetNested() const pure; /** @brief Gets the type (or namespace) where the type is nested. */ virtual Type* GetDirectory() const pure; protected: /** @brief Invalidates the data integrity of a given object. * @remarks Used to mark an object instance as bad, in cases where an object is * destroyed, but still being referenced. */ void pInvalidate(Object o) const { if(!isnull(o.mReference)) { o.mReference->IsValid(false); } } }; } #endif // __NGEN_TYPE_HPP
35.046392
122
0.706574
[ "object" ]
2b68639732ec2a9ed6d68bd21c2c328bfb73b93a
1,926
cpp
C++
Programs/Binary_Lifting_Tree_Advanced/binary_lifting.cpp
shivamjha779/Hacktoberfest2021-5
0a900f4390108c818ddb99d60766f974a7838433
[ "MIT" ]
21
2021-10-02T07:10:18.000Z
2022-01-28T08:38:27.000Z
Programs/Binary_Lifting_Tree_Advanced/binary_lifting.cpp
shivamjha779/Hacktoberfest2021-5
0a900f4390108c818ddb99d60766f974a7838433
[ "MIT" ]
19
2021-10-01T17:03:46.000Z
2021-10-20T07:31:36.000Z
Programs/Binary_Lifting_Tree_Advanced/binary_lifting.cpp
shivamjha779/Hacktoberfest2021-5
0a900f4390108c818ddb99d60766f974a7838433
[ "MIT" ]
115
2021-10-01T22:03:58.000Z
2022-01-28T08:38:31.000Z
// PLEASE READ README.TXT BEFORE USING #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define MOD 1000000007 #define FOR(i, a, b) for(ll i=a; i<=b; ++i) #define FORR(i, a, b) for(ll i=a; i>=b; --i) using namespace std; int ROOT; void lift( int root, vector<vector<int>> &tree, vector<int>&parent, int up[][35] , vector<bool>&visited ) { if( root == ROOT ){ FOR(k, 0 , 35-1) { up[root][k] = -1; } }else{ up[root][0]= parent[root]; FOR(k, 1, 35-1) { if(up[root][k-1] == -1) up[root][k] = -1; else up[root][k] = up[up[root][k-1]][k-1]; } } FOR(i, 0, tree[root].size()-1){ if(!visited[tree[root][i]]) { parent[tree[root][i]] = root; visited[tree[root][i]] = 1; lift(tree[root][i], tree, parent, up, visited); } } } int node_at_height(int node, int up[][35], int h ){ if( node <= -1 ) return node; if( h == 0 ) return node; int k =0 ; int temp = h; while( temp%2 == 0) { temp = (temp/2); ++k; } // cout<<"$"<<k<<"$"; return node_at_height( up[node][k] , up , h - (long)(1<<k) ); } int main () { int total_nodes; cin>>total_nodes; vector<vector<int>> tree(total_nodes+1); FOR(i , 1, total_nodes-1){ int u, v ; cin>> u>> v; tree[u].push_back(v); tree[v].push_back(u); } ROOT = 1; // rooting tree at node 1 (global variable) vector<int> parent(total_nodes+1 , -1 ); // vector for storing parent of each node int up[total_nodes+1][35]; memset(up , -1, sizeof(int) * (total_nodes+1) * 35); // up[][] used for precomputation and storing dp values vector<bool> visited(total_nodes+1, 0); visited[1]=true; lift(ROOT, tree, parent , up , visited ); // finally lifting int queries; cin >> queries; while(queries -- ) { int node; cin >> node; int height; cin >> height; cout <<"node at give height from "<<node<< " is "<< node_at_height ( node, up , height )<<endl; } return 0; }
19.454545
137
0.579439
[ "vector" ]
2b698c4fce2f5498a4634877a4693effc754f796
4,512
cpp
C++
cross_section/Product.cpp
fmidev/smartmet-plugin-cross_section
c421523a7f1ba7887d44dc8a229fbf22b4393faa
[ "MIT" ]
null
null
null
cross_section/Product.cpp
fmidev/smartmet-plugin-cross_section
c421523a7f1ba7887d44dc8a229fbf22b4393faa
[ "MIT" ]
null
null
null
cross_section/Product.cpp
fmidev/smartmet-plugin-cross_section
c421523a7f1ba7887d44dc8a229fbf22b4393faa
[ "MIT" ]
null
null
null
#include "Product.h" #include "Config.h" #include "State.h" #include <boost/lexical_cast.hpp> #include <ctpp2/CDT.hpp> #include <macgyver/TimeParser.h> #include <macgyver/Exception.h> #include <spine/HTTP.h> namespace { // ---------------------------------------------------------------------- /*! * \brief Distance between two points along earth surface * * \param theLon1 Longitude of point 1 * \param theLat1 Latitude of point 1 * \param theLon2 Longitude of point 2 * \param theLat2 Latitude of point 2 * \return The distance in kilometers * * Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", * Sky and Telescope, vol. 68, no. 2, 1984, p. 159) * will give mathematically and computationally exact results. The * intermediate result c is the great circle distance in radians. The * great circle distance d will be in the same units as R. * * When the two points are antipodal (on opposite sides of the Earth), * the Haversine Formula is ill-conditioned, but the error, perhaps * as large as 2 km (1 mi), is in the context of a distance near * 20,000 km (12,000 mi). Further, there is a possibility that roundoff * errors might cause the value of sqrt(a) to exceed 1.0, which would * cause the inverse sine to crash without the bulletproofing provided by * the min() function. * * The code was taken from NFmiLocation::Distance */ // ---------------------------------------------------------------------- double torad(double theValue) { return theValue * 3.14159265358979323846 / 180.0; } double geodistance(double theLon1, double theLat1, double theLon2, double theLat2) { double lo1 = torad(theLon1); double la1 = torad(theLat1); double lo2 = torad(theLon2); double la2 = torad(theLat2); double dlon = lo2 - lo1; double dlat = la2 - la1; double sindlat = sin(dlat / 2); double sindlon = sin(dlon / 2); double a = sindlat * sindlat + cos(la1) * cos(la2) * sindlon * sindlon; double help1 = sqrt(a); double c = 2. * asin(std::min(1., help1)); return 6371.220 * c; } } // namespace namespace SmartMet { namespace Plugin { namespace CrossSection { // ---------------------------------------------------------------------- /*! * \brief Initialize the product from JSON */ // ---------------------------------------------------------------------- void Product::init(const Json::Value& theJson, const Config& theConfig) { try { if (!theJson.isObject()) throw Fmi::Exception(BCP, "Product JSON is not a JSON object (name-value pairs)"); // Iterate through all the members const auto members = theJson.getMemberNames(); for (const auto& name : members) { const Json::Value& json = theJson[name]; if (name == "layers") layers.init(json, theConfig); else throw Fmi::Exception(BCP, "Product does not have a setting named '" + name + "'"); } } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } // ---------------------------------------------------------------------- /*! * \brief Generate the product into the template hash tables * */ // ---------------------------------------------------------------------- void Product::generate(CTPP::CDT& theGlobals, State& theState, const SmartMet::Spine::TimeSeriesGenerator::LocalTimeList& theTimes) { try { // Initialize the structure theGlobals["layers"] = CTPP::CDT(CTPP::CDT::HASH_VAL); // Process all times for (const auto& time : theTimes) { theState.time(time); layers.generate(theGlobals, theState); } // Generate bounding box const auto& env = theState.envelope(); if (env.IsInit() != 0) { theGlobals["bbox"] = CTPP::CDT(CTPP::CDT::HASH_VAL); theGlobals["bbox"]["xmin"] = env.MinX; theGlobals["bbox"]["xmax"] = env.MaxX; theGlobals["bbox"]["ymin"] = env.MinY; theGlobals["bbox"]["ymax"] = env.MaxY; } // Distance between the two points theGlobals["distance"] = geodistance(theState.query().longitude1, theState.query().latitude1, theState.query().longitude2, theState.query().latitude2); } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } } // namespace CrossSection } // namespace Plugin } // namespace SmartMet
28.738854
97
0.570922
[ "object" ]
2b6ac182e535344de003e48bc17d78a10e85a35b
334
cpp
C++
PostScript objects/name.cpp
ntclark/PostScript
b8655b0313b43827309b3468df7a5ba2ac6a9deb
[ "BSD-3-Clause" ]
1
2019-06-23T04:38:22.000Z
2019-06-23T04:38:22.000Z
PostScript objects/name.cpp
ntclark/PostScript
b8655b0313b43827309b3468df7a5ba2ac6a9deb
[ "BSD-3-Clause" ]
null
null
null
PostScript objects/name.cpp
ntclark/PostScript
b8655b0313b43827309b3468df7a5ba2ac6a9deb
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 InnoVisioNate Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "PostScript objects\name.h" name::name(char *pszValue) : object(pszValue,object::name) { } name::~name() { return; }
20.875
74
0.628743
[ "object" ]
2b7207ee8169435af4fc099dbd0e6c80b064d3d7
4,411
hpp
C++
PAQ8/Paq8.hpp
Vicshann/Common
f5f5145382ecac5e44459ad9fceb4bc281afd5df
[ "MIT" ]
4
2018-05-22T13:43:34.000Z
2021-12-21T08:33:59.000Z
PAQ8/Paq8.hpp
Vicshann/Common
f5f5145382ecac5e44459ad9fceb4bc281afd5df
[ "MIT" ]
null
null
null
PAQ8/Paq8.hpp
Vicshann/Common
f5f5145382ecac5e44459ad9fceb4bc281afd5df
[ "MIT" ]
3
2020-03-21T10:56:17.000Z
2021-12-24T11:31:10.000Z
#pragma once #include <windows.h> #pragma warning(disable:4554) // warning C4554: '>>': check operator precedence for possible error; use parentheses to clarify precedence namespace NPAQ8 // paq8o10t { #include "PaqUtils.hpp" #include "PaqFilters.hpp" #include "PaqMixer.hpp" #include "PaqCtxMap.hpp" #include "PaqModels.hpp" #include "PaqEncoder.hpp" //================================================================================== // Compress a file // BUG: At level 8 will crash compressing str of size 33 bytes static inline int strm_compress(STRM& SrcStrm, Encoder* en, unsigned long DataSize=0) { if(en->getMode() != COMPRESS)return -1; long start=en->size(); // Transform and test in blocks const int BLOCK=en->getMem()*64; // MEM*64 if(!DataSize) // Rest of source stream { unsigned long savepos = SrcStrm.ftell(); SrcStrm.fseek(0,SEEK_END); DataSize = SrcStrm.ftell(); // 4GB only! SrcStrm.fseek(savepos,SEEK_SET); } for(unsigned long i=0; DataSize > 0; i+=BLOCK) { unsigned long size=BLOCK; if(size > DataSize) size=DataSize; MSTRM tmp; // Base stream is memory stream unsigned long savepos = SrcStrm.ftell(); encode(&SrcStrm, &tmp, size); // Test transform tmp.fseek(0,SEEK_SET); //rewind(tmp); en->setFile(&tmp); SrcStrm.fseek(savepos, SEEK_SET); long j; int c1=0, c2=0; for (j=0; j<size; ++j) { if ((c1=decode(*en))!=(c2=SrcStrm.getc())) break; } // Test fails, compress without transform if (j!=size || tmp.getc()!=STRM::PEOF) { // PRINTF("Transform fails at %ld, input=%d decoded=%d, skipping...\n", i+j, c2, c1); en->compress(0); // Block type en->compress(size>>24); // Block size en->compress(size>>16); en->compress(size>>8); en->compress(size); SrcStrm.fseek(savepos, SEEK_SET); for (int j=0; j<size; ++j) { // printStatus(i+j); en->compress(SrcStrm.getc()); } } else { // Test succeeds, decode(encode(f)) == f, compress tmp tmp.fseek(0,SEEK_SET); //rewind(tmp); int c; j=0; while ((c=tmp.getc())!=STRM::PEOF) { // printStatus(i+j++); en->compress(c); } } DataSize-=size; } en->flush(); return 0; } //---------------------------------------------------------------------------------- // Decompress a file (DataSize is side of COMPRESSED data) static inline int strm_decompress(STRM& DstStrm, Encoder* en, unsigned long DataSize=0) // DataSize is known size of a single file. If 0 then assume that all blocks belong to a single file { if(en->getMode() != DECOMPRESS)return -1; // PRINTF("Extracting %s %ld -> ", filename, filesize); en->ResetDecoderCtx(); unsigned long ArchSize = en->ArchSize(); unsigned long DataEnd = 0; if(DataSize) { DataEnd = en->ArchPos() + DataSize; if(DataEnd > ArchSize)DataEnd = ArchSize; } else DataEnd = ArchSize; while((en->ArchPos() < DataEnd) || en->BlkLeft()) // May be more than one block { DstStrm.putc(decode(*en)); // 'decode' can`t detect end of stream // Why headers read by the same function as a compressed data? } return 0; } //---------------------------------------------------------------------------------- // No reason to compress SrcStrm by a separate blocks here? static inline int strm_compress(int Lvl, STRM& SrcStrm, STRM& DstStrm) // Single file { if(Lvl < 0 || Lvl > 9)return -1; Encoder* en = new Encoder(Lvl, COMPRESS, &DstStrm); int res = strm_compress(SrcStrm, en, 0); delete(en); return res; } //---------------------------------------------------------------------------------- // SrcStrm may be an archive with a separate files // DataSize is size of COMPRESSED data (Includes all file blocks) static inline int strm_decompress(int Lvl, unsigned long DataSize, STRM& SrcStrm, STRM& DstStrm) // DataSize is known size of a single(all of its blocks) file in SrcStrm { if(Lvl < 0 || Lvl > 9)return -1; Encoder* en = new Encoder(Lvl, DECOMPRESS, &SrcStrm); // if(!DataSize)DataSize = SrcStrm.fsize() - SrcStrm.ftell(); // Assume that all block until end of src stream belong to a same file int res = strm_decompress(DstStrm, en, DataSize); delete(en); return res; } //---------------------------------------------------------------------------------- }
34.732283
191
0.575606
[ "transform" ]
2b7976392acdd87546a291d1a7e2370ae8d4c2d2
9,742
cc
C++
src/data/slot_reader.cc
wakensky/parameter_server
12f9e086ca637366fdf3a5e5292ad8234e2b214e
[ "Apache-2.0" ]
null
null
null
src/data/slot_reader.cc
wakensky/parameter_server
12f9e086ca637366fdf3a5e5292ad8234e2b214e
[ "Apache-2.0" ]
null
null
null
src/data/slot_reader.cc
wakensky/parameter_server
12f9e086ca637366fdf3a5e5292ad8234e2b214e
[ "Apache-2.0" ]
null
null
null
#include "data/slot_reader.h" #include "data/example_parser.h" #include "util/threadpool.h" #include "util/filelinereader.h" #include "util/split.h" namespace PS { DEFINE_int32(load_data_max_mb_per_thread, 2 * 1024, "maximum memory usage (MB) allowed for each worker thread " "while downloading data (LOAD_DATA)"); DECLARE_bool(verbose); void SlotReader::init(const DataConfig& data, const DataConfig& cache) { CHECK(data.format() == DataConfig::TEXT); if (cache.file_size()) dump_to_disk_ = true; cache_ = cache.file(0); data_ = data; } string SlotReader::cacheName(const DataConfig& data, int slot_id) const { CHECK_GT(data.file_size(), 0); return cache_ + std::to_string(DJBHash32(data.file(0))) + "-" + \ getFilename(data.file(0)) + "_slot_" + std::to_string(slot_id); } size_t SlotReader::nnzEle(int slot_id) const { size_t nnz = 0; for (int i = 0; i < info_.slot_size(); ++i) { if (info_.slot(i).id() == slot_id) nnz = info_.slot(i).nnz_ele(); } return nnz; } int SlotReader::read(ExampleInfo* info) { CHECK_GT(FLAGS_num_threads, 0); { Lock l(mu_); loaded_file_count_ = 0; } { if (FLAGS_verbose) { for (size_t i = 0; i < data_.file_size(); ++i) { LI << "I will load data file [" << i + 1 << "/" << data_.file_size() << "] [" << data_.file(i) << "]"; } } ThreadPool pool(FLAGS_num_threads); for (int i = 0; i < data_.file_size(); ++i) { auto one_file = ithFile(data_, i); pool.add([this, one_file](){ readOneFile(one_file); }); } pool.startWorkers(); } if (info) *info = info_; for (int i = 0; i < info_.slot_size(); ++i) { slot_info_[info_.slot(i).id()] = info_.slot(i); } return 0; } bool SlotReader::readOneFile(const DataConfig& data) { if (FLAGS_verbose) { Lock l(mu_); LI << "loading data file [" << data.file(0) << "]; loaded [" << loaded_file_count_ << "/" << data_.file_size() << "]"; } string info_name = cache_ + std::to_string(DJBHash32(data.file(0))) + "-" + \ getFilename(data.file(0)) + ".info"; ExampleInfo info; if (readFileToProto(info_name, &info)) { // the data is already in cache_dir Lock l(mu_); info_ = mergeExampleInfo(info_, info); if (FLAGS_verbose) { LI << "loaded data file [" << data.file(0) << "]; loaded [" << loaded_file_count_ << "/" << data_.file_size() << "]"; } return true; } ExampleParser parser; parser.init(data.text(), data.ignore_feature_group()); struct VSlot { SArray<float> val; SArray<uint64> col_idx; SArray<uint16> row_siz; // how many elements in row_siz has been created since construction // used for zero-padding size_t row_siz_total_size; bool writeToFile(const string& name) { return val.compressTo().writeToFile(name+".value") && col_idx.compressTo().writeToFile(name+".colidx") && row_siz.compressTo().writeToFile(name+".rowsiz"); } VSlot() : row_siz_total_size(0) { // do nothing } void clear() { val.clear(); col_idx.clear(); row_siz.clear(); } size_t memSize() { return val.memSize() + col_idx.memSize() + row_siz.memSize(); } bool appendToFile(const string& name) { // lambda: append "start\tsize\n" to the file that contains partition info // We named a compressed block "partition" here auto appendPartitionInfo = [] ( const size_t start, const size_t size, const string& file_name_prefix) { std::stringstream ss; ss << start << "\t" << size << "\n"; File *file = File::open(file_name_prefix + ".partition", "a+"); file->writeString(ss.str()); file->close(); }; string file_name = name + ".value"; size_t start = File::size(file_name); auto val_compressed = val.compressTo(); CHECK(val_compressed.appendToFile(file_name)); appendPartitionInfo(start, val_compressed.dataMemSize(), file_name); file_name = name + ".colidx"; start = File::size(file_name); auto col_compressed = col_idx.compressTo(); CHECK(col_compressed.appendToFile(file_name)); appendPartitionInfo(start, col_compressed.dataMemSize(), file_name); file_name = name + ".rowsiz"; start = File::size(file_name); auto row_compressed = row_siz.compressTo(); CHECK(row_compressed.appendToFile(file_name)); appendPartitionInfo(start, row_compressed.dataMemSize(), file_name); return true; } }; VSlot vslots[kSlotIDmax]; uint32 num_ex = 0; Example ex; // first parse data into slots std::function<void(char*)> handle = [&] (char *line) { if (!parser.toProto(line, &ex)) return; // store them in slots for (int i = 0; i < ex.slot_size(); ++i) { const auto& slot = ex.slot(i); CHECK_LT(slot.id(), kSlotIDmax); auto& vslot = vslots[slot.id()]; int key_size = slot.key_size(); for (int j = 0; j < key_size; ++j) vslot.col_idx.pushBack(slot.key(j)); int val_size = slot.val_size(); for (int j = 0; j < val_size; ++j) vslot.val.pushBack(slot.val(j)); while (vslot.row_siz_total_size < num_ex) { vslot.row_siz.pushBack(0); ++vslot.row_siz_total_size; } vslot.row_siz.pushBack(std::max(key_size, val_size)); ++vslot.row_siz_total_size; } ++ num_ex; }; // invoked by FileLineReader every N lines std::function<void(void*)> periodicity_check_handle = [&] (void*) { // check memory usage size_t mem_size = 0; for (auto& slot : vslots) { mem_size += slot.memSize(); } if (mem_size / 1024 / 1024 < FLAGS_load_data_max_mb_per_thread || 0 == FLAGS_load_data_max_mb_per_thread) { return; } // log if (FLAGS_verbose) { LI << "dumping vslots ... "; } // dump memory image to file // release vslots for (int i = 0; i < kSlotIDmax; ++i) { auto& slot = vslots[i]; if (slot.row_siz.empty() && slot.val.empty()) { continue; } CHECK(slot.appendToFile(cacheName(data, i))); slot.clear(); } // log if (FLAGS_verbose) { LI << "vslots dumped"; } }; FileLineReader reader(data); reader.set_line_callback(handle); reader.set_periodicity_callback(periodicity_check_handle); reader.Reload(); // save in cache info = parser.info(); writeProtoToASCIIFileOrDie(info, info_name); for (int i = 0; i < kSlotIDmax; ++i) { auto& vslot = vslots[i]; if (vslot.row_siz.empty() && vslot.val.empty()) continue; // zero-padding while (vslot.row_siz_total_size < num_ex) { vslot.row_siz.pushBack(0); ++vslot.row_siz_total_size; } CHECK(vslot.appendToFile(cacheName(data, i))); } { Lock l(mu_); info_ = mergeExampleInfo(info_, info); loaded_file_count_++; if (FLAGS_verbose) { LI << "loaded data file [" << data.file(0) << "]; loaded [" << loaded_file_count_ << "/" << data_.file_size() << "]"; } } return true; } SArray<uint64> SlotReader::index(int slot_id) { auto nnz = nnzEle(slot_id); if (nnz == 0) return SArray<uint64>(); SArray<uint64> idx = index_cache_[slot_id]; if (idx.size() == nnz) return idx; for (int i = 0; i < data_.file_size(); ++i) { string file = cacheName(ithFile(data_, i), slot_id) + ".colidx"; SArray<char> comp; CHECK(comp.readFromFile(file)); SArray<uint64> uncomp; { SArray<char> buffer; CHECK(assemblePartitions(buffer, comp, file + ".partition")); uncomp = buffer; } idx.append(uncomp); } CHECK_EQ(idx.size(), nnz); index_cache_[slot_id] = idx; return idx; } SArray<size_t> SlotReader::offset(int slot_id) { if (offset_cache_[slot_id].size() == info_.num_ex()+1) { return offset_cache_[slot_id]; } SArray<size_t> os(1); os[0] = 0; if (nnzEle(slot_id) == 0) return os; for (int i = 0; i < data_.file_size(); ++i) { string file = cacheName(ithFile(data_, i), slot_id) + ".rowsiz"; SArray<char> comp; CHECK(comp.readFromFile(file)); SArray<uint16> uncomp; { SArray<char> buffer; CHECK(assemblePartitions(buffer, comp, file + ".partition")); uncomp = buffer; } size_t n = os.size(); os.resize(n + uncomp.size()); for (size_t i = 0; i < uncomp.size(); ++i) os[i+n] = os[i+n-1] + uncomp[i]; } CHECK_EQ(os.size(), info_.num_ex()+1); offset_cache_[slot_id] = os; return os; } bool SlotReader::assemblePartitions( SArray<char>& out, SArray<char>& in, const string& partition_file_name) const { if (in.empty()) { out.clear(); return true; } // if no corresponding partition file exists, // we simply uncompress the whole SArray if (0 == File::size(partition_file_name)) { out.uncompressFrom(in); return true; } // store partitions' info: {start_byte, size} File* partition_file = File::openOrDie(partition_file_name, "r"); std::vector<std::pair<size_t, size_t> > partitions; const size_t kLineMaxLen = 1024; char line_buffer[kLineMaxLen]; while (nullptr != partition_file->readLine(line_buffer, kLineMaxLen)) { auto vec = split(line_buffer, '\t'); CHECK_EQ(2, vec.size()); partitions.push_back(std::make_pair( std::stoull(vec[0], nullptr), std::stoull(vec[1], nullptr))); } CHECK(!partitions.empty()); // decompress each partition, merge into output for (const auto& partition : partitions) { CHECK_LE(partition.first + partition.second, in.memSize()); SArray<char> decompressed; decompressed.uncompressFrom( in.data() + partition.first, partition.second); out.append(decompressed); } return true; } } // namespace PS
30.34891
81
0.619893
[ "vector" ]
2b7e1a9ceffb1c34e810c15fc0d0dc6d8bdbd4ff
315
cpp
C++
src/bounce/physics/collider/ctor.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
src/bounce/physics/collider/ctor.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
src/bounce/physics/collider/ctor.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
#include <bounce/physics/collider/collider.hpp> Collider::Collider(Transform *parent) : Transform(parent) , _hw(.5) , _hh(.5) , _shape_type(ST_RECT) , _touching_flags(0) , _interaction_mask(1) , _renderable_collider(nullptr) { this->set_shape_rectangle(1.0, 1.0); this->add_tag("collider"); }
22.5
47
0.692063
[ "transform" ]
2b7ff8a116b268f289def9eeb439ddfb88c04065
2,347
cpp
C++
SimulationsOMP/RigidObject/FrictionalContact2D.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
null
null
null
SimulationsOMP/RigidObject/FrictionalContact2D.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
2
2020-10-19T02:03:11.000Z
2021-03-19T16:34:39.000Z
SimulationsOMP/RigidObject/FrictionalContact2D.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
1
2020-04-28T00:33:14.000Z
2020-04-28T00:33:14.000Z
#include "SimulationsOMP_pcp.h" #include "FrictionalContact2D.h" FrictionalContact2D::FrictionalContact2D() : Kn_cont(0.0), Kt_cont(0.0), friction_ratio(0.0) {} FrictionalContact2D::~FrictionalContact2D() {} void FrictionalContact2D::cal_contact_force( // in size_t substp_id, size_t ori_pcl_id, double dist, const Vector2D& norm, const Point2D& cont_pos, double pcl_len, ParticleVariablesGetter& pv_getter, // out size_t& cont_substp_id, Point2D& prev_cont_pos, Vector2D& prev_cont_tan_force, Vector2D& cont_force) { // normal force const double f_cont = Kn_cont * pcl_len * dist; cont_force.x = f_cont * norm.x; cont_force.y = f_cont * norm.y; double& pcd = prev_contact_dist[ori_pcl_id]; if (cont_substp_id != substp_id) // not previously in contact { pcd = 0.0; } else // previously in contact { // local damping const double ddist_sign = sign(dist - pcd); pcd = dist; cont_force.x -= ddist_sign * abs(cont_force.x) * 0.02; cont_force.y -= ddist_sign * abs(cont_force.y) * 0.02; } // tangential force if (cont_substp_id != substp_id) { // not in contacct // record contact position prev_cont_pos.x = cont_pos.x; prev_cont_pos.y = cont_pos.y; // rest contact force prev_cont_tan_force.x = 0.0; prev_cont_tan_force.y = 0.0; } else { // previously in contactt // cal relative movement double rx = cont_pos.x - prev_cont_pos.x; double ry = cont_pos.y - prev_cont_pos.y; prev_cont_pos.x = cont_pos.x; prev_cont_pos.y = cont_pos.y; const double norm_len = rx * norm.x + ry * norm.y; rx -= norm_len * norm.x; ry -= norm_len * norm.y; const double Kt_area = Kt_cont * pcl_len; prev_cont_tan_force.x -= rx * Kt_area; prev_cont_tan_force.y -= ry * Kt_area; // contact consitutive model double tan_force = sqrt(prev_cont_tan_force.x * prev_cont_tan_force.x + prev_cont_tan_force.y * prev_cont_tan_force.y); const double max_tan_force = sqrt(cont_force.x * cont_force.x + cont_force.y * cont_force.y) * friction_ratio; if (tan_force > max_tan_force) { const double ratio = max_tan_force / tan_force; prev_cont_tan_force.x *= ratio; prev_cont_tan_force.y *= ratio; } // add tangential force to contact force cont_force.x += prev_cont_tan_force.x; cont_force.y += prev_cont_tan_force.y; } cont_substp_id = substp_id + 1; }
27.611765
71
0.709842
[ "model" ]
2b8155e13b53f6fac14dcd95184454b0597e5ef9
3,074
cpp
C++
src/Game/Physics/Debugger.cpp
Lexicality/Wulf2012
5bcf42797e6fb0db16107ab134e8b977fc99daed
[ "MIT" ]
6
2015-01-06T13:04:52.000Z
2020-04-21T05:50:01.000Z
src/Game/Physics/Debugger.cpp
Lexicality/Wulf2012
5bcf42797e6fb0db16107ab134e8b977fc99daed
[ "MIT" ]
null
null
null
src/Game/Physics/Debugger.cpp
Lexicality/Wulf2012
5bcf42797e6fb0db16107ab134e8b977fc99daed
[ "MIT" ]
null
null
null
#include "Game/Physics/Debugger.h" #include "Game/Physics/TileData.h" using namespace Wulf; using namespace Wulf::Physics; Debugger::Debugger() { } Debugger::~Debugger() { } // comes from the manager. (This is icky but hey) CollisionObj getObj(const Entity& ent); CollisionObj adjust(const CollisionObj& original, Vector centre) { float x = centre.x; float y = centre.y; CollisionObj ret = { original.Left - x, original.Top - y, original.Right - x, original.Bottom - y }; return ret; } void add(std::vector<float>& buff, const CollisionObj& obj) { buff.push_back(obj.Left); buff.push_back(obj.Bottom); buff.push_back(obj.Left); buff.push_back(obj.Top); buff.push_back(obj.Right); buff.push_back(obj.Top); buff.push_back(obj.Right); buff.push_back(obj.Bottom); } // 2 = number of floats/point; 4 = number of points/square const size_t pointsPerSquare = 2 * 4; const size_t maxNumSquares = 10; void Debugger::UpdateScreen(const Entity& ply, const std::vector<TileData const * const>& tiles) const { if (!mRenderChunk.VAO) return; std::vector<float> buffdata; buffdata.reserve(pointsPerSquare * maxNumSquares); const Vector centre = ply.GetPos(); // Woo!~ add(buffdata, adjust(getObj(ply), centre)); for (const TileData *const tile : tiles) { //if (tile != nullptr && tile->Solid) add(buffdata, adjust(tile->Bounds, centre)); } // Adjust the draw calls etc. numSquares = buffdata.size() / pointsPerSquare; // WOO random opengl GLint prevBuff; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &prevBuff); glBindBuffer(GL_ARRAY_BUFFER, mRenderChunk.VBO); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float) * buffdata.size(), &buffdata[0]); glBindBuffer(GL_ARRAY_BUFFER, prevBuff); } OpenGL::RenderChunk * Debugger::GetRenderChunk(OpenGL::ResourceManager& mgr, glm::mat4 const&) { // Setup mRenderChunk.VAO = mgr.CreateVAO(); mRenderChunk.VBO = mgr.CreateVBO(); mRenderChunk.Program = mgr.LoadShaders("CollisionDebug", "SolidColour"); // We don't use a view uniform mRenderChunk.ViewUniform = -1; // Programatical stuffs glUseProgram(mRenderChunk.Program); { GLuint colourloc = glGetUniformLocation(mRenderChunk.Program, "Colour"); auto a = [](int i) -> GLfloat { return static_cast<GLfloat>(i) / 255; }; glUniform3f(colourloc, a(234), a(92), a(37)); } glUseProgram(0); // OpenGL buffery stuffery glBindVertexArray(mRenderChunk.VAO); glBindBuffer(GL_ARRAY_BUFFER, mRenderChunk.VBO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glBufferData(GL_ARRAY_BUFFER, pointsPerSquare * maxNumSquares * sizeof(float), NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // OpenGL render function indicies = new GLint[maxNumSquares]; counts = new GLsizei[maxNumSquares]; for (int i = 0; i < maxNumSquares; ++i) { indicies[i] = i * 4; counts[i] = 4; } mRenderChunk.RenderFunction = [this](const OpenGL::RenderChunk& self) { if (numSquares > 0) glMultiDrawArrays(GL_LINE_LOOP, indicies, counts, numSquares); }; return &mRenderChunk; }
26.730435
103
0.725439
[ "render", "vector", "solid" ]
2b966288017100fa3a7c3b52d71c190512df9ef8
389
cpp
C++
solutions/443.string-compression.324046769.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/443.string-compression.324046769.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/443.string-compression.324046769.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int compress(vector<char> &chars) { int l = 0; int c = 1; for (int i = 1; i <= chars.size(); i++) { if (i == chars.size() || chars[i] != chars[i - 1]) { chars[l++] = chars[i - 1]; if (c > 1) for (char j : to_string(c)) chars[l++] = j; c = 1; } else c++; } return l; } };
17.681818
58
0.398458
[ "vector" ]
2b994d16ac408fce94e02405fef8db3455ace5fb
446
cpp
C++
ArthurProject/src/Nodes/AudioSource.cpp
JackiBackiBoy/ArthurProject
88c5a7365cb3edc768a88f9a71a8f29751a1d75e
[ "Apache-2.0" ]
null
null
null
ArthurProject/src/Nodes/AudioSource.cpp
JackiBackiBoy/ArthurProject
88c5a7365cb3edc768a88f9a71a8f29751a1d75e
[ "Apache-2.0" ]
null
null
null
ArthurProject/src/Nodes/AudioSource.cpp
JackiBackiBoy/ArthurProject
88c5a7365cb3edc768a88f9a71a8f29751a1d75e
[ "Apache-2.0" ]
null
null
null
#include "AudioSource.h" #include "Managers/AssetManager.h" #include "data/Options.h" void AudioSource::Play(std::string aString) { mySounds.push_back(sf::Sound(AssetManager::GetSoundBuffer(aString))); mySounds.back().setVolume(Options::GetSoundEffectVolume()); mySounds.back().play(); } AudioSource::AudioSource(const sf::Vector2f& aPosition, const std::string& aName) : Node(aPosition, aName) { mySounds = std::vector<sf::Sound>(); }
22.3
106
0.737668
[ "vector" ]
2ba816c45ae4aa3ebc8f8e799f9e4ce08698a74f
844
cc
C++
Code/2188-minimized-maximum-of-products-distributed-to-any-store.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/2188-minimized-maximum-of-products-distributed-to-any-store.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/2188-minimized-maximum-of-products-distributed-to-any-store.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { public: int minimizedMaximum(int n, vector<int>& quantities) { int low = 1; int high = 1; for (auto &quantity : quantities) { high = max(high, quantity); } int middle; while (low < high - 1) { middle = (low + high) / 2; int count = 0; for (auto &quantity : quantities) { count += ceil((double)quantity / middle); } if (count > n) { low = middle; } else { high = middle; } } int lastCount = 0; for (auto &quantity : quantities) { lastCount += ceil((double)quantity / low); } if (lastCount > n) { return high; } else { return low; } } };
26.375
58
0.418246
[ "vector" ]
ad953d2a0e8ffbc267dce7f6512bf3ff5632ceca
3,761
cpp
C++
test/test_basics.cpp
OpenCL/ComplexMath
e0b0d11471478341c21bbad6811ca92ba7258aeb
[ "MIT" ]
6
2017-05-11T07:10:35.000Z
2021-05-24T00:38:06.000Z
test/test_basics.cpp
OpenCL/ComplexMath
e0b0d11471478341c21bbad6811ca92ba7258aeb
[ "MIT" ]
1
2016-12-28T03:21:08.000Z
2017-04-14T15:49:45.000Z
test/test_basics.cpp
OpenCL/ComplexMath
e0b0d11471478341c21bbad6811ca92ba7258aeb
[ "MIT" ]
2
2019-05-13T14:21:49.000Z
2020-01-10T02:12:17.000Z
//---------------------------------------------------------------------------// // MIT License // // Copyright (c) 2017 StreamComputing // // 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. //---------------------------------------------------------------------------// #define BOOST_TEST_MODULE TestBasics #include <boost/test/unit_test.hpp> #include <boost/compute/core.hpp> #include <boost/compute/system.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/utility/source.hpp> #include <boost/compute/container/vector.hpp> struct OpenCLContext { boost::compute::device device; boost::compute::context context; boost::compute::command_queue queue; OpenCLContext() : device (boost::compute::system::default_device()), context(boost::compute::system::default_context()), queue (boost::compute::system::default_queue()) {} }; BOOST_FIXTURE_TEST_SUITE(complex_numbers_test, OpenCLContext) BOOST_AUTO_TEST_CASE(test_create) { namespace bc = boost::compute; boost::compute::vector<bc::float_> reals(context); boost::compute::vector<bc::float_> imags(context); reals.push_back(bc::float_(1.0f), queue); reals.push_back(bc::float_(2.0f), queue); reals.push_back(bc::float_(-3.0f), queue); reals.push_back(bc::float_(4.0f), queue); imags.push_back(bc::float_(-1.0f), queue); imags.push_back(bc::float_(2.0f), queue); imags.push_back(bc::float_(3.0f), queue); imags.push_back(bc::float_(-4.0f), queue); boost::compute::vector<bc::float2_> complexs(size_t(4), context); std::string source = "#include \"clcomplex.h\"\n"; source += BOOST_COMPUTE_STRINGIZE_SOURCE( __kernel void test_kernel(__global float * reals, __global float * imags, __global float2 * complexs) { const uint i = get_global_id(0); complexs[i] = complexf(reals[i], imags[i]); } ); std::string options = "-I" + std::string(OPENCL_COMPLEX_MATH_DIR); bc::program program = bc::program::build_with_source( source, context, options ); bc::kernel k = program.create_kernel("test_kernel"); k.set_args( reals.get_buffer(), imags.get_buffer(), complexs.get_buffer() ); queue.enqueue_1d_range_kernel(k, 0, complexs.size(), 0).wait(); BOOST_CHECK_EQUAL(bc::float2_(complexs[0]), bc::float2_(1.0f, -1.0f)); BOOST_CHECK_EQUAL(bc::float2_(complexs[1]), bc::float2_(2.0f, 2.0f)); BOOST_CHECK_EQUAL(bc::float2_(complexs[2]), bc::float2_(-3.0f, 3.0f)); BOOST_CHECK_EQUAL(bc::float2_(complexs[3]), bc::float2_(4.0f, -4.0f)); } BOOST_AUTO_TEST_SUITE_END()
38.377551
81
0.657272
[ "vector" ]
ad9d754c54d01baa320a86d39f9676dadba52b55
14,631
hpp
C++
include/src/Core/Block/SparseBlockMatrixBase.impl.hpp
sjokic/WallDestruction
2e1c000096df4aa027a91ff1732ce50a205b221a
[ "MIT" ]
1
2021-11-03T11:30:05.000Z
2021-11-03T11:30:05.000Z
include/src/Core/Block/SparseBlockMatrixBase.impl.hpp
sjokic/WallDestruction
2e1c000096df4aa027a91ff1732ce50a205b221a
[ "MIT" ]
null
null
null
include/src/Core/Block/SparseBlockMatrixBase.impl.hpp
sjokic/WallDestruction
2e1c000096df4aa027a91ff1732ce50a205b221a
[ "MIT" ]
null
null
null
/* * This file is part of bogus, a C++ sparse block matrix library. * * Copyright 2013 Gilles Daviet <gdaviet@gmail.com> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef BOGUS_SPARSE_BLOCK_MATRIX_BASE_IMPL_HPP #define BOGUS_SPARSE_BLOCK_MATRIX_BASE_IMPL_HPP #include "Access.hpp" #include "SparseBlockMatrixBase.hpp" #include "SparseBlockIndexComputer.hpp" #include "../Utils/CppTools.hpp" #include <algorithm> namespace bogus { // Finalizer template < bool Symmetric > struct SparseBlockMatrixFinalizer { template <typename T> static void finalize( const T& ) { } } ; template < > struct SparseBlockMatrixFinalizer< true > { template < typename Derived > static void finalize( SparseBlockMatrixBase< Derived >& matrix ) { matrix.computeMinorIndex() ; } } ; // Sparse Block Matrix template < typename Derived > const typename BlockMatrixBase< Derived >::BlockPtr BlockMatrixBase< Derived >::InvalidBlockPtr( -1 ); template < typename Derived > typename SparseBlockMatrixBase< Derived >::RowIndexType &SparseBlockMatrixBase< Derived >::rowMajorIndex( ) { return SparseBlockIndexGetter< Derived, !Traits::is_col_major >::get( *this ) ; } template < typename Derived > typename SparseBlockMatrixBase< Derived >::ColIndexType &SparseBlockMatrixBase< Derived >::colMajorIndex( ) { return SparseBlockIndexGetter< Derived, Traits::is_col_major >::get( *this ) ; } template < typename Derived > const typename SparseBlockMatrixBase< Derived >::RowIndexType &SparseBlockMatrixBase< Derived >::rowMajorIndex( ) const { return SparseBlockIndexGetter< Derived, !Traits::is_col_major >::get( *this ) ; } template < typename Derived > const typename SparseBlockMatrixBase< Derived >::ColIndexType &SparseBlockMatrixBase< Derived >::colMajorIndex( ) const { return SparseBlockIndexGetter< Derived, Traits::is_col_major >::get( *this ) ; } template < typename Derived > SparseBlockMatrixBase< Derived >::SparseBlockMatrixBase() : Base() { //Resize to zero setRows( 0, BOGUS_NULL_PTR(const unsigned) ) ; setCols( 0, BOGUS_NULL_PTR(const unsigned) ) ; m_transposeIndex.resizeOuter(0) ; m_transposeIndex.valid = false ; } template < typename Derived > void SparseBlockMatrixBase< Derived >::setRows( const Index nBlocks, const unsigned* rowsPerBlock ) { setInnerOffets( colMajorIndex(), nBlocks, rowsPerBlock ); m_rows = colMajorIndex().innerOffsets.back() ; rowMajorIndex().resizeOuter( nBlocks ) ; if( Traits::is_symmetric ) setCols( nBlocks, rowsPerBlock ) ; } template < typename Derived > void SparseBlockMatrixBase< Derived >::setCols( const Index nBlocks, const unsigned* colsPerBlock ) { setInnerOffets( rowMajorIndex(), nBlocks, colsPerBlock ); m_cols = rowMajorIndex().innerOffsets.back() ; colMajorIndex().resizeOuter( nBlocks ) ; } template < typename Derived > template < typename IndexT > void SparseBlockMatrixBase< Derived >::setInnerOffets( IndexT &index, const Index nBlocks, const unsigned *blockSizes) const { index.innerOffsets.resize( nBlocks + 1 ) ; index.innerOffsets[0] = 0 ; for ( Index i = 0 ; i < nBlocks ; ++ i ) { index.innerOffsets[ i+1 ] = index.innerOffsets[ i ] + blockSizes[i] ; } } template < typename Derived > template < bool Ordered > typename SparseBlockMatrixBase< Derived >::BlockRef SparseBlockMatrixBase< Derived >::insertByOuterInner( Index outer, Index inner ) { assert( outer < m_majorIndex.outerSize() ) ; assert( inner < m_majorIndex.innerSize() ) ; BlockPtr ptr ; BlockRef b = derived().template allocateBlock< !Ordered >( ptr, m_minorIndex.innerOffsetsData()[outer+1]- m_minorIndex.innerOffsetsData()[outer], m_majorIndex.innerOffsetsData()[inner+1]- m_majorIndex.innerOffsetsData()[inner] ) ; m_majorIndex.template insert< Ordered >( outer, inner, ptr ) ; m_minorIndex.valid = false ; return b ; } template < typename Derived > template < bool EnforceThreadSafety > typename SparseBlockMatrixBase< Derived >::BlockRef SparseBlockMatrixBase< Derived >::allocateBlock( BlockPtr &ptr, Index outer, Index inner ) { return derived().allocateBlock( ptr, outer, inner ); } template < typename Derived > void SparseBlockMatrixBase< Derived >::finalize() { assert( m_majorIndex.valid ) ; m_majorIndex.finalize() ; m_minorIndex.valid = false ; Finalizer::finalize( *this ) ; } template < typename Derived > void SparseBlockMatrixBase< Derived >::clear() { m_majorIndex.clear() ; m_minorIndex.clear() ; m_transposeIndex.clear() ; m_transposeIndex.valid = false ; m_transposeBlocks.clear() ; m_blocks.clear() ; } template < typename Derived > bool SparseBlockMatrixBase< Derived >::computeMinorIndex() { if ( m_minorIndex.valid ) return true ; computeMinorIndex( m_minorIndex ) ; return m_minorIndex.valid ; } template < typename Derived > void SparseBlockMatrixBase< Derived >::computeMinorIndex( MinorIndexType &cmIndex) const { cmIndex.clear() ; cmIndex.innerOffsets = m_minorIndex.innerOffsets ; cmIndex.template setToTranspose< Traits::is_symmetric >( m_majorIndex ) ; } template < typename Derived > const typename SparseBlockMatrixBase< Derived >::MinorIndexType& SparseBlockMatrixBase< Derived >::getOrComputeMinorIndex( MinorIndexType &cmIndex) const { if( m_minorIndex.valid ) return m_minorIndex ; computeMinorIndex( cmIndex ) ; return cmIndex ; } template < typename Derived > void SparseBlockMatrixBase<Derived>::cacheTranspose() { BOGUS_STATIC_ASSERT( IsTransposable< typename Derived::BlockType >::Value, TRANSPOSE_IS_NOT_DEFINED_FOR_THIS_BLOCK_TYPE ) ; if ( m_transposeIndex.valid ) return ; computeMinorIndex() ; BlockPtr base = 0 ; std::vector< BlockPtr > ptrOffsets( m_minorIndex.outerSize() ) ; for( Index i = 0 ; i < m_minorIndex.outerSize() ; ++i ) { ptrOffsets[i] = base ; base += m_minorIndex.size( i ) ; } m_transposeBlocks.resize( base ) ; assert( m_minorIndex.valid ) ; m_transposeIndex = m_minorIndex ; #ifndef BOGUS_DONT_PARALLELIZE #pragma omp parallel for #endif for ( Index i = 0 ; i < m_minorIndex.outerSize() ; ++ i ) { typename MinorIndexType::InnerIterator uncompressed_it ( m_minorIndex , i ) ; for( typename TransposeIndexType::InnerIterator it( m_transposeIndex, i ) ; it ; ++ it, ++uncompressed_it ) { const BlockPtr ptr = ptrOffsets[i]++ ; m_transposeBlocks[ ptr ] = transpose_block( m_blocks[ uncompressed_it.ptr() ] ) ; } } m_transposeIndex.valid = true ; } template < typename Derived > typename SparseBlockMatrixBase< Derived >::BlockPtr SparseBlockMatrixBase< Derived >::diagonalBlockPtr( const Index row ) const { if( Traits::is_symmetric ) { const typename MajorIndexType::InnerIterator it = m_majorIndex.last( row ) ; return ( it && it.inner() == row ) ? it.ptr() : InvalidBlockPtr ; } return blockPtr( row, row ) ; } template < typename Derived > typename SparseBlockMatrixBase< Derived >::BlockPtr SparseBlockMatrixBase< Derived >::blockPtr( Index row, Index col ) const { if( Traits::is_col_major ) std::swap( row, col ) ; const typename MajorIndexType::InnerIterator innerIt( majorIndex(), row ) ; const typename MajorIndexType::InnerIterator found( std::lower_bound( innerIt, innerIt.end(), col ) ) ; return found && found.inner() == col ? found.ptr() : InvalidBlockPtr ; } template< typename Derived > template< typename OtherDerived > void SparseBlockMatrixBase<Derived>::cloneDimensions( const BlockMatrixBase< OtherDerived > &source ) { std::vector< unsigned > dims( source.rowsOfBlocks() ) ; for( unsigned i = 0 ; i < dims.size() ; ++i ) { dims[i] = (unsigned) source.blockRows( i ) ; } setRows( dims ) ; dims.resize( source.colsOfBlocks() ) ; for( unsigned i = 0 ; i < dims.size() ; ++i ) { dims[i] = (unsigned) source.blockCols( i ) ; } setCols( dims ) ; } template < typename Derived > template < typename OtherDerived > void SparseBlockMatrixBase<Derived>::cloneStructure( const SparseBlockMatrixBase< OtherDerived > &source ) { BOGUS_STATIC_ASSERT( static_cast<unsigned>(BlockMatrixTraits< Derived >::flags) == static_cast< unsigned >(BlockMatrixTraits< OtherDerived >::flags), OPERANDS_HAVE_INCONSISTENT_FLAGS ) ; rowMajorIndex() = source.rowMajorIndex() ; colMajorIndex() = source.colMajorIndex() ; m_cols = source.cols() ; m_rows = source.rows() ; m_blocks.resize( source.nBlocks() ) ; m_transposeBlocks.clear() ; m_transposeIndex.valid = false ; } template < typename Derived > void SparseBlockMatrixBase<Derived>::cloneIndex( const MajorIndexType &source ) { assert( m_majorIndex.outerSize() == source.outerSize() ) ; assert( source.valid ) ; assert( !source.hasInnerOffsets() || m_majorIndex.innerSize() == source.innerSize() ) ; // Preserve current innerOffsets typename MajorIndexType::InnerOffsetsType tmpOffsets ; std::swap( tmpOffsets, m_majorIndex.innerOffsets ) ; m_majorIndex = source ; std::swap( tmpOffsets, m_majorIndex.innerOffsets ) ; m_blocks.resize( source.nonZeros() ) ; m_minorIndex.valid = false ; m_transposeBlocks.clear() ; m_transposeIndex.valid = false ; Finalizer::finalize( *this ) ; } template < typename Derived > Derived& SparseBlockMatrixBase< Derived >::prune( const Scalar precision ) { MajorIndexType oldIndex = m_majorIndex ; typename Traits::BlocksArrayType old_blocks ; old_blocks.swap( m_blocks ) ; derived().resetFor( old_blocks ) ; for( Index outer = 0 ; outer < oldIndex.outerSize() ; ++outer ) { for( typename MajorIndexType::InnerIterator it( oldIndex, outer ) ; it ; ++it ) { if( ! is_zero( old_blocks[ it.ptr() ], precision ) ) { m_majorIndex.insertBack( outer, it.inner(), m_blocks.size() ) ; m_blocks.push_back( old_blocks[ it.ptr() ] ) ; } } } m_minorIndex.valid = empty() ; finalize() ; return derived() ; } namespace perm_impl { template< typename T, typename U > typename EnableIf<U::RowsAtCompileTime == T::RowsAtCompileTime, void >::ReturnType swap( T t, U u ) { using std::swap ; for( unsigned i = 0 ; i < u.rows() ; ++i ) swap( t[i], u[i] ) ; } } template < typename IndexT, typename ArrayT > void applyPermutation( const IndexT n, const IndexT* permutation, ArrayT& array ) { using std::swap ; using perm_impl::swap ; std::vector< bool > swapped( n, false ) ; for( IndexT i = 0 ; i < n ; ++i ) { if( swapped[ i ] ) continue ; for( IndexT j = i, p ;; j = p ) { p = permutation[j] ; swapped[ j ] = true ; if( swapped[p] ) break ; swap( array[j], array[p] ) ; } } } template < typename Derived > Derived& SparseBlockMatrixBase< Derived >::applyPermutation( const std::size_t* indices ) { assert( rowsOfBlocks() == colsOfBlocks() ) ; std::vector< std::size_t > inv( rowsOfBlocks() ) ; for( std::size_t i = 0 ; i < inv.size() ; ++i ) inv[ indices[i] ] = i ; const MajorIndexType &sourceIndex = majorIndex() ; const bool MayTranspose = Traits::is_symmetric && ! BlockTraits< BlockType >::is_self_transpose ; typedef TransposeIf< MayTranspose > TransposeOption ; UncompressedIndexType destIndex ; destIndex.resizeOuter( sourceIndex.outerSize() ); BlockType tmp ; //For temporary evaluation of transpose() for( Index outer = 0 ; outer < sourceIndex.outerSize() ; ++outer ) { for( typename MajorIndexType::InnerIterator inner( sourceIndex, indices[ outer ] ) ; inner ; ++inner ) { if( Traits::is_symmetric && static_cast< Index >( inv[inner.inner()] ) > outer ) { if( MayTranspose ) { tmp = TransposeOption::get( m_blocks[inner.ptr()] ) ; m_blocks[inner.ptr()] = tmp ; } destIndex.template insert< false >( inv[ inner.inner() ], outer, inner.ptr() ); } else { destIndex.template insert< false >( outer, inv[ inner.inner() ], inner.ptr() ); } } } destIndex.finalize(); // Reorder blocks std::vector< BlockPtr > blocksPermutation ; blocksPermutation.reserve( nBlocks() ); for( Index outer = 0 ; outer < destIndex.outerSize() ; ++outer ) { for( typename UncompressedIndexType::InnerIterator inner( destIndex, outer ) ; inner ; ++inner ) { blocksPermutation.push_back( inner.ptr() ) ; destIndex.changePtr( inner, blocksPermutation.size() - 1 ) ; } } m_majorIndex = destIndex ; assert( m_majorIndex.valid ) ; bogus::applyPermutation( nBlocks(), data_pointer(blocksPermutation), m_blocks ) ; m_minorIndex.valid = empty() ; m_transposeIndex.valid = false ; m_transposeBlocks.clear() ; Finalizer::finalize( *this ) ; return derived() ; } template < typename Derived > void set_identity( SparseBlockMatrixBase< Derived >& block ) { block.setIdentity() ; } template < typename Derived > typename SparseBlockMatrixBase< Derived >::BlockRef SparseBlockMatrixBase< Derived >::insertBackAndResize( Index row, Index col ) { BlockRef block = insertBack( row, col ) ; resize( block, blockRows( row ), blockCols( col ) ) ; return block ; } template < typename Derived > typename SparseBlockMatrixBase< Derived >::BlockRef SparseBlockMatrixBase< Derived >::insertAndResize( Index row, Index col ) { BlockRef block = insert( row, col ) ; resize( block, blockRows( row ), blockCols( col ) ) ; return block ; } template < typename Derived > Derived& SparseBlockMatrixBase< Derived >::setIdentity( ) { clear() ; Index m = std::min( rowsOfBlocks(), colsOfBlocks() ) ; for( Index i = 0 ; i < m ; ++i ) { majorIndex().insertBack( i, i, i ) ; } finalize(); derived().createBlockShapes( m, majorIndex(), m_blocks ) ; for( Index i = 0 ; i < m ; ++i ) { resize( m_blocks[i], blockRows(i), blockCols(i) ) ; set_identity( m_blocks[i] ) ; } return derived() ; } template < typename Derived > Derived& SparseBlockMatrixBase< Derived >::setBlocksToZero( ) { #ifndef BOGUS_DONT_PARALLELIZE #pragma omp parallel for #endif for( std::size_t i = 0 ; i < nBlocks() ; ++i ) { set_zero( block(i) ) ; } return derived() ; } template < typename Derived > template < bool ColWise, typename Func> void SparseBlockMatrixBase< Derived >::eachBlockOf( const Index outer, Func func ) const { typedef SparseBlockIndexComputer< Derived, ColWise, false > IndexComputer ; typedef typename IndexComputer::ReturnType IndexType ; IndexComputer cptr( *this ) ; const IndexType& index = cptr.get() ; for( typename IndexType::InnerIterator it ( index, outer ) ; it ; ++it ) { func( it.inner(), block(it.ptr() ) ) ; } } } //namespace bogus #endif
27.24581
127
0.70337
[ "vector" ]
adaa53bf27aa9dd1eeaea11c806d60a2f04590dc
867
hpp
C++
wxdraw/object/Object.hpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/object/Object.hpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
wxdraw/object/Object.hpp
yasuikentarow/graed
45db4f4291bdca27c32a3b2938ccd1aa7b40d48a
[ "MIT" ]
null
null
null
#pragma once namespace wxdraw::object { /** オブジェクト基底クラス */ class Object : public std::enable_shared_from_this<Object> { private: wxString type_; wxString id_; wxString name_; static std::map<std::type_index, std::map<wxString, int>> Serials; public: Object(const wxString& type); Object(const Object& src); virtual ~Object() = default; WXDRAW_GETTER(Type, type_); WXDRAW_ACCESSOR(Id, id_); WXDRAW_ACCESSOR(Name, name_); virtual PropertyPtr generateProperty(); virtual void onUpdateProperty(); template<class T, class... Args> static std::shared_ptr<T> Create(Args&&... args) { auto object = std::make_shared<T>(args...); object->onCreate(); return object; } static wxString CreateId(); virtual void onCreate(); wxDataObject* toDataObject(); private: void onCreate(const std::type_index& type); }; }
18.847826
68
0.689735
[ "object" ]
adb565139efde49fc780fa8b1b8e9d14b8ab26c5
22,372
cc
C++
utils/flatbuffers/mutable.cc
yangzhigang1999/libtextclassifier
4c965f1c12b3c7a37f6126cef737a8fe33f4677c
[ "Apache-2.0" ]
null
null
null
utils/flatbuffers/mutable.cc
yangzhigang1999/libtextclassifier
4c965f1c12b3c7a37f6126cef737a8fe33f4677c
[ "Apache-2.0" ]
null
null
null
utils/flatbuffers/mutable.cc
yangzhigang1999/libtextclassifier
4c965f1c12b3c7a37f6126cef737a8fe33f4677c
[ "Apache-2.0" ]
1
2021-03-20T03:40:21.000Z
2021-03-20T03:40:21.000Z
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "utils/flatbuffers/mutable.h" #include <vector> #include "utils/flatbuffers/reflection.h" #include "utils/strings/numbers.h" #include "utils/variant.h" #include "flatbuffers/reflection_generated.h" namespace libtextclassifier3 { namespace { bool Parse(const std::string& str_value, float* value) { double double_value; if (!ParseDouble(str_value.data(), &double_value)) { return false; } *value = static_cast<float>(double_value); return true; } bool Parse(const std::string& str_value, double* value) { return ParseDouble(str_value.data(), value); } bool Parse(const std::string& str_value, int64* value) { return ParseInt64(str_value.data(), value); } bool Parse(const std::string& str_value, int32* value) { return ParseInt32(str_value.data(), value); } bool Parse(const std::string& str_value, std::string* value) { *value = str_value; return true; } template <typename T> bool ParseAndSetField(const reflection::Field* field, const std::string& str_value, MutableFlatbuffer* buffer) { T value; if (!Parse(str_value, &value)) { TC3_LOG(ERROR) << "Could not parse '" << str_value << "'"; return false; } if (field->type()->base_type() == reflection::Vector) { buffer->Repeated(field)->Add(value); return true; } else { return buffer->Set<T>(field, value); } } } // namespace MutableFlatbufferBuilder::MutableFlatbufferBuilder( const reflection::Schema* schema, StringPiece root_type) : schema_(schema), root_type_(TypeForName(schema, root_type)) {} std::unique_ptr<MutableFlatbuffer> MutableFlatbufferBuilder::NewRoot() const { return NewTable(root_type_); } std::unique_ptr<MutableFlatbuffer> MutableFlatbufferBuilder::NewTable( StringPiece table_name) const { return NewTable(TypeForName(schema_, table_name)); } std::unique_ptr<MutableFlatbuffer> MutableFlatbufferBuilder::NewTable( const int type_id) const { if (type_id < 0 || type_id >= schema_->objects()->size()) { TC3_LOG(ERROR) << "Invalid type id: " << type_id; return nullptr; } return NewTable(schema_->objects()->Get(type_id)); } std::unique_ptr<MutableFlatbuffer> MutableFlatbufferBuilder::NewTable( const reflection::Object* type) const { if (type == nullptr) { return nullptr; } return std::make_unique<MutableFlatbuffer>(schema_, type); } const reflection::Field* MutableFlatbuffer::GetFieldOrNull( const StringPiece field_name) const { return libtextclassifier3::GetFieldOrNull(type_, field_name); } const reflection::Field* MutableFlatbuffer::GetFieldOrNull( const FlatbufferField* field) const { return libtextclassifier3::GetFieldOrNull(type_, field); } bool MutableFlatbuffer::GetFieldWithParent( const FlatbufferFieldPath* field_path, MutableFlatbuffer** parent, reflection::Field const** field) { const auto* path = field_path->field(); if (path == nullptr || path->size() == 0) { return false; } for (int i = 0; i < path->size(); i++) { *parent = (i == 0 ? this : (*parent)->Mutable(*field)); if (*parent == nullptr) { return false; } *field = (*parent)->GetFieldOrNull(path->Get(i)); if (*field == nullptr) { return false; } } return true; } const reflection::Field* MutableFlatbuffer::GetFieldOrNull( const int field_offset) const { return libtextclassifier3::GetFieldOrNull(type_, field_offset); } bool MutableFlatbuffer::SetFromEnumValueName(const reflection::Field* field, StringPiece value_name) { if (!IsEnum(field->type())) { return false; } Variant variant_value = ParseEnumValue(schema_, field->type(), value_name); if (!variant_value.HasValue()) { return false; } fields_[field] = variant_value; return true; } bool MutableFlatbuffer::SetFromEnumValueName(StringPiece field_name, StringPiece value_name) { if (const reflection::Field* field = GetFieldOrNull(field_name)) { return SetFromEnumValueName(field, value_name); } return false; } bool MutableFlatbuffer::SetFromEnumValueName(const FlatbufferFieldPath* path, StringPiece value_name) { MutableFlatbuffer* parent; const reflection::Field* field; if (!GetFieldWithParent(path, &parent, &field)) { return false; } return parent->SetFromEnumValueName(field, value_name); } bool MutableFlatbuffer::ParseAndSet(const reflection::Field* field, const std::string& value) { // Try parsing as an enum value. if (IsEnum(field->type()) && SetFromEnumValueName(field, value)) { return true; } switch (field->type()->base_type() == reflection::Vector ? field->type()->element() : field->type()->base_type()) { case reflection::String: return ParseAndSetField<std::string>(field, value, this); case reflection::Int: return ParseAndSetField<int32>(field, value, this); case reflection::Long: return ParseAndSetField<int64>(field, value, this); case reflection::Float: return ParseAndSetField<float>(field, value, this); case reflection::Double: return ParseAndSetField<double>(field, value, this); default: TC3_LOG(ERROR) << "Unhandled field type: " << field->type()->base_type(); return false; } } bool MutableFlatbuffer::ParseAndSet(const FlatbufferFieldPath* path, const std::string& value) { MutableFlatbuffer* parent; const reflection::Field* field; if (!GetFieldWithParent(path, &parent, &field)) { return false; } return parent->ParseAndSet(field, value); } MutableFlatbuffer* MutableFlatbuffer::Add(StringPiece field_name) { const reflection::Field* field = GetFieldOrNull(field_name); if (field == nullptr) { return nullptr; } if (field->type()->base_type() != reflection::BaseType::Vector) { return nullptr; } return Add(field); } MutableFlatbuffer* MutableFlatbuffer::Add(const reflection::Field* field) { if (field == nullptr) { return nullptr; } return Repeated(field)->Add(); } MutableFlatbuffer* MutableFlatbuffer::Mutable(const StringPiece field_name) { if (const reflection::Field* field = GetFieldOrNull(field_name)) { return Mutable(field); } TC3_LOG(ERROR) << "Unknown field: " << field_name.ToString(); return nullptr; } MutableFlatbuffer* MutableFlatbuffer::Mutable(const reflection::Field* field) { if (field->type()->base_type() != reflection::Obj) { return nullptr; } const auto entry = children_.find(field); if (entry != children_.end()) { return entry->second.get(); } const auto it = children_.insert( /*hint=*/entry, std::make_pair( field, std::unique_ptr<MutableFlatbuffer>(new MutableFlatbuffer( schema_, schema_->objects()->Get(field->type()->index()))))); return it->second.get(); } MutableFlatbuffer* MutableFlatbuffer::Mutable(const FlatbufferFieldPath* path) { const auto* field_path = path->field(); if (field_path == nullptr || field_path->size() == 0) { return this; } MutableFlatbuffer* object = this; for (int i = 0; i < field_path->size(); i++) { const reflection::Field* field = object->GetFieldOrNull(field_path->Get(i)); if (field == nullptr) { return nullptr; } object = object->Mutable(field); if (object == nullptr) { return nullptr; } } return object; } RepeatedField* MutableFlatbuffer::Repeated(StringPiece field_name) { if (const reflection::Field* field = GetFieldOrNull(field_name)) { return Repeated(field); } TC3_LOG(ERROR) << "Unknown field: " << field_name.ToString(); return nullptr; } RepeatedField* MutableFlatbuffer::Repeated(const reflection::Field* field) { if (field->type()->base_type() != reflection::Vector) { TC3_LOG(ERROR) << "Field is not of type Vector."; return nullptr; } // If the repeated field was already set, return its instance. const auto entry = repeated_fields_.find(field); if (entry != repeated_fields_.end()) { return entry->second.get(); } // Otherwise, create a new instance and store it. std::unique_ptr<RepeatedField> repeated_field( new RepeatedField(schema_, field)); const auto it = repeated_fields_.insert( /*hint=*/entry, std::make_pair(field, std::move(repeated_field))); return it->second.get(); } RepeatedField* MutableFlatbuffer::Repeated(const FlatbufferFieldPath* path) { MutableFlatbuffer* parent; const reflection::Field* field; if (!GetFieldWithParent(path, &parent, &field)) { return nullptr; } return parent->Repeated(field); } flatbuffers::uoffset_t MutableFlatbuffer::Serialize( flatbuffers::FlatBufferBuilder* builder) const { // Build all children before we can start with this table. std::vector< std::pair</* field vtable offset */ int, /* field data offset in buffer */ flatbuffers::uoffset_t>> offsets; offsets.reserve(children_.size() + repeated_fields_.size()); for (const auto& it : children_) { offsets.push_back({it.first->offset(), it.second->Serialize(builder)}); } // Create strings. for (const auto& it : fields_) { if (it.second.Has<std::string>()) { offsets.push_back( {it.first->offset(), builder->CreateString(it.second.ConstRefValue<std::string>()).o}); } } // Build the repeated fields. for (const auto& it : repeated_fields_) { offsets.push_back({it.first->offset(), it.second->Serialize(builder)}); } // Build the table now. const flatbuffers::uoffset_t table_start = builder->StartTable(); // Add scalar fields. for (const auto& it : fields_) { switch (it.second.GetType()) { case Variant::TYPE_BOOL_VALUE: builder->AddElement<uint8_t>( it.first->offset(), static_cast<uint8_t>(it.second.Value<bool>()), static_cast<uint8_t>(it.first->default_integer())); continue; case Variant::TYPE_INT8_VALUE: builder->AddElement<int8_t>( it.first->offset(), static_cast<int8_t>(it.second.Value<int8>()), static_cast<int8_t>(it.first->default_integer())); continue; case Variant::TYPE_UINT8_VALUE: builder->AddElement<uint8_t>( it.first->offset(), static_cast<uint8_t>(it.second.Value<uint8>()), static_cast<uint8_t>(it.first->default_integer())); continue; case Variant::TYPE_INT_VALUE: builder->AddElement<int32>( it.first->offset(), it.second.Value<int>(), static_cast<int32>(it.first->default_integer())); continue; case Variant::TYPE_UINT_VALUE: builder->AddElement<uint32>( it.first->offset(), it.second.Value<uint>(), static_cast<uint32>(it.first->default_integer())); continue; case Variant::TYPE_INT64_VALUE: builder->AddElement<int64>(it.first->offset(), it.second.Value<int64>(), it.first->default_integer()); continue; case Variant::TYPE_UINT64_VALUE: builder->AddElement<uint64>(it.first->offset(), it.second.Value<uint64>(), it.first->default_integer()); continue; case Variant::TYPE_FLOAT_VALUE: builder->AddElement<float>( it.first->offset(), it.second.Value<float>(), static_cast<float>(it.first->default_real())); continue; case Variant::TYPE_DOUBLE_VALUE: builder->AddElement<double>(it.first->offset(), it.second.Value<double>(), it.first->default_real()); continue; default: continue; } } // Add strings, subtables and repeated fields. for (const auto& it : offsets) { builder->AddOffset(it.first, flatbuffers::Offset<void>(it.second)); } return builder->EndTable(table_start); } std::string MutableFlatbuffer::Serialize() const { flatbuffers::FlatBufferBuilder builder; builder.Finish(flatbuffers::Offset<void>(Serialize(&builder))); return std::string(reinterpret_cast<const char*>(builder.GetBufferPointer()), builder.GetSize()); } bool MutableFlatbuffer::MergeFrom(const flatbuffers::Table* from) { // No fields to set. if (type_->fields() == nullptr) { return true; } for (const reflection::Field* field : *type_->fields()) { // Skip fields that are not explicitly set. if (!from->CheckField(field->offset())) { continue; } const reflection::BaseType type = field->type()->base_type(); switch (type) { case reflection::Bool: Set<bool>(field, from->GetField<uint8_t>(field->offset(), field->default_integer())); break; case reflection::Byte: Set<int8_t>(field, from->GetField<int8_t>(field->offset(), field->default_integer())); break; case reflection::UByte: Set<uint8_t>(field, from->GetField<uint8_t>(field->offset(), field->default_integer())); break; case reflection::Int: Set<int32>(field, from->GetField<int32>(field->offset(), field->default_integer())); break; case reflection::UInt: Set<uint32>(field, from->GetField<uint32>(field->offset(), field->default_integer())); break; case reflection::Long: Set<int64>(field, from->GetField<int64>(field->offset(), field->default_integer())); break; case reflection::ULong: Set<uint64>(field, from->GetField<uint64>(field->offset(), field->default_integer())); break; case reflection::Float: Set<float>(field, from->GetField<float>(field->offset(), field->default_real())); break; case reflection::Double: Set<double>(field, from->GetField<double>(field->offset(), field->default_real())); break; case reflection::String: Set<std::string>( field, from->GetPointer<const flatbuffers::String*>(field->offset()) ->str()); break; case reflection::Obj: if (MutableFlatbuffer* nested_field = Mutable(field); nested_field == nullptr || !nested_field->MergeFrom( from->GetPointer<const flatbuffers::Table* const>( field->offset()))) { return false; } break; case reflection::Vector: { if (RepeatedField* repeated_field = Repeated(field); repeated_field == nullptr || !repeated_field->Extend(from)) { return false; } break; } default: TC3_LOG(ERROR) << "Unsupported type: " << type << " for field: " << field->name()->str(); return false; } } return true; } bool MutableFlatbuffer::MergeFromSerializedFlatbuffer(StringPiece from) { return MergeFrom(flatbuffers::GetAnyRoot( reinterpret_cast<const unsigned char*>(from.data()))); } void MutableFlatbuffer::AsFlatMap( const std::string& key_separator, const std::string& key_prefix, std::map<std::string, Variant>* result) const { // Add direct fields. for (const auto& it : fields_) { (*result)[key_prefix + it.first->name()->str()] = it.second; } // Add nested messages. for (const auto& it : children_) { it.second->AsFlatMap(key_separator, key_prefix + it.first->name()->str() + key_separator, result); } } std::string RepeatedField::ToTextProto() const { std::string result = " ["; std::string current_field_separator; for (int index = 0; index < Size(); index++) { if (is_primitive_) { result.append(current_field_separator + items_.at(index).ToString()); } else { result.append(current_field_separator + "{" + Get<MutableFlatbuffer*>(index)->ToTextProto() + "}"); } current_field_separator = ", "; } result.append("] "); return result; } std::string MutableFlatbuffer::ToTextProto() const { std::string result; std::string current_field_separator; // Add direct fields. for (const auto& field_value_pair : fields_) { const std::string field_name = field_value_pair.first->name()->str(); const Variant& value = field_value_pair.second; std::string quotes; if (value.GetType() == Variant::TYPE_STRING_VALUE) { quotes = "'"; } result.append(current_field_separator + field_name + ": " + quotes + value.ToString() + quotes); current_field_separator = ", "; } // Add repeated message for (const auto& repeated_fb_pair : repeated_fields_) { result.append(current_field_separator + repeated_fb_pair.first->name()->c_str() + ": " + repeated_fb_pair.second->ToTextProto()); current_field_separator = ", "; } // Add nested messages. for (const auto& field_flatbuffer_pair : children_) { const std::string field_name = field_flatbuffer_pair.first->name()->str(); result.append(current_field_separator + field_name + " {" + field_flatbuffer_pair.second->ToTextProto() + "}"); current_field_separator = ", "; } return result; } // // Repeated field methods. // MutableFlatbuffer* RepeatedField::Add() { if (is_primitive_) { TC3_LOG(ERROR) << "Trying to add sub-message on a primitive-typed field."; return nullptr; } object_items_.emplace_back(new MutableFlatbuffer( schema_, schema_->objects()->Get(field_->type()->index()))); return object_items_.back().get(); } namespace { template <typename T> flatbuffers::uoffset_t TypedSerialize(const std::vector<Variant>& values, flatbuffers::FlatBufferBuilder* builder) { std::vector<T> typed_values; typed_values.reserve(values.size()); for (const Variant& item : values) { typed_values.push_back(item.Value<T>()); } return builder->CreateVector(typed_values).o; } } // namespace bool RepeatedField::Extend(const flatbuffers::Table* from) { switch (field_->type()->element()) { case reflection::Int: AppendFromVector<int32>(from); return true; case reflection::UInt: AppendFromVector<uint>(from); return true; case reflection::Long: AppendFromVector<int64>(from); return true; case reflection::ULong: AppendFromVector<uint64>(from); return true; case reflection::Byte: AppendFromVector<int8_t>(from); return true; case reflection::UByte: AppendFromVector<uint8_t>(from); return true; case reflection::String: AppendFromVector<std::string>(from); return true; case reflection::Obj: AppendFromVector<MutableFlatbuffer>(from); return true; case reflection::Double: AppendFromVector<double>(from); return true; case reflection::Float: AppendFromVector<float>(from); return true; default: TC3_LOG(ERROR) << "Repeated unsupported type: " << field_->type()->element() << " for field: " << field_->name()->str(); return false; } } flatbuffers::uoffset_t RepeatedField::Serialize( flatbuffers::FlatBufferBuilder* builder) const { switch (field_->type()->element()) { case reflection::String: return SerializeString(builder); break; case reflection::Obj: return SerializeObject(builder); break; case reflection::Bool: return TypedSerialize<bool>(items_, builder); break; case reflection::Byte: return TypedSerialize<int8_t>(items_, builder); break; case reflection::UByte: return TypedSerialize<uint8_t>(items_, builder); break; case reflection::Int: return TypedSerialize<int>(items_, builder); break; case reflection::UInt: return TypedSerialize<uint>(items_, builder); break; case reflection::Long: return TypedSerialize<int64>(items_, builder); break; case reflection::ULong: return TypedSerialize<uint64>(items_, builder); break; case reflection::Float: return TypedSerialize<float>(items_, builder); break; case reflection::Double: return TypedSerialize<double>(items_, builder); break; default: TC3_LOG(FATAL) << "Unsupported type: " << field_->type()->element(); break; } TC3_LOG(FATAL) << "Invalid state."; return 0; } flatbuffers::uoffset_t RepeatedField::SerializeString( flatbuffers::FlatBufferBuilder* builder) const { std::vector<flatbuffers::Offset<flatbuffers::String>> offsets(items_.size()); for (int i = 0; i < items_.size(); i++) { offsets[i] = builder->CreateString(items_[i].ConstRefValue<std::string>()); } return builder->CreateVector(offsets).o; } flatbuffers::uoffset_t RepeatedField::SerializeObject( flatbuffers::FlatBufferBuilder* builder) const { std::vector<flatbuffers::Offset<void>> offsets(object_items_.size()); for (int i = 0; i < object_items_.size(); i++) { offsets[i] = object_items_[i]->Serialize(builder); } return builder->CreateVector(offsets).o; } } // namespace libtextclassifier3
32.612245
80
0.63432
[ "object", "vector" ]
adbacce3de707cca8aa512af1e0856b1167c4aa9
4,707
cpp
C++
src/caffe/layers/eltwise_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
123
2017-05-04T02:15:47.000Z
2021-01-04T05:04:24.000Z
src/caffe/layers/eltwise_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
43
2017-05-10T11:21:25.000Z
2021-01-28T14:53:01.000Z
src/caffe/layers/eltwise_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
32
2017-05-10T11:08:18.000Z
2020-12-17T20:03:45.000Z
#include <cfloat> #include <vector> #include "caffe/layers/eltwise_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> __global__ void MaxForward(const int nthreads, const Dtype* bottom_data_a, const Dtype* bottom_data_b, const int blob_idx, Dtype* top_data, int* mask) { HIP_KERNEL_LOOP(index, nthreads) { Dtype maxval = -FLT_MAX; int maxidx = -1; if (bottom_data_a[index] > bottom_data_b[index]) { // only update for very first bottom_data blob (blob_idx == 0) if (blob_idx == 0) { maxval = bottom_data_a[index]; top_data[index] = maxval; maxidx = blob_idx; mask[index] = maxidx; } } else { maxval = bottom_data_b[index]; top_data[index] = maxval; maxidx = blob_idx + 1; mask[index] = maxidx; } } } template <typename Dtype> void EltwiseLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int* mask = NULL; const int count = top[0]->count(); Dtype* top_data = top[0]->mutable_gpu_data(); switch (op_) { case EltwiseParameter_EltwiseOp_PROD: caffe_gpu_mul(count, bottom[0]->gpu_data(), bottom[1]->gpu_data(), top_data); for (int i = 2; i < bottom.size(); ++i) { caffe_gpu_mul(count, top_data, bottom[i]->gpu_data(), top_data); } break; case EltwiseParameter_EltwiseOp_SUM: caffe_gpu_set(count, Dtype(0.), top_data); // TODO(shelhamer) does cuBLAS optimize to sum for coeff = 1? for (int i = 0; i < bottom.size(); ++i) { caffe_gpu_axpy(count, coeffs_[i], bottom[i]->gpu_data(), top_data); } break; case EltwiseParameter_EltwiseOp_MAX: { mask = max_idx_.mutable_gpu_data(); // NOLINT_NEXT_LINE(whitespace/operators) auto bot0_gpu_data = bottom[0]->gpu_data(); auto bot1_gpu_data = bottom[1]->gpu_data(); hipLaunchKernelGGL(MaxForward<Dtype>, dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, count, bot0_gpu_data, bot1_gpu_data, 0, top_data, mask); for (int i = 2; i < bottom.size(); ++i) { // NOLINT_NEXT_LINE(whitespace/operators) auto boti_gpu_data = bottom[i]->gpu_data(); hipLaunchKernelGGL(MaxForward<Dtype>, dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, count, top_data, boti_gpu_data, i-1, top_data, mask); } } break; default: LOG(FATAL) << "Unknown elementwise operation."; } } template <typename Dtype> __global__ void MaxBackward(const int nthreads, const Dtype* top_diff, const int blob_idx, const int* mask, Dtype* bottom_diff) { HIP_KERNEL_LOOP(index, nthreads) { Dtype gradient = 0; if (mask[index] == blob_idx) { gradient += top_diff[index]; } bottom_diff[index] = gradient; } } template <typename Dtype> void EltwiseLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const int* mask = NULL; const int count = top[0]->count(); const Dtype* top_data = top[0]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); for (int i = 0; i < bottom.size(); ++i) { if (propagate_down[i]) { const Dtype* bottom_data = bottom[i]->gpu_data(); Dtype* bottom_diff = bottom[i]->mutable_gpu_diff(); switch (op_) { case EltwiseParameter_EltwiseOp_PROD: if (stable_prod_grad_) { bool initialized = false; for (int j = 0; j < bottom.size(); ++j) { if (i == j) { continue; } if (!initialized) { caffe_copy(count, bottom[j]->gpu_data(), bottom_diff); initialized = true; } else { caffe_gpu_mul(count, bottom[j]->gpu_data(), bottom_diff, bottom_diff); } } } else { caffe_gpu_div(count, top_data, bottom_data, bottom_diff); } caffe_gpu_mul(count, bottom_diff, top_diff, bottom_diff); break; case EltwiseParameter_EltwiseOp_SUM: if (coeffs_[i] == Dtype(1.)) { caffe_copy(count, top_diff, bottom_diff); } else { caffe_gpu_scale(count, coeffs_[i], top_diff, bottom_diff); } break; case EltwiseParameter_EltwiseOp_MAX: mask = max_idx_.gpu_data(); hipLaunchKernelGGL(MaxBackward<Dtype>, dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, count, top_diff, i, mask, bottom_diff); break; default: LOG(FATAL) << "Unknown elementwise operation."; } } } } INSTANTIATE_LAYER_GPU_FUNCS(EltwiseLayer); } // namespace caffe
33.621429
109
0.628001
[ "vector" ]
adbbaa953ff1fdc844088eedd5e3dad6a774e2bf
1,584
hxx
C++
Core/GraphicsKit/GraphicsHandler.hxx
broken-bytes/Cyanite-Engine
5733e1fc010b375bbafc9ebfa41e248845f945b3
[ "MIT" ]
null
null
null
Core/GraphicsKit/GraphicsHandler.hxx
broken-bytes/Cyanite-Engine
5733e1fc010b375bbafc9ebfa41e248845f945b3
[ "MIT" ]
null
null
null
Core/GraphicsKit/GraphicsHandler.hxx
broken-bytes/Cyanite-Engine
5733e1fc010b375bbafc9ebfa41e248845f945b3
[ "MIT" ]
1
2020-12-20T07:35:05.000Z
2020-12-20T07:35:05.000Z
#pragma once #include <cstdint> #include "pch.hxx" #include "Frame.hxx" #include "Gpu.hxx" #include "Texture.hxx" #include "../EventKit/EventRelay.hxx" namespace Cyanite::GraphicsKit { class GraphicsHandler { public: explicit GraphicsHandler(HWND window); ~GraphicsHandler(); GraphicsHandler(const GraphicsHandler&) = delete; GraphicsHandler(GraphicsHandler&&) = delete; GraphicsHandler& operator=(GraphicsHandler&) = delete; GraphicsHandler& operator=(GraphicsHandler&&) = delete; auto Initialize() -> void; auto Deinitialize() -> void; auto Update() -> void; auto Render() -> void; auto Resize(uint32_t width, uint32_t height) -> void; private: // Pipeline objects. CD3DX12_VIEWPORT _viewport; CD3DX12_RECT _scissorRect; winrt::com_ptr<IDXGISwapChain4> _swapChain; winrt::com_ptr<ID3D12Device> _device; winrt::com_ptr<ID3D12Resource> _renderTargets[Frames]; winrt::com_ptr<ID3D12Resource> _depthStencil; winrt::com_ptr<ID3D12CommandAllocator> _commandAllocator; winrt::com_ptr<ID3D12RootSignature> _rootSignature; winrt::com_ptr<ID3D12DescriptorHeap> _rtvHeap; uint64_t m_rtvDescriptorSize; winrt::com_ptr<ID3D12DescriptorHeap> _dsvHeap; winrt::com_ptr<ID3D12DescriptorHeap> _cbvSrvHeap; winrt::com_ptr<ID3D12DescriptorHeap> _samplerHeap; winrt::com_ptr<ID3D12PipelineState> _pipelineState; uint64_t _frameIndex; HANDLE _fenceEvent; winrt::com_ptr<ID3D12Fence> _fence; uint64_t _fenceValue; }; }
31.68
65
0.710859
[ "render" ]
adbfb5969900ba7dfb2f0b5039d95a936e265ac1
1,922
cc
C++
code/Modules/IO/private/schemeRegistry.cc
FrogAC/oryol
7254c59411e97bbb6f2363aa685718def9f13827
[ "MIT" ]
1,707
2015-01-01T14:56:08.000Z
2022-03-28T06:44:09.000Z
code/Modules/IO/private/schemeRegistry.cc
FrogAC/oryol
7254c59411e97bbb6f2363aa685718def9f13827
[ "MIT" ]
256
2015-01-03T14:55:53.000Z
2020-09-09T10:43:46.000Z
code/Modules/IO/private/schemeRegistry.cc
FrogAC/oryol
7254c59411e97bbb6f2363aa685718def9f13827
[ "MIT" ]
222
2015-01-05T00:20:54.000Z
2022-02-06T01:41:37.000Z
//------------------------------------------------------------------------------ // schemeRegistry.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "schemeRegistry.h" #include "IO/FileSystemBase.h" #include "Core/Core.h" #if ORYOL_HAS_THREADS #include <mutex> static std::mutex lockMutex; #define SCOPED_LOCK std::lock_guard<std::mutex> lock(lockMutex) #else #define SCOPED_LOCK #endif namespace Oryol { namespace _priv { //------------------------------------------------------------------------------ void schemeRegistry::RegisterFileSystem(const StringAtom& scheme, std::function<Ptr<FileSystemBase>()> fsCreator) { o_assert_dbg(!this->registry.Contains(scheme)); { SCOPED_LOCK; this->registry.Add(scheme, fsCreator); } // create temp FileSystem object on main-thread to call the Init method auto fs = this->CreateFileSystem(scheme); fs->init(scheme); } //------------------------------------------------------------------------------ void schemeRegistry::UnregisterFileSystem(const StringAtom& scheme) { SCOPED_LOCK; o_assert_dbg(this->registry.Contains(scheme)); this->registry.Erase(scheme); } //------------------------------------------------------------------------------ bool schemeRegistry::IsFileSystemRegistered(const StringAtom& scheme) const { SCOPED_LOCK; bool result = this->registry.Contains(scheme); return result; } //------------------------------------------------------------------------------ Ptr<FileSystemBase> schemeRegistry::CreateFileSystem(const StringAtom& scheme) const { SCOPED_LOCK; o_assert_dbg(this->registry.Contains(scheme)); Ptr<FileSystemBase> fileSystem(this->registry[scheme]()); fileSystem->initLane(); return fileSystem; } } // namespace _priv } // namespace Oryol
31.508197
111
0.523933
[ "object" ]
adc24ff0cc0097fdfbf27c19f8f2c849e06b4b4c
1,632
cpp
C++
project2D/MenuState.cpp
PancakesMan/GameStateProject
09a2587d96759768f04c521585b90bd961ef1758
[ "MIT" ]
null
null
null
project2D/MenuState.cpp
PancakesMan/GameStateProject
09a2587d96759768f04c521585b90bd961ef1758
[ "MIT" ]
null
null
null
project2D/MenuState.cpp
PancakesMan/GameStateProject
09a2587d96759768f04c521585b90bd961ef1758
[ "MIT" ]
null
null
null
#include "MenuState.h" #include "GameState.h" MenuState::MenuState(Application2D* _app) : IGameState(_app) { m_font = resources.getFont("./font/consolas.ttf", 28); m_start = new Button(app->getWindowWidth() / 2, app->getWindowHeight() / 2 - 60, "Start Game", m_font.get()); m_controls = new Button(app->getWindowWidth() / 2, m_start->getY() - 40, "Controls", m_font.get()); m_scores = new Button(app->getWindowWidth() / 2, m_controls->getY() - 40, "Scores", m_font.get()); m_quit = new Button(app->getWindowWidth() / 2, m_scores->getY() - 40, "Exit", m_font.get()); } MenuState::~MenuState() {} void MenuState::update(float deltaTime) { aie::Input* input = aie::Input::getInstance(); if (input->wasMouseButtonPressed(0)) { if (m_start->Collision()) { app->getGameStateManager()->popState(); app->getGameStateManager()->setState((int)eStateID::GAME, new GameState(app)); app->getGameStateManager()->pushState((int)eStateID::GAME); } else if (m_controls->Collision()) { app->getGameStateManager()->popState(); app->getGameStateManager()->pushState((int)eStateID::CONTROLS); } else if (m_scores->Collision()) { app->getGameStateManager()->popState(); app->getGameStateManager()->pushState((int)eStateID::SCORES); } else if (m_quit->Collision()) { app->quit(); } } } void MenuState::render(aie::Renderer2D* renderer) { renderer->drawSprite(resources.getTexture("./textures/splash.png").get(), app->getWindowWidth() / 2, app->getWindowHeight() / 2 + 150, 1000, 400, 0, 0); m_start->Draw(renderer); m_controls->Draw(renderer); m_scores->Draw(renderer); m_quit->Draw(renderer); }
36.266667
153
0.681985
[ "render" ]
adc38dfcf77ce239654964aa2d7013b0d0b6473b
1,269
cpp
C++
cpp/lib/search/bfs.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/search/bfs.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/search/bfs.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; void bfs(int H, int W, int sy, int sx, vector<string> &c, vector<vector<int>> &dist) { vector<vector<int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; queue<pair<int,int>> q; q.push(make_pair(sy, sx)); dist[sy][sx] = 0; int h, w, y, x; while (!q.empty()) { tie(h, w) = q.front(); q.pop(); for (auto p: directions) { y = h + p[0]; x = w + p[1]; if (y < 0 || H <= y || x < 0 || W <= x) continue; if (c[y][x] == '#') continue; if (dist[y][x] != -1) continue; dist[y][x] = dist[h][w] + 1; q.push(make_pair(y, x)); } } } int main() { int H, W, sy, sx, gy, gx; cin >> H >> W >> sy >> sx >> gy >> gx; sy--; sx--; gy--; gx--; vector<string> c(H); rep(h, H) cin >> c[h]; vector<vector<int>> dist(H, vector<int>(W, -1)); bfs(H, W, sy, sx, c, dist); int ans = dist[gy][gx]; cout << ans << endl; return 0; } /* https://atcoder.jp/contests/atc002/tasks/abc007_3 Input 1 ------- 7 8 2 2 4 5 ######## #......# #.###### #..#...# #..##..# ##.....# ######## Output 1 -------- 11 */
20.142857
86
0.427896
[ "vector" ]
adcca3afb4a6b09498041b5d9aeb00cead9e722b
5,286
cpp
C++
CoolProp/purefluids/R125.cpp
perrante/coolprop
c67ecc570e545d624c18feaf2a01e48b63ae1501
[ "MIT" ]
12
2015-04-21T07:43:09.000Z
2021-11-09T08:35:58.000Z
CoolProp/purefluids/R125.cpp
perrante/coolprop
c67ecc570e545d624c18feaf2a01e48b63ae1501
[ "MIT" ]
32
2015-01-04T05:05:05.000Z
2017-12-13T18:03:29.000Z
CoolProp/purefluids/R125.cpp
perrante/coolprop
c67ecc570e545d624c18feaf2a01e48b63ae1501
[ "MIT" ]
8
2015-01-01T21:15:37.000Z
2020-08-05T13:31:50.000Z
#include "CoolProp.h" #include <vector> #include "CPExceptions.h" #include "FluidClass.h" #include "R125.h" #include "REFPROP.h" R125Class::R125Class() { double n[] = {0.0, 5.280760, -8.676580, 0.7501127, 0.7590023, 0.01451899, 4.777189, -3.330988, 3.775673, -2.290919, 0.8888268, -0.6234864, -0.04127263, -0.08455389, -0.1308752, 0.008344962, -1.532005, -0.05883649, 0.02296658}; double t[] = {0, 0.669, 1.05, 2.75, 0.956, 1.00, 2.00, 2.75, 2.38, 3.37, 3.47, 2.63, 3.45, 0.72, 4.23, 0.20, 4.5, 29.0, 24.0}; double d[] = {0, 1, 1, 1, 2, 4, 1, 1, 2, 2, 3, 4, 5, 1, 5, 1, 2, 3, 5}; double l[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 2, 3, 3}; double m[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.7, 7.0, 6.0}; //Critical parameters crit.rho = 4.779*120.0214; //[kg/m^3] crit.p = PressureUnit(3617.7, UNIT_KPA); //[kPa] crit.T = 339.173; //[K] crit.v = 1/crit.rho; // Other fluid parameters params.molemass = 120.0214; params.Ttriple = 172.52; params.accentricfactor = 0.3052; params.R_u = 8.314472; params.ptriple = 2.914; // Limits of EOS limits.Tmin = params.Ttriple; limits.Tmax = 500.0; limits.pmax = 100000.0; limits.rhomax = 1000000.0*params.molemass; phirlist.push_back(new phir_Lemmon2005( n,d,t,l,m,1,18,19)); const double a1 = 37.2674, a2 = 8.88404, a3 = -49.8651; phi0list.push_back(new phi0_lead(a1,a2)); phi0list.push_back(new phi0_logtau(-1)); phi0list.push_back(new phi0_power(a3,-0.1)); double a[] = {0,0,0,0, 2.303, 5.086, 7.3}; double b[] = {0,0,0,0, 0.92578, 2.22895, 5.03283}; std::vector<double> a_v(a,a+sizeof(a)/sizeof(double)); std::vector<double> b_v(b,b+sizeof(b)/sizeof(double)); phi0list.push_back(new phi0_Planck_Einstein(a_v,b_v,4,6)); EOSReference.assign("Lemmon-JPCRD-2005"); TransportReference.assign("Viscosity: Huber IECR 2006\n\n Conductivity: Perkins JCED 2006"); name.assign("R125"); REFPROPname.assign("R125"); BibTeXKeys.EOS = "Lemmon-JPCRD-2005"; BibTeXKeys.VISCOSITY = "Huber-IECR-2006"; BibTeXKeys.CONDUCTIVITY = "Perkins-JCED-2006"; BibTeXKeys.ECS_LENNARD_JONES = "Huber-IECR-2006"; BibTeXKeys.SURFACE_TENSION = "Mulero-JPCRD-2012"; } double R125Class::psat(double T) { const double ti[]={0,1.0,1.5,2.3,4.6}; const double Ni[]={0, -7.5295, 1.9026, -2.2966, -3.4480}; double summer=0,theta; int i; theta=1-T/reduce.T; for (i=1;i<=4;i++) { summer=summer+Ni[i]*pow(theta,ti[i]); } return reduce.p.Pa*exp(reduce.T/T*summer); } double R125Class::rhosatL(double T) { const double ti[]={0,1.0/3.0,0.6,2.9}; const double Ni[]={0, 1.6684, 0.88415, 0.44383}; double summer=0; int i; double theta; theta=1-T/reduce.T; for (i=1;i<=3;i++) { summer+=Ni[i]*pow(theta,ti[i]); } return reduce.rho*(summer+1); } double R125Class::rhosatV(double T) { // Maximum absolute error is 0.161887 % between 87.800001 K and 419.289990 K const double ti[]={0,0.38,1.22,3.3,6.9}; const double Ni[]={0, -2.8403, -7.2738, -21.890, -58.825}; double summer=0,theta; int i; theta=1.0-T/reduce.T; for (i=1; i<=4; i++) { summer=summer+Ni[i]*pow(theta,ti[i]); } return reduce.rho*exp(summer); } double R125Class::viscosity_Trho(double T, double rho) { double b[] = {-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158}; double N_A = 6.0221415e23; double e_k, sigma; this->ECSParams(&e_k,&sigma); double Tstar = T/e_k; double eta_0 = this->viscosity_dilute(T,e_k,sigma)*1e6; // uPa-s //Rainwater-Friend for Bstar double Bstar = b[0]*pow(Tstar,-0.25*0)+b[1]*pow(Tstar,-0.25*1)+b[2]*pow(Tstar,-0.25*2)+b[3]*pow(Tstar,-0.25*3)+b[4]*pow(Tstar,-0.25*4)+b[5]*pow(Tstar,-0.25*5)+b[6]*pow(Tstar,-0.25*6)+b[7]*pow(Tstar,-2.5)+b[8]*pow(Tstar,-5.5); double B = Bstar*N_A*sigma*sigma*sigma/1e27*1000; double e[4][4]; // init with zeros e[2][1] = 0; e[3][2] = 0; e[2][2] = 5.677448e-3; e[3][1] = -5.096662e-3; double c1 = 1.412564e-1, c2 = 3.033797, c3 = 2.992464e-1; double sumresid = 0; double tau = T/crit.T, delta = rho/crit.rho; for (int i = 2; i<=3; i++) { for (int j = 1; j <= 2; j++) { sumresid += e[i][j]*pow(delta,i)/pow(tau,j); } } double delta_0 = c2 + c3*sqrt(T/crit.T); double eta_r = (sumresid + c1*(delta/(delta_0-delta)-delta/delta_0))*1000; // uPa-s double rhobar = rho/params.molemass; // [mol/L] return (eta_0*(1+B*rhobar)+eta_r)/1e6; } void R125Class::ECSParams(double *e_k, double *sigma) { // Huber IECR 2006 *e_k = 237.077; *sigma = 0.5235; } double R125Class::conductivity_Trho(double T, double rho) { // Perkins JCED 2006 double sumresid = 0, tau = T/crit.T; double lambda_0 = (-4.6082e-3 + 1.68688e-2*tau + 4.88345e-3*tau*tau); //[W/m/K] double B1[] = {0, -7.29410e-3, 4.16339e-2, -3.11487e-2, 1.12682e-2, -1.38322e-3}; double B2[] = {0, 1.10497e-2, -2.89236e-2, 2.78399e-2, -1.2110e-2, 2.11196e-3}; for (int i = 1; i <= 5; i++) { sumresid += (B1[i]+B2[i]*T/crit.T)*pow(rho/crit.rho,i); } double lambda_r = sumresid; //[W/m/K] double lambda_c = this->conductivity_critical(T,rho,1.7139e9); //[W/m/K] return lambda_0 + lambda_r + lambda_c; //[W/m/K] } double R125Class::surface_tension_T(double T) { return 0.05252*pow(1-T/crit.T, 1.237); }
31.464286
227
0.622777
[ "vector" ]
add97e9fa17f26fbb2ba5b8d9268039d44db79b7
7,767
cc
C++
elang/compiler/semantics/nodes_test.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2018-01-27T22:40:53.000Z
2018-01-27T22:40:53.000Z
elang/compiler/semantics/nodes_test.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2016-01-29T00:54:49.000Z
2016-01-29T00:54:49.000Z
elang/compiler/semantics/nodes_test.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "elang/compiler/testing/analyzer_test.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/predefined_names.h" #include "elang/compiler/semantics/editor.h" #include "elang/compiler/semantics/factory.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/source_code_range.h" #include "elang/compiler/token.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace sm { ////////////////////////////////////////////////////////////////////// // // SemanticTest // class SemanticTest : public testing::AnalyzerTest { protected: SemanticTest(); ~SemanticTest() override = default; Type* bool_type(); Editor* editor() { return &editor_; } Factory* factory() { return editor()->factory(); } Type* int32_type(); Type* int64_type(); Class* NewClass(Semantic* outer, base::StringPiece name); Class* NewClass(base::StringPiece name); Value* NewLiteral(Type* type, const TokenData& data); Token* NewToken(const TokenData& data); Token* NewToken(base::StringPiece name); std::string ToString(Semantic* node); private: sm::Editor editor_; DISALLOW_COPY_AND_ASSIGN(SemanticTest); }; SemanticTest::SemanticTest() : editor_(session()) { } Type* SemanticTest::bool_type() { return session()->PredefinedTypeOf(PredefinedName::Bool); } Type* SemanticTest::int32_type() { return session()->PredefinedTypeOf(PredefinedName::Int32); } Type* SemanticTest::int64_type() { return session()->PredefinedTypeOf(PredefinedName::Int64); } Class* SemanticTest::NewClass(Semantic* outer, base::StringPiece name) { return factory()->NewClass(outer, Modifiers(), NewToken(name)); } Class* SemanticTest::NewClass(base::StringPiece name) { return NewClass(factory()->global_namespace(), name); } Value* SemanticTest::NewLiteral(Type* type, const TokenData& data) { return factory()->NewLiteral(type, NewToken(data)); } Token* SemanticTest::NewToken(const TokenData& data) { return session()->NewToken(SourceCodeRange(), data); } Token* SemanticTest::NewToken(base::StringPiece name) { return NewToken( TokenData(session()->NewAtomicString(base::UTF8ToUTF16(name)))); } std::string SemanticTest::ToString(Semantic* semantic) { std::ostringstream ostream; ostream << *semantic; return ostream.str(); } TEST_F(SemanticTest, ArrayType) { auto const type1 = factory()->NewArrayType(int32_type(), {10, 20}); auto const type2 = factory()->NewArrayType(int32_type(), {10, 20}); auto const type3 = factory()->NewArrayType(int32_type(), {10}); EXPECT_EQ(type1, type2) << "array type should be unique by element type and dimensions"; EXPECT_NE(type1, type3); EXPECT_EQ(2, type1->rank()); EXPECT_EQ("System.Int32[10, 20]", ToString(type1)); EXPECT_EQ("System.Int32[10]", ToString(type3)); } // Element type of array type is omitting left most rank, e.g. // element_type_of(T[A]) = T // element_type_of(T[A][B}) = T[B] // element_type_of(T[A][B}[C]) = T[B][C] TEST_F(SemanticTest, ArrayTypeArrayOfArray) { auto const type1 = factory()->NewArrayType(int32_type(), {10}); auto const type2 = factory()->NewArrayType(type1, {20}); auto const type3 = factory()->NewArrayType(type2, {30}); EXPECT_EQ("System.Int32[10]", ToString(type1)); EXPECT_EQ("System.Int32[20][10]", ToString(type2)); EXPECT_EQ("System.Int32[30][20][10]", ToString(type3)); } TEST_F(SemanticTest, ArrayTypeUnbound) { EXPECT_EQ("System.Int32[]", ToString(factory()->NewArrayType(int32_type(), {-1}))); EXPECT_EQ("System.Int32[,]", ToString(factory()->NewArrayType(int32_type(), {-1, -1}))); EXPECT_EQ("System.Int32[,,]", ToString(factory()->NewArrayType(int32_type(), {-1, -1, -1}))); } TEST_F(SemanticTest, Class) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const class_type = NewClass(outer, "Bar"); editor()->FixClassBase( class_type, {session()->PredefinedTypeOf(PredefinedName::Object)->as<Class>()}); EXPECT_EQ("Foo.Bar", ToString(class_type)); } TEST_F(SemanticTest, ClassIntermediate) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const class_type = NewClass(outer, "Bar"); EXPECT_EQ("#Foo.Bar", ToString(class_type)); } TEST_F(SemanticTest, Const) { auto const clazz = NewClass("Foo"); auto const node = factory()->NewConst(clazz, NewToken("Bar")); EXPECT_EQ("const ? Foo.Bar = ?", ToString(node)); } TEST_F(SemanticTest, Enum) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const enum_base = int64_type(); auto const enum_type = factory()->NewEnum(outer, NewToken("Color")); editor()->FixEnumBase(enum_type, enum_base); factory()->NewEnumMember(enum_type, NewToken("Red")); factory()->NewEnumMember(enum_type, NewToken("Green")); auto const blue = factory()->NewEnumMember(enum_type, NewToken("Blue")); editor()->FixEnumMember( blue, NewLiteral(enum_base, TokenData(TokenType::Int32Literal, 42))); EXPECT_EQ("enum Foo.Color : System.Int64 {Red, Green, Blue = 42}", ToString(enum_type)); } TEST_F(SemanticTest, EnumIntermediate) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const enum_type = factory()->NewEnum(outer, NewToken("Color")); EXPECT_EQ("#enum Foo.Color", ToString(enum_type)); } TEST_F(SemanticTest, EnumMemberIntermediate) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const enum_type = factory()->NewEnum(outer, NewToken("Color")); auto const enum_member = factory()->NewEnumMember(enum_type, NewToken("Red")); EXPECT_EQ("Foo.Color.Red", ToString(enum_member)); } TEST_F(SemanticTest, Field) { auto const class_type = NewClass("Foo"); auto const field = factory()->NewField(class_type, Modifiers(), NewToken("field_")); EXPECT_EQ("? Foo.field_", ToString(field)); } TEST_F(SemanticTest, Method) { auto const class_type = NewClass("Foo"); auto const method_group = factory()->NewMethodGroup(class_type, NewToken("Bar")); std::vector<Parameter*> parameters{ factory()->NewParameter(ParameterKind::Required, 0, bool_type(), NewToken("a"), nullptr), factory()->NewParameter(ParameterKind::Required, 0, int32_type(), NewToken("b"), nullptr)}; auto const method_signature = factory()->NewSignature(int32_type(), parameters); auto const method = factory()->NewMethod(method_group, Modifiers(), method_signature); EXPECT_EQ("System.Int32 Foo.Bar(System.Bool, System.Int32)", ToString(method)); EXPECT_EQ("(#Foo* this, System.Bool a, System.Int32 b) => System.Int32", ToString(method->function_signature())); } TEST_F(SemanticTest, Namespace) { auto const ns1 = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const ns2 = factory()->NewNamespace(ns1, NewToken("Bar")); EXPECT_EQ("namespace Foo", ToString(ns1)); EXPECT_EQ("namespace Foo.Bar", ToString(ns2)); } TEST_F(SemanticTest, PointerType) { auto const node = factory()->NewPointerType(int32_type()); EXPECT_EQ("System.Int32*", ToString(node)); EXPECT_EQ(node, factory()->NewPointerType(int32_type())); } } // namespace sm } // namespace compiler } // namespace elang
34.52
80
0.690485
[ "object", "vector" ]