hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8633bd0b683be688cd6e306869a339be8a521d34 | 2,269 | cpp | C++ | tile.cpp | hardhat/letssplitup | c2ccd216fd2c90e95590536fe2a9ef688efc650b | [
"BSD-3-Clause"
] | 1 | 2021-05-14T22:09:29.000Z | 2021-05-14T22:09:29.000Z | tile.cpp | hardhat/letssplitup | c2ccd216fd2c90e95590536fe2a9ef688efc650b | [
"BSD-3-Clause"
] | 1 | 2020-05-09T03:26:15.000Z | 2020-05-09T14:51:08.000Z | tile.cpp | hardhat/letssplitup | c2ccd216fd2c90e95590536fe2a9ef688efc650b | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include "tile.h"
#include <SDL.h>
extern "C" {
#include <SDL_image.h>
}
#include <map>
#include "main.h"
#include "sprite.h"
struct Texture {
int w,h;
SDL_Texture *texture;
};
typedef std::map<std::string,int> TileNameMap;
typedef std::map<int,Texture *> TileTextureMap;
static TileNameMap tileNameMap;
static TileTextureMap tileTextureMap;
static int tileId;
Tile::Tile(const char *name,int tileWidth,int tileHeight)
{
this->tileWidth=tileWidth;
this->tileHeight=tileHeight;
imageId=-1;
if(tileNameMap.find(name)!=tileNameMap.end()) {
imageId=tileNameMap[name];
return;
}
std::string path=(std::string)"data/"+name;
SDL_Surface *bitmap=IMG_Load(path.c_str());
if(!bitmap) {
fprintf(stderr,"Can't load image '%s'\n",path.c_str());
return;
}
SDL_Texture* tex = NULL;
tex = SDL_CreateTextureFromSurface(renderer, bitmap);
Texture *texture=new Texture();
texture->w=bitmap->w;
texture->h=bitmap->h;
texture->texture=tex;
SDL_FreeSurface(bitmap);
tileTextureMap[tileId]=texture;
tileNameMap[name]=tileId;
imageId=tileId;
tileId++;
}
Tile::~Tile()
{
}
void Tile::draw(int id,int col,int row)
{
int x=col*tileWidth;
int y=row*tileHeight;
if(id<0) return; // blank spot
if(tileTextureMap.find(imageId)==tileTextureMap.end()) {
SDL_Rect rect={(int)((x-8)*renderScale)+screenleft,(int)((y-8-maptop)*renderScale)+screentop,(int)(tileWidth*renderScale),(int)(tileHeight*renderScale)};
static int color=0;
Uint8 r=255*color/32, g=255, b=255;
color=(color+1)%32;
SDL_SetRenderDrawColor(renderer,r,g,b,255);
SDL_RenderFillRect(renderer,&rect);
return;
}
Texture *t=tileTextureMap[imageId];
int tilesAcross = t->w/tileWidth;
int tx=id%tilesAcross;
int ty=id/tilesAcross;
SDL_Rect srcRect={tx*tileWidth,ty*tileHeight,tileWidth,tileHeight};
SDL_Rect rect={(int)((x-tileWidth/2)*renderScale)+screenleft,(int)((y-tileHeight/2-maptop)*renderScale)+screentop,(int)(tileWidth*renderScale),(int)(tileHeight*renderScale)};
//if(rect.x>screenw || rect.y>screenh || rect.x-rect.w<0 || rect.y-rect.h<0) return;
SDL_RenderCopy(renderer, t->texture, &srcRect, &rect);
}
int Tile::getHeight(){
return tileHeight;
}
int Tile::getWidth(){
return tileWidth;
}
| 24.397849 | 175 | 0.702953 | hardhat |
8637bda3aa071b594aa91beaec8a2d30d0238041 | 6,814 | cpp | C++ | src/libs/gapi/Texture.cpp | JKot-Coder/OpenDemo | 8b9554914f5bab08df47e032486ca668a560c97c | [
"BSD-3-Clause"
] | null | null | null | src/libs/gapi/Texture.cpp | JKot-Coder/OpenDemo | 8b9554914f5bab08df47e032486ca668a560c97c | [
"BSD-3-Clause"
] | null | null | null | src/libs/gapi/Texture.cpp | JKot-Coder/OpenDemo | 8b9554914f5bab08df47e032486ca668a560c97c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "Texture.hpp"
#include "gapi/GpuResourceViews.hpp"
#include "gapi/MemoryAllocation.hpp"
#include "render/DeviceContext.hpp"
#include "common/Math.hpp"
#include "common/OnScopeExit.hpp"
namespace RR
{
namespace GAPI
{
namespace
{
GpuResourceFormat getViewFormat(GpuResourceFormat resourceFormat, GpuResourceFormat viewFormat)
{
if (viewFormat == GpuResourceFormat::Unknown)
{
const bool isDepthStencil = GpuResourceFormatInfo::IsDepth(resourceFormat) && GpuResourceFormatInfo::IsStencil(resourceFormat);
ASSERT(!isDepthStencil);
return resourceFormat;
}
// TODO VALIDATION
return viewFormat;
}
const GpuResourceViewDescription& createViewDesctiption(const GpuResourceDescription& resDesctiption, GpuResourceFormat viewFormat, uint32_t mipLevel, uint32_t mipCount, uint32_t firstArraySlice, uint32_t arraySliceCount)
{
const auto resArraySize = resDesctiption.GetArraySize();
const auto resMipLevels = resDesctiption.GetMipCount();
ASSERT(firstArraySlice < resArraySize);
ASSERT(mipLevel < resMipLevels);
if (mipCount == Texture::MaxPossible)
mipCount = resMipLevels - mipLevel;
if (arraySliceCount == Texture::MaxPossible)
arraySliceCount = resArraySize - firstArraySlice;
ASSERT(firstArraySlice + arraySliceCount <= resArraySize);
ASSERT(mipLevel + mipCount <= resMipLevels);
viewFormat = getViewFormat(resDesctiption.GetFormat(), viewFormat);
return GpuResourceViewDescription::Texture(viewFormat, mipLevel, mipCount, firstArraySlice, arraySliceCount);
}
}
ShaderResourceView::SharedPtr Texture::GetSRV(uint32_t mipLevel, uint32_t mipCount, uint32_t firstArraySlice, uint32_t numArraySlices, GpuResourceFormat format)
{
const const auto& viewDesc = createViewDesctiption(description_, format, mipLevel, 1, firstArraySlice, numArraySlices);
if (srvs_.find(viewDesc) == srvs_.end())
{
auto& renderContext = Render::DeviceContext::Instance();
// TODO static_pointer_cast; name_
srvs_[viewDesc] = renderContext.CreateShaderResourceView(std::static_pointer_cast<Texture>(shared_from_this()), viewDesc);
}
return srvs_[viewDesc];
}
DepthStencilView::SharedPtr Texture::GetDSV(uint32_t mipLevel, uint32_t firstArraySlice, uint32_t numArraySlices, GpuResourceFormat format)
{
const auto& viewDesc = createViewDesctiption(description_, format, mipLevel, 1, firstArraySlice, numArraySlices);
// TODO VALIDATION VIEW DESC FORMAT
if (dsvs_.find(viewDesc) == dsvs_.end())
{
auto& renderContext = Render::DeviceContext::Instance();
// TODO static_pointer_cast; name_
dsvs_[viewDesc] = renderContext.CreateDepthStencilView(std::static_pointer_cast<Texture>(shared_from_this()), viewDesc);
}
return dsvs_[viewDesc];
}
RenderTargetView::SharedPtr Texture::GetRTV(uint32_t mipLevel, uint32_t firstArraySlice, uint32_t numArraySlices, GpuResourceFormat format)
{
const auto& viewDesc = createViewDesctiption(description_, format, mipLevel, 1, firstArraySlice, numArraySlices);
if (rtvs_.find(viewDesc) == rtvs_.end())
{
auto& renderContext = Render::DeviceContext::Instance();
// TODO static_pointer_cast; name_
rtvs_[viewDesc] = renderContext.CreateRenderTargetView(std::static_pointer_cast<Texture>(shared_from_this()), viewDesc);
}
return rtvs_[viewDesc];
}
UnorderedAccessView::SharedPtr Texture::GetUAV(uint32_t mipLevel, uint32_t firstArraySlice, uint32_t numArraySlices, GpuResourceFormat format)
{
const auto& viewDesc = createViewDesctiption(description_, format, mipLevel, 1, firstArraySlice, numArraySlices);
if (uavs_.find(viewDesc) == uavs_.end())
{
auto& renderContext = Render::DeviceContext::Instance();
// TODO static_pointer_cast; name_
uavs_[viewDesc] = renderContext.CreateUnorderedAccessView(std::static_pointer_cast<Texture>(shared_from_this()), viewDesc);
}
return uavs_[viewDesc];
}
void CpuResourceData::CopyDataFrom(const GAPI::CpuResourceData::SharedPtr& source)
{
ASSERT(source);
ASSERT(source != shared_from_this());
static_assert(static_cast<int>(MemoryAllocationType::Count) == 3);
ASSERT(allocation_->GetMemoryType() != GAPI::MemoryAllocationType::Readback);
ASSERT(source->GetAllocation()->GetMemoryType() != GAPI::MemoryAllocationType::Upload);
ASSERT(source->GetFirstSubresource() == GetFirstSubresource());
ASSERT(source->GetNumSubresources() == GetNumSubresources());
const auto sourceDataPointer = static_cast<uint8_t*>(source->GetAllocation()->Map());
const auto destDataPointer = static_cast<uint8_t*>(allocation_->Map());
ON_SCOPE_EXIT(
{
source->GetAllocation()->Unmap();
allocation_->Unmap();
});
const auto numSubresources = source->GetNumSubresources();
for (uint32_t index = 0; index < numSubresources; index++)
{
const auto& sourceFootprint = source->GetSubresourceFootprintAt(index);
const auto& destFootprint = GetSubresourceFootprintAt(index);
ASSERT(sourceFootprint.isComplatable(destFootprint));
for (uint32_t depth = 0; depth < sourceFootprint.depth; depth++)
{
auto sourceRowPointer = sourceDataPointer + sourceFootprint.offset + sourceFootprint.depthPitch * depth;
auto destRowPointer = destDataPointer + destFootprint.offset + destFootprint.depthPitch * depth;
for (uint32_t row = 0; row < sourceFootprint.numRows; row++)
{
std::memcpy(destRowPointer, sourceRowPointer, sourceFootprint.rowSizeInBytes);
sourceRowPointer += sourceFootprint.rowPitch;
destRowPointer += destFootprint.rowPitch;
}
}
}
}
}
} | 44.246753 | 233 | 0.620634 | JKot-Coder |
86390538891c8d7e02f42b6cbb2475461672dd92 | 2,177 | hpp | C++ | core/src/cogs/math/range_to_bits.hpp | cogmine/cogs | ef1c369a36a4f811704e0ced0493c3a6f8eca821 | [
"MIT"
] | 5 | 2019-02-08T15:59:14.000Z | 2022-01-22T19:12:33.000Z | core/src/cogs/math/range_to_bits.hpp | cogmine/cogs | ef1c369a36a4f811704e0ced0493c3a6f8eca821 | [
"MIT"
] | 1 | 2019-12-03T03:11:34.000Z | 2019-12-03T03:11:34.000Z | core/src/cogs/math/range_to_bits.hpp | cogmine/cogs | ef1c369a36a4f811704e0ced0493c3a6f8eca821 | [
"MIT"
] | null | null | null | //
// Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC
//
// Status: Good
#ifndef COGS_HEADER_MATH_RANGE_TO_BITS
#define COGS_HEADER_MATH_RANGE_TO_BITS
#include "cogs/math/bytes_to_int.hpp"
#include "cogs/mem/int_parts.hpp"
namespace cogs {
/// @ingroup ConstMath
/// @brief Template helper that converts a range to the number of bits necessary to represent it.
/// @tparam min_value Minimum value of the range
/// @tparam max_value Maximum value of the range
template <longest min_value, ulongest max_value>
class range_to_bits
{
public:
static constexpr size_t bitsRequiredForMin = range_to_bits<0, (ulongest)~min_value >::value + 1; // if signed
static constexpr size_t bitsRequiredForMax = range_to_bits<0, max_value>::value;
public:
static constexpr size_t value =
(min_value >= 0)
? bitsRequiredForMax
: ((bitsRequiredForMin > bitsRequiredForMax)
? bitsRequiredForMin
: bitsRequiredForMax);
};
template <longest min_value, ulongest max_value> inline constexpr size_t range_to_bits_v = range_to_bits<min_value, max_value>::value;
template <ulongest max_value>
class range_to_bits<0, max_value>
{
private:
template <typename int_t, int_t x, bool unused = true>
class helper;
template <bool unused>
class helper<unsigned char, 0, unused>
{
public:
static constexpr size_t value = 0;
};
template <unsigned char x, bool unused>
class helper<unsigned char, x, unused>
{
public:
static constexpr size_t value = helper<unsigned char, (x >> 1), true>::value + 1;
};
template <typename int_t, int_t x, bool unused>
class helper
{
public:
typedef bytes_to_uint_t<sizeof(int_t) / 2> half_t;
static constexpr half_t highPart = helper<half_t, (half_t)get_const_high_part_v<int_t, x>, true>::value;
static constexpr half_t lowPart = helper<half_t, (half_t)get_const_low_part_v<int_t, x>, true>::value;
static constexpr int_t value = (!highPart) ? lowPart : (highPart + (sizeof(half_t)*8));
};
public:
static constexpr size_t value = helper<ulongest, max_value, true>::value;
};
template <>
class range_to_bits<0, 0>
{
public:
static constexpr size_t value = 0;
};
}
#endif
| 24.188889 | 134 | 0.738631 | cogmine |
863e5e9929eca946b17d0d05c3d5667da7be0ac7 | 407 | cpp | C++ | main.cpp | TheOpenDevProject/Community-Game | e23dd6a10e4fbe61d0bdd684d26ed3ad06514af6 | [
"MIT"
] | 3 | 2016-12-09T07:31:00.000Z | 2016-12-09T22:43:09.000Z | main.cpp | TheOpenDevProject/Community-Game | e23dd6a10e4fbe61d0bdd684d26ed3ad06514af6 | [
"MIT"
] | null | null | null | main.cpp | TheOpenDevProject/Community-Game | e23dd6a10e4fbe61d0bdd684d26ed3ad06514af6 | [
"MIT"
] | null | null | null | #include <QCoreApplication>
#include "gamewindow.h"
#include "testscene.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//Maybe we pass this window to something, not sure if we need an extra layer yet.
std::unique_ptr<TestScene> testingScene(new TestScene);
GameWindow window;
window.changeScene(std::move(testingScene));
window.run();
return a.exec();
}
| 25.4375 | 85 | 0.700246 | TheOpenDevProject |
863fc4a2a1468281f94041e309f4cfa90d88bf62 | 573 | cpp | C++ | Uri-Online-Judge/cpp/1091 - Division of Nlogonia.cpp | ThiagoInocencio/Competitive-Programming-Solutions | efcabdd48d8c103ca619fff53db50aef0ea873d4 | [
"MIT"
] | 1 | 2020-06-07T22:08:42.000Z | 2020-06-07T22:08:42.000Z | Uri-Online-Judge/cpp/1091 - Division of Nlogonia.cpp | ThiagoInocencio/Competitive-Programming-Solutions | efcabdd48d8c103ca619fff53db50aef0ea873d4 | [
"MIT"
] | null | null | null | Uri-Online-Judge/cpp/1091 - Division of Nlogonia.cpp | ThiagoInocencio/Competitive-Programming-Solutions | efcabdd48d8c103ca619fff53db50aef0ea873d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int K, N, M, X, Y, i;
while(cin >> K, K != 0) {
cin >> N >> M;
for(i = 0; i < K; i++) {
cin >> X >> Y;
if(X > N && Y > M)
printf("NE\n");
else if(X > N && Y < M)
printf("SE\n");
else if(X < N && Y > M)
printf("NO\n");
else if(X < N && Y < M)
printf("SO\n");
else
printf("divisa\n");
}
}
return 0;
}
| 17.363636 | 35 | 0.324607 | ThiagoInocencio |
8640a9fe08df688c39223f7f43bbfbba7a3102ca | 2,297 | hpp | C++ | unused/outputStreamBoost.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | null | null | null | unused/outputStreamBoost.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | null | null | null | unused/outputStreamBoost.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | 2 | 2019-12-26T13:54:29.000Z | 2020-10-31T10:19:13.000Z | /*
* outputStreamBoost.hpp
*
* Created on: Jul 30, 2015
* Author: romeo
*/
#ifndef INCLUDE_FLEXIBITY_UNUSED_OUTPUTSTREAMBOOST_HPP_
#define INCLUDE_FLEXIBITY_UNUSED_OUTPUTSTREAMBOOST_HPP_
#include <flexibity/jsonrpc/tests/outputStream.hpp>
#include "flexibity/jsonrpc/jsonRpcBoost.hpp"
#include <memory>
namespace Flexibity{
class JsOSBoost: public JsonRpcOutputStream{
public:
JsOSBoost(std::weak_ptr<Flexibity::jsonRpcBoost> rpc):
service(),
w(service),
_rpcParty(rpc),
bt((boost::bind(&JsOSBoost::loop, this))){
LGF("");
_instances++;
_instance = _instances;
LGF(_instances );
}
JsOSBoost(const JsOSBoost& a):
service(),
w(service),
_rpcParty(a._rpcParty),
bt((boost::bind(&JsOSBoost::loop, this))) {
LGF("cp");
_instances++;
_instance = _instances;
LGF("cp" << _instances );
}
virtual ~JsOSBoost(){
_instances--;
service.stop();
if(bt.joinable()){
bt.join();
}
LGF(_instances );
}
virtual void send(const std::string &buffer){
auto buf = std::make_shared<std::string>(std::string(buffer));
LGF("asked to post:" << endl << buf); //TODO: magage buffer!
service.post(boost::bind(&JsOSBoost::sendOp, this, buf));
}
private:
void sendOp(std::shared_ptr<std::string> buffer){
if(!buffer){
LG("buffer is lost");
return;
}
auto end = buffer->rfind("\n");
if(end != std::string::npos){
LGF("skipping line break in buffer");
}else
end = buffer->length();
if(auto party = _rpcParty.lock()){
LGF("feeding to party (" << buffer->length() << "): " << std::endl << buffer)
//party->feedInput(buffer->c_str(), end);
}else{
LGF("feed buffer is not set: "
<< std::endl << buffer);
}
/*LGF("received:" << endl << buffer);
if(auto p = _rpcParty.lock())
p->feedInput(buffer);
else
LGF("no buffer");*/
}
void loop(){
LGF("enter");
while(!service.stopped()){
size_t ev = service.run_one(); // processes the tasks
LGF("processed " << ev << " event(s)");
}
LGF("exit");
}
boost::asio::io_service service;
boost::asio::io_service::work w;
std::weak_ptr<Flexibity::jsonRpcBoost> _rpcParty;
boost::thread bt;
static int _instances;
int _instance;
};
/*static*/ int JsOSBoost::_instances = 0;
}
#endif /* INCLUDE_FLEXIBITY_UNUSED_OUTPUTSTREAMBOOST_HPP_ */
| 21.268519 | 80 | 0.651284 | flexibity-team |
8649b420886fee702d48dd0ee8ed2a17e2b22346 | 369 | hpp | C++ | hiro/reference/widget/horizontal-scroller.hpp | mp-lee/higan | c38a771f2272c3ee10fcb99f031e982989c08c60 | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | hiro/reference/widget/horizontal-scroller.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 2 | 2015-10-06T14:59:48.000Z | 2022-01-27T08:57:57.000Z | hiro/reference/widget/horizontal-scroller.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | namespace phoenix {
struct pHorizontalScroller : public pWidget {
HorizontalScroller& horizontalScroller;
void setLength(unsigned length);
void setPosition(unsigned position);
pHorizontalScroller(HorizontalScroller& horizontalScroller) : pWidget(horizontalScroller), horizontalScroller(horizontalScroller) {}
void constructor();
void destructor();
};
}
| 24.6 | 134 | 0.794038 | mp-lee |
864b11550741cf37faec2ae7ef2d3e888399fd29 | 3,545 | cpp | C++ | Eudora71/Imapdll/src/MyTypes.cpp | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Windows/Eudora71/Imapdll/src/MyTypes.cpp | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Windows/Eudora71/Imapdll/src/MyTypes.cpp | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | // MyTypes.cpp - Implementations of the utility class and structures for IMAP/
//
#include "stdafx.h"
#include "MyTypes.h"
#include "DebugNewHelpers.h"
// Internals!!
//
//=============== CPtrUidList will be replaced by CUidMap ==========================/
CMsgMap::~CMsgMap()
{
RemoveAll ();
}
// RemoveAll [PUBLIC]
// FUNCTION
// Delete all entries in the map without deleting data items.
// END FUNCITON
void CMsgMap::RemoveAll ()
{
erase (begin(), end());
}
//=================================================================================//
// ======================= CPtrUidList implementation =============================//
CPtrMsgList::CPtrMsgList()
{
InitializeCriticalSection(&m_hMsgLockable);
}
CPtrMsgList::~CPtrMsgList()
{
// Make sure none left.
DeleteAll();
// Put this last!!/
//
DeleteCriticalSection(&m_hMsgLockable);
}
// DeleteAll [PUBLIC]
// FUNCTION
// Delete all data in the list and call RemoveAll.
// END FUNCITON
void CPtrMsgList::DeleteAll ()
{
// Protect this!!!
//
EnterCriticalSection(&m_hMsgLockable);
POSITION pos, next;
unsigned long *pF;
pos = GetHeadPosition();
for( next = pos; pos; pos = next )
{
pF = ( unsigned long * ) GetNext( next );
if (pF)
{
SetAt (pos, NULL);
delete pF;
}
}
RemoveAll();
// Make sure:
LeaveCriticalSection (&m_hMsgLockable);
}
// Append
// FUNCTION
// Append a new object. Note: We assume that when adding msgno's to the list, we only
// higher msgnos, and consecutively!!!
//
// END FUNCTION
// NOTES
// END NOTES.
POSITION CPtrMsgList::Append(unsigned long msgno, unsigned long Uid)
{
POSITION pos = NULL;
if (msgno == 0)
return NULL;
// Protect this!!!
//
EnterCriticalSection(&m_hMsgLockable);
// We MUST be doing this in sequence!!
// This allows us to arbitrarily call this function anytime we get a UID response from the
// server.
//
if ( msgno == (unsigned)GetCount() + 1 )
{
// Allocate mem unsigned long.
//
unsigned long* pNewUid = DEBUG_NEW_NOTHROW unsigned long;
if (pNewUid)
{
*pNewUid = Uid;
pos = AddTail( pNewUid );
}
}
// Make sure.
LeaveCriticalSection(&m_hMsgLockable);
return pos;
}
// Remove [PUBLIC]
//
// Return the removed UID, or 0 if error.
//
unsigned long CPtrMsgList::Remove (unsigned long msgno)
{
POSITION pos, next;
unsigned long ulResult = 0;
// Protect this!!!
//
EnterCriticalSection(&m_hMsgLockable);
pos = GetHeadPosition ();
unsigned long i = 1;
for(next = pos; pos && i < msgno; pos = next, i++ )
{
GetNext (next);
}
if (pos == NULL || i != msgno)
{
ASSERT (0);
}
else
{
unsigned long* pUid = (unsigned long * )GetAt (pos);
if (pUid)
{
ulResult = *pUid;
delete pUid;
}
RemoveAt (pos);
}
// Make sure.
LeaveCriticalSection(&m_hMsgLockable);
return ulResult;
}
// FindUid [PUBLIC]
//
// Loop through the list and return the uid in the position corresponding to msgno.
// Return 0 if error.
//
unsigned long CPtrMsgList::FindUid (unsigned long msgno)
{
// Protect this!!!
//
EnterCriticalSection(&m_hMsgLockable);
// Return value:
unsigned long ulResult = 0;
POSITION pos = GetHeadPosition();
POSITION next;
unsigned long i = 1;
for(next = pos; pos != NULL && i < msgno; pos = next, i++ )
{
GetNext (next);
}
if (pos == NULL || i != msgno)
{
ASSERT (0);
}
else
{
unsigned long* pCurUid = (unsigned long *)GetAt (pos);
if (pCurUid)
{
ulResult = *pCurUid;
}
}
// Make sure.
LeaveCriticalSection(&m_hMsgLockable);
return ulResult;
}
| 15.548246 | 91 | 0.616079 | dusong7 |
8654a8a2d8b7052d45937dac4c4985208a84bb87 | 3,921 | hpp | C++ | include/Expression.hpp | fuchstraumer/CraftingInterpreters | c8787afe11bc963733dff8c61e4f53daaf7c5fc9 | [
"MIT"
] | null | null | null | include/Expression.hpp | fuchstraumer/CraftingInterpreters | c8787afe11bc963733dff8c61e4f53daaf7c5fc9 | [
"MIT"
] | null | null | null | include/Expression.hpp | fuchstraumer/CraftingInterpreters | c8787afe11bc963733dff8c61e4f53daaf7c5fc9 | [
"MIT"
] | null | null | null | #pragma once
#ifndef LOX_EXPRESSION_HPP
#define LOX_EXPRESSION_HPP
#include "Utility.hpp"
#include "Token.hpp"
#include <cstdint>
#include <limits>
#include <string>
#include <variant>
#include <concepts>
/*
Initial grammar:
expression -> literal | unary | binary | grouping ;
literal -> NUMBER | STRING | "true" | "false" | "nil" ;
grouping -> "(" expression ")" ;
unary -> ( "-" | "!" ) expression ;
binary -> expression operator expression
operator -> "==" | "!=" | "<" | "<=" | ">" | ">=" | "+" | "-" | "*" | "/" ;
*/
struct SourceLocation
{
size_t line{ 0u };
size_t column{ 0u };
};
struct Expression
{
Expression() noexcept = default;
~Expression() noexcept = default;
Expression(const Expression&) noexcept = default;
Expression(Expression&&) noexcept = default;
Expression& operator=(const Expression&) noexcept = default;
Expression& operator=(Expression&&) noexcept = default;
SourceLocation loc;
};
// lowest to highest
enum class PrecedenceLevel
{
Expression,
Equality,
Comparison,
Term,
Factor,
Unary,
Primary
};
struct NumericLiteralExpression : public Expression
{
explicit NumericLiteralExpression(float val) noexcept : value{ val } {}
float value{ std::numeric_limits<float>::max() };
};
struct StringLiteralExpression : public Expression
{
explicit StringLiteralExpression(std::string_view sv) noexcept :
value{ sv } {}
std::string value{};
};
struct IdentifierLiteralExpression : public Expression
{
explicit IdentifierLiteralExpression(std::string_view sv) noexcept :
identifier{ sv } {}
std::string identifier{};
};
struct UnaryExpression : public Expression
{
explicit UnaryExpression(LoxToken op, Expression _rhs) noexcept :
operatorToken(std::move(op)), rhs(std::move(_rhs)) {}
LoxToken operatorToken;
Expression rhs;
};
struct BinaryExpression : public Expression
{
explicit BinaryExpression(Expression _lhs, LoxToken op, Expression _rhs) noexcept :
lhs(std::move(_lhs)), operatorToken(std::move(op)), rhs(std::move(_rhs)) {}
Expression lhs;
LoxToken operatorToken;
Expression rhs;
};
struct LanguageLiteralExpression : public Expression
{
explicit LanguageLiteralExpression(TokenType _type, LoxToken _literal) noexcept :
type(_type), literal(_literal) {}
TokenType type;
LoxToken literal;
};
struct GroupingExpression : public Expression
{
Expression group;
};
template<typename T>
concept IsExpressionType = std::is_base_of_v<Expression, T>;
struct PrettyPrinterVisitor
{
template<IsExpressionType ExpressionType>
std::string Visit(const ExpressionType& expr)
{
// doing this ourself ensures that recursive calls parenthetize as well
std::string result("(");
if constexpr (std::is_same_v<ExpressionType, NumericLiteralExpression>)
{
result += std::to_string(expr.value);
}
else if constexpr (std::is_same_v<ExpressionType, StringLiteralExpression>)
{
result += expr.value;
}
else if constexpr (std::is_same_v<ExpressionType, IdentifierLiteralExpression>)
{
result += expr.identifier;
}
else if constexpr (std::is_same_v<ExpressionType, UnaryExpression>)
{
result += TokenTypeToString(expr.operatorToken);
result += " ";
result += Visit(expr.rhs);
}
else if constexpr (std::is_same_v<ExpressionType, BinaryExpression>)
{
result += Visit(expr.lhs);
result += " ";
result += TokenTypeToString(expr.operatorToken);
result += " ";
result += Visit(expr.rhs);
}
else
{
result += "INVALID_EXPRESSION_TYPE";
}
result += ")";
return result;
}
};
#endif //!LOX_EXPRESSION_HPP
| 25.796053 | 87 | 0.643458 | fuchstraumer |
8656f17ce795efeec922d44e3a82b4f96878b390 | 6,677 | cpp | C++ | workspace/PsstTest/src/Test.cpp | PeterSommerlad/workshopworkspace | 5e5eb9c42280a4aba27ee196d3003fd54a5e3607 | [
"MIT"
] | 2 | 2021-08-28T11:43:58.000Z | 2021-09-07T08:10:05.000Z | workspace/PsstTest/src/Test.cpp | PeterSommerlad/workshopworkspace | 5e5eb9c42280a4aba27ee196d3003fd54a5e3607 | [
"MIT"
] | null | null | null | workspace/PsstTest/src/Test.cpp | PeterSommerlad/workshopworkspace | 5e5eb9c42280a4aba27ee196d3003fd54a5e3607 | [
"MIT"
] | null | null | null | #include "psst.h"
#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"
#include <string>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <utility>
#include <cstddef>
using namespace Psst;
struct Int: strong<int,Int>,ops<Int,Cmp,Inc,Add,Eq,Out>{
};
struct Size: strong<unsigned,Size>,ops<Size,Eq,Cmp,Inc,Add,Out> {
};
static_assert(sizeof(Size)==sizeof(unsigned),"no overhead");
void testSizeworks(){
Size sz{42};
//ASSERT_EQUAL(42,sz);// doesn't compile
//ASSERT_EQUAL(42u,sz);//doesn't compile
ASSERT_EQUAL(Size{21}+Size{21},sz);
}
void testBoolConverts(){
//bool b=Bool{};
// Bool b42{42}; // unfortunately, only a SFINAE ctor could diallow that, not considered narrowing
//int i{b42}; // no automatic conversion
// ASSERTM("start writing tests", b42);
}
namespace test {
struct Size: strong<size_t,Size>,ops<Size,Eq,Cmp,Additive,Out> {
};
struct Diff: strong<std::ptrdiff_t,Diff>,ops<Diff,Eq,Cmp,Additive,Out>{};
template <typename T, size_t N>
struct array{
T a[N];
using size_type=Size;
using value_type=T;
using difference_type=Diff;
using reference=value_type&;
using const_reference= value_type const&;
using pointer=value_type*;
using const_pointer=const value_type*;
using iterator=pointer;
using const_iterator=const_pointer;
using reverse_iterator=std::reverse_iterator<iterator>;
using const_reverse_iterator=std::reverse_iterator<const_iterator>;
constexpr pointer data() { return a;}
constexpr const_pointer data() const { return a;}
constexpr reference at( size_type pos ) { if (pos < size()) return a[pos]; throw std::out_of_range{"array::at"};}
constexpr const_reference at( size_type pos ) const { if (pos < size()) return a[pos]; throw std::out_of_range{"array::at"};}
constexpr reference operator[]( size_type pos ) { return a[pos];}
constexpr const_reference operator[]( size_type pos ) const { return a[pos]; }
constexpr reference front() { return *a;}
constexpr const_reference front() const{ return *a;}
constexpr reference back() { return a[N-1];}
constexpr const_reference back() const{ return a[N-1];}
constexpr iterator begin() noexcept{return a;}
constexpr const_iterator begin() const noexcept {return a;}
constexpr const_iterator cbegin() const noexcept {return a;}
constexpr iterator end() noexcept {return a+N;}
constexpr const_iterator end() const noexcept {return a+N;}
constexpr const_iterator cend() const noexcept {return a+N;}
constexpr reverse_iterator rbegin() noexcept { return reverse_iterator(end());}
constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end());}
constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end());}
constexpr reverse_iterator rend() noexcept { return reverse_iterator(begin());}
constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin());}
constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin());}
constexpr bool empty() const noexcept {return N !=0;}
constexpr size_type size() const noexcept { return size_type{N};}
constexpr size_type max_size() const noexcept { return size();}
constexpr void fill( const T& value ) { std::fill(begin(),end(),value);}
constexpr void swap( array& other ) noexcept(std::is_nothrow_swappable<T>::value){ std::swap_ranges(begin(), end(), other.begin());}
};
template <class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;
}
void InsaneBool() {
Int x{42};
++x;
ASSERT_EQUAL(43,x.get());
}
void testUPlus(){
struct uptest:strong<int,uptest>,ops<uptest,UPlus>{};
uptest one{1};
ASSERT_EQUAL(one.val,(+one).val);
}
void testUMinus(){
struct umtest:strong<int,umtest>,ops<umtest,UMinus>{};
umtest one{1};
ASSERT_EQUAL(-(one.val),(-one).val);
}
void testUInc(){
struct uinctest:strong<int,uinctest>,ops<uinctest,Inc>{};
uinctest var{1};
ASSERT_EQUAL(2,(++var).val);
ASSERT_EQUAL(2,(var++).val);
ASSERT_EQUAL(3,var.val);
}
void testUDec(){
struct udtest:strong<int,udtest>,ops<udtest,Dec>{};
udtest var{2};
ASSERT_EQUAL(1,(--var).val);
ASSERT_EQUAL(1,(var--).val);
ASSERT_EQUAL(0,var.val);
}
void testWithStringBase(){
struct S:strong<std::string,S>,ops<S,Out,Eq>{};
S s{"hello"};
ASSERT_EQUAL(S{"hello"},s);
}
//namespace testRelativeOps{
//struct WidthD : Relative<WidthD,double>{};
//
//void testWidthDConstructionEq(){
// WidthD w{3.14};
// ASSERT_EQUAL(WidthD{3.14},w);
//}
//
//void testWidthDMultiplyWith(){
// WidthD w{42.0};
//// w /= 2.0;
// w *= 2.0;
//// w += w;
//// w /= 2;
// ASSERT_EQUAL(WidthD{42},w);
//}
//void testWidthDAddable(){
// WidthD w{42.0};
// w += w;
// w++;
// ASSERT_EQUAL(WidthD{86},++w);
//}
//void testWidthDSubtractable(){
// WidthD w{42.0};
// w -= WidthD{-2};
// w--;
// ASSERT_EQUAL(WidthD{42},--w);
//}
//void testWidthDivides(){
// WidthD w{42.0};
// auto d= w / WidthD{21};
// static_assert(std::is_same_v<decltype(d),underlying_value_type<WidthD>>,"should be double");
// ASSERT_EQUAL(2,d);
//}
////struct Diff : strong<std::ptrdiff_t,Diff>,ops<Diff,RelArithmetic<std::ptrdiff_t>::apply,Eq,Cmp,Out>{};
//struct Diff:Relative<Diff,std::ptrdiff_t>{};
//void testDiffCtorEq(){
// Diff d{42};
// ASSERT_EQUAL(Diff{42},d);
//}
//
//}
struct WaitC:strong<unsigned,WaitC>
,ops<WaitC,Eq,Inc,Out>{};
static_assert(sizeof(unsigned)==sizeof(WaitC));
void testWaitCounter(){
WaitC c{};
WaitC const one{1};
ASSERT_EQUAL(WaitC{0},c);
ASSERT_EQUAL(one,++c);
ASSERT_EQUAL(one,c++);
ASSERT_EQUAL(2,c.val);
}
bool runAllTests(int argc, char const *argv[]) {
cute::suite s { };
//TODO add your test here
s.push_back(CUTE(InsaneBool));
s.push_back(CUTE(testWithStringBase));
s.push_back(CUTE(testSizeworks));
// s.push_back(CUTE(testRelativeOps::testWidthDConstructionEq));
// s.push_back(CUTE(testRelativeOps::testWidthDMultiplyWith));
// s.push_back(CUTE(testRelativeOps::testWidthDAddable));
// s.push_back(CUTE(testRelativeOps::testWidthDSubtractable));
// s.push_back(CUTE(testRelativeOps::testWidthDivides));
// s.push_back(CUTE(testRelativeOps::testDiffCtorEq));
s.push_back(CUTE(testUPlus));
s.push_back(CUTE(testUMinus));
s.push_back(CUTE(testUInc));
s.push_back(CUTE(testUDec));
s.push_back(CUTE(testBoolConverts));
s.push_back(CUTE(testWaitCounter));
cute::xml_file_opener xmlfile(argc, argv);
cute::xml_listener<cute::ide_listener<>> lis(xmlfile.out);
auto runner = cute::makeRunner(lis, argc, argv);
bool success = runner(s, "AllTests");
return success;
}
int main(int argc, char const *argv[]) {
return runAllTests(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 30.35 | 133 | 0.713045 | PeterSommerlad |
866045ba1fd59818cba0e6184d80fb3e638578f0 | 1,779 | hpp | C++ | PhysicsTestbeds/Physics2dCore/Collision/PrimitiveGeometry2d.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | PhysicsTestbeds/Physics2dCore/Collision/PrimitiveGeometry2d.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | PhysicsTestbeds/Physics2dCore/Collision/PrimitiveGeometry2d.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | #pragma once
#include "Physics2dCore/Physics2dCoreStandard.hpp"
#include "Collision/IntersectionInterval2d.hpp"
#include "Collision/IntersectionTypes2d.hpp"
namespace Physics2d
{
class Mesh2d;
class Manifold2d;
//-------------------------------------------------------------------PrimitiveGeometry2d
class PrimitiveGeometry2d
{
public:
static IntersectionType::Type PointPlane(const Vector2& point, const Vector3& planeData, float epsilon);
static bool PointAabb(const Vector2& point, const Vector2& aabbMin, const Vector2& aabbMax);
static bool PointCircle(const Vector2& point, const Vector2& circleCenter, float circleRadius);
static bool RayPlane(const Vector2& rayStart, const Vector2& rayDir, const Vector3& planeData, float& t, float parallelCheckEpsilon = 0.0001f);
static RayIntersectionType RayAabb(const Vector2& rayStart, const Vector2& rayDir, const Vector2& aabbMin, const Vector2& aabbMax, IntersectionInterval2d& interval, float parallelCheckEpsilon = 0.0001f);
static RayIntersectionType RayAabb(const Vector2& rayStart, const Vector2& rayDir, const Vector2& aabbMin, const Vector2& aabbMax, float& t, float parallelCheckEpsilon = 0.0001f);
static RayIntersectionType RayCircle(const Vector2& rayStart, const Vector2& rayDir, const Vector2& circleCenter, float circleRadius, IntersectionInterval2d& interval);
static RayIntersectionType RayCircle(const Vector2& rayStart, const Vector2& rayDir, const Vector2& circleCenter, float circleRadius, float& t);
static bool AabbAabb(const Vector2& aabb0Min, const Vector2& aabb0Max, const Vector2& aabb1Min, const Vector2& aabb1Max);
static bool CircleCircle(const Vector2& circle0Center, float circle0Radius, const Vector2& circle1Center, float circle1Radius);
};
}//namespace Physics2d
| 49.416667 | 205 | 0.775155 | jodavis42 |
8667f55edbd0a21f7e79ce19f3aae3f16f90ed73 | 13,406 | cpp | C++ | src/cpp/initialiser.cpp | mikhailiuk/Deep-Learning-Applied-To-Seismic-Data | 3c3a17b0db670fac71026717bb96277f22717d6f | [
"MIT"
] | 12 | 2018-03-19T21:56:52.000Z | 2022-03-09T00:31:53.000Z | src/cpp/initialiser.cpp | mikhailiuk/Deep-Learning-Applied-To-Seismic-Data | 3c3a17b0db670fac71026717bb96277f22717d6f | [
"MIT"
] | null | null | null | src/cpp/initialiser.cpp | mikhailiuk/Deep-Learning-Applied-To-Seismic-Data | 3c3a17b0db670fac71026717bb96277f22717d6f | [
"MIT"
] | 6 | 2018-01-13T07:07:19.000Z | 2020-04-03T03:21:06.000Z | // Author: Aliaksei Mikhailiuk, 2017.
#include "../headers/Initialiser.h"
int Initialiser::initialise(NeuralNetwork *&neuralNetwork,TrainingAlgorithm *Alg){
Config cfg;
ParamsInit parameters;
// Open config file, check for errors
try{
cfg.readFile("./config/config.cfg");
} catch(const FileIOException &fioex) {
std::cerr << "I/O error while reading file." << std::endl;
return(EXIT_FAILURE);
}catch(const ParseException &pex){
std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
<< " - " << pex.getError() << std::endl;
return(EXIT_FAILURE);
}
// Look up arrays
Setting& actFunctions = cfg.lookup("neuralnetwork.actFunctions");
Setting& layers = cfg.lookup("neuralnetwork.layers");
Setting& patch = cfg.lookup("neuralnetwork.patch");
Setting& shiftTest = cfg.lookup("neuralnetwork.shiftTest");
Setting& shiftTrain = cfg.lookup("neuralnetwork.shiftTrain");
Setting& dynamicLearningRate = cfg.lookup("neuralnetwork.dynamicLearningR");
// Look up individual values
try{
cfg.lookupValue("neuralnetwork.weightedErrorFlag",parameters.weightedErrorFlag);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'weightedErrorFlag' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.augment",parameters.augment);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'augment' setting in configuration file." << std::endl;
}
try{
parameters.weightsInit = (const char *)cfg.lookup("neuralnetwork.weightsInit");
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'weightsInit' setting in configuration file." << std::endl;
}
try{
parameters.nameDataTrainIn = (const char *)cfg.lookup("neuralnetwork.nameTrainIn");
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'nameDataTrainIn' setting in configuration file." << std::endl;
}
try{
parameters.nameDataTestIn = (const char *)cfg.lookup("neuralnetwork.nameTestIn");
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'nameDataTestIn' setting in configuration file." << std::endl;
}
try{
parameters.nameMaskTest = (const char *)cfg.lookup("neuralnetwork.nameMaskTest");
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'nameMask' setting in configuration file." << std::endl;
}
try{
parameters.nameMaskValidation = (const char *)cfg.lookup("neuralnetwork.nameMaskValidation");
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'nameMask' setting in configuration file." << std::endl;
}
try{
parameters.saveFolder = (const char *)cfg.lookup("neuralnetwork.saveFolder");
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'saveFolder' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.weightMagnitude",parameters.weightMagnitude);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'weightMagnitude' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.weightsInitFlag",parameters.weightsInitFlag);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'weightsInitFlag' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.numbEpoches",parameters.numbEpoches);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'numbEpoches' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.numbItTest",parameters.numbItTest);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'numbItTest' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.numbItValidation",parameters.numbItValidation);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'numbItValidation' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.numbItTrain",parameters.numbItTrain);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'numbItTrain' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.numbLayers",parameters.numbLayers);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'numbLayers' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.miniBatch",parameters.miniBatch);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'miniBatch' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.lambda",parameters.lambda);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'lambda' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.learningRate",parameters.learningRate);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'learningRate' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.annealing",parameters.annealing);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'annealing' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.bias",parameters.bias);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'bias' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.randomFlag",parameters.randomFlag);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'randomFlag' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.objective",parameters.objective);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'objective' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.huberDelta",parameters.huberDelta);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'huberDelta' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.momentum",parameters.momentum);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'momentum' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.adaGrad",parameters.adaGrad);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'adaGrad' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.curriculum",parameters.curriculum);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'curriculum' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.maskFlagValidation",parameters.maskFlagValidation);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'maskFlagValidation' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.maskFlagTest",parameters.maskFlagTest);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'maskFlagTest' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.statsFlag",parameters.statsFlag);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'statsFlag' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.freezeFractionEpochs",parameters.freezeFractionEpochs);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'freezeFractionEpochs' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.weightFreezeFlag",parameters.weightFreezeFlag);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'weightFreezeFlag' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.shuffleFlag",parameters.shuffleFlag);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'shuffleFlag' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.dropOut",parameters.dropOut);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'dropOut' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.inputScale",parameters.inputScale);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'inputScale' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.sparsityParameter",parameters.sparsityParameter);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'sparsityParameter' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.sparse",parameters.sparse);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'sparse' setting in configuration file." << std::endl;
}
try{
cfg.lookupValue("neuralnetwork.polishing",parameters.polishing);
}catch(const SettingNotFoundException &nfex){
std::cerr << "No 'polishing' setting in configuration file." << std::endl;
}
// Copy read arrays into the parameters variables
parameters.patchZ=(int)patch[0];
parameters.patchY=(int)patch[1];
parameters.patchX =(int)patch[2];
parameters.shiftZTest=(int)shiftTest[0];
parameters.shiftYTest=(int)shiftTest[1];
parameters.shiftXTest=(int)shiftTest[2];
parameters.shiftZTrain=(int)shiftTrain[0];
parameters.shiftYTrain=(int)shiftTrain[1];
parameters.shiftXTrain=(int)shiftTrain[2];
parameters.learningRateLower = dynamicLearningRate[0];
parameters.learningRateUpper = dynamicLearningRate[1];
// Check whether the number of layers in the array is the same as specified
// copy the sizes of the layers to the parameters array
if (layers.getLength()==parameters.numbLayers){
for (int ii = 0; ii < parameters.numbLayers; ii++) {
parameters.layersVec.push_back((int)layers[ii]);
}
} else {
std::cout<<"Settings numbLayers and size of Array do not match\n";
exit(0);
}
// Check whether the number of activations in the array is the same as specified
// copy the sizes of the activations to the parameters array
if (actFunctions.getLength()==parameters.numbLayers){
for (int ii = 0; ii < parameters.numbLayers; ii++) {
parameters.actVec.push_back((int)actFunctions[ii]);
}
} else {
std::cout<<"Settings numbLayers and size of Act Array do not match\n";
exit(0);
}
// If lambda is not 0, then the contractive is used
if (parameters.lambda!= 0.0){
neuralNetwork = new ContractiveAutoencoder();
// Otherwise a simple autoencoder is used
}else {
neuralNetwork = new Autoencoder();
}
// Check the values of the parameters in the sanity check
parameters.sanityCheck();
// Update the size of the patches
parameters.updatePatchSize();
//printf("here1\n");
// Initialise the neural netowork
neuralNetwork->initialise(parameters);
//printf("here2\n");
// Initialise the algorithm
Alg->initialise(parameters);
//printf("here3\n");
// If the user wants to init weights from a file, then do it
if (parameters.weightsInitFlag==1){
neuralNetwork->initWeightsFromFile(parameters.weightsInit);
}
//printf("here4\n");
return 0;
}
| 41.504644 | 109 | 0.594137 | mikhailiuk |
866d4fca95d8819facaee161f2788d02a643df54 | 2,456 | cpp | C++ | src/event_loop.cpp | logikoisto/Skunk | 0856853495a792a12576a3e7167950d6e0d34efe | [
"MIT"
] | 3 | 2021-05-07T02:44:35.000Z | 2021-05-09T03:53:37.000Z | src/event_loop.cpp | logikoisto/Skunk | 0856853495a792a12576a3e7167950d6e0d34efe | [
"MIT"
] | null | null | null | src/event_loop.cpp | logikoisto/Skunk | 0856853495a792a12576a3e7167950d6e0d34efe | [
"MIT"
] | null | null | null | #include "event_loop.h"
#include <fcntl.h>
#include <memory>
#include "channel.h"
#include "poller.h"
#include "util/condition.h"
#include "util/mutex.h"
namespace zoo {
namespace skunk {
class Channel;
const int64_t kPollTimeMs = 1000;
EventLoop::EventLoop(bool is_main_loop)
: thread_(std::bind(&EventLoop::Loop, shared_from_this())),
poller_(std::make_shared<Poller>(shared_from_this())),
mutex_(),
is_main_loop_(is_main_loop),
started_(false){};
void EventLoop::Start() {
MutexGuard gurd(mutex_);
if (started_) {
return;
} else {
thread_.start();
started_ = true;
}
};
EventLoop::~EventLoop(){};
void EventLoop::Stop() {
MutexGuard gurd(mutex_);
if (!started_) {
return;
} else {
started_ = false;
}
};
// 事件循环的主流程
void EventLoop::Loop() {
while (true) {
{
MutexGuard gurd(mutex_);
if (!started_) {
break;
}
}
poller_->Poll(kPollTimeMs);
int32_t active_channel_size = poller_->active_channel_list_.size();
for (int32_t i = 0; i < active_channel_size; i++) {
// 分发事件
std::shared_ptr<Channel> channel = poller_->active_channel_list_[i];
channel->HandleEvent();
}
poller_->active_channel_list_.clear();
}
thread_.join();
};
// 将连接添加到 当前的 event loop中
void EventLoop::AddConnection(std::shared_ptr<Socket> socket,
EventLoop::Event event) {
// 创建 channel 对象
std::shared_ptr<Channel> channel =
std::make_shared<Channel>(shared_from_this());
std::shared_ptr<Connection> conn =
std::make_shared<Connection>(channel, socket);
if (!poller_->HasChannel(channel)) {
switch (event) {
case EventLoop::Accept:
channel->EnableAccept();
break;
case EventLoop::Read:
channel->EnableRead();
break;
case EventLoop::Write:
channel->EnableWrite();
break;
default:
break;
}
poller_->UpdateChannel(channel);
}
};
void EventLoop::UpdateChannel(const std::shared_ptr<Channel> channel) {
poller_->UpdateChannel(channel);
};
void EventLoop::RemoveChannel(const std::shared_ptr<Channel> channel) {
if (poller_->HasChannel(channel)) {
channel->DisableAll();
poller_->RemoveChannel(channel);
}
};
// TODO: timer api
static std::shared_ptr<EventLoop> CreateEventLoop(bool isMainLoop) {
return std::make_shared<EventLoop>(isMainLoop);
}
} // namespace skunk
} // namespace zoo | 24.316832 | 74 | 0.645358 | logikoisto |
866d60dfcdc4e753b9077fd962ff4e74c7b79e43 | 1,439 | hpp | C++ | pomdog/experimental/skeletal2d/blendtrees/animation_graph.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 163 | 2015-03-16T08:42:32.000Z | 2022-01-11T21:40:22.000Z | pomdog/experimental/skeletal2d/blendtrees/animation_graph.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 17 | 2015-04-12T20:57:50.000Z | 2020-10-10T10:51:45.000Z | pomdog/experimental/skeletal2d/blendtrees/animation_graph.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 21 | 2015-04-12T20:45:11.000Z | 2022-01-14T20:50:16.000Z | // Copyright mogemimi. Distributed under the MIT license.
#pragma once
#include "pomdog/basic/conditional_compilation.hpp"
#include "pomdog/experimental/skeletal2d/blendtrees/animation_blend_input.hpp"
#include "pomdog/experimental/skeletal2d/blendtrees/animation_node.hpp"
#include "pomdog/utility/assert.hpp"
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <algorithm>
#include <cstdint>
#include <memory>
#include <optional>
#include <vector>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END
namespace pomdog::skeletal2d {
class AnimationGraphState final {
public:
std::string Name;
std::unique_ptr<AnimationNode> Tree;
};
class AnimationGraph final {
public:
std::vector<AnimationGraphState> States;
std::vector<AnimationBlendInput> Inputs;
std::optional<std::uint16_t> FindParameter(const std::string& name) const
{
auto iter = std::find_if(std::begin(Inputs), std::end(Inputs), [&name](const AnimationBlendInput& input) {
return input.Name == name;
});
if (iter != std::end(Inputs)) {
POMDOG_ASSERT(Inputs.size() <= std::numeric_limits<std::uint16_t>::max());
auto d = std::distance(std::begin(Inputs), iter);
POMDOG_ASSERT(d <= std::numeric_limits<std::uint16_t>::max());
return static_cast<std::uint16_t>(d);
}
return std::nullopt;
}
};
} // namespace pomdog::skeletal2d
| 29.367347 | 114 | 0.705351 | mogemimi |
8675804a54f9a72ff3938f1b25eb9b33489663af | 9,281 | cc | C++ | ithwrapper/ith/cli/main.cc | wareya/chiitrans | 7a392a304e6315cb4ecf836804512bb972090e8b | [
"Apache-2.0"
] | 71 | 2015-01-06T03:06:25.000Z | 2022-03-02T17:47:28.000Z | ithwrapper/ith/cli/main.cc | holemcross/chiitrans | c5e9aba5f555b1f81792d1dd4864b7efeb12f823 | [
"Apache-2.0"
] | 7 | 2015-01-14T15:08:41.000Z | 2018-11-20T18:18:15.000Z | ithwrapper/ith/cli/main.cc | holemcross/chiitrans | c5e9aba5f555b1f81792d1dd4864b7efeb12f823 | [
"Apache-2.0"
] | 35 | 2015-05-24T02:16:17.000Z | 2022-03-23T18:52:56.000Z | // main.cc
// 8/24/2013 jichi
// Branch: ITH_DLL/main.cpp, rev 128
// 8/24/2013 TODO: Clean up this file
#ifdef _MSC_VER
# pragma warning (disable:4100) // C4100: unreference formal parameter
# pragma warning (disable:4733) // C4733: Inline asm assigning to 'FS:0' : handler not registered as safe handler
#endif // _MSC_VER
#include "cli_p.h"
#include "avl_p.h"
#include "ith/common/defs.h"
#include "ith/common/except.h"
//#include "ith/common/growl.h"
#include "ith/sys/sys.h"
//#include "md5.h"
//#include <ITH\AVL.h>
//#include <ITH\ntdll.h>
enum { HOOK_BUFFER_SIZE = MAX_HOOK *sizeof(TextHook) };
//#define MAX_HOOK (HOOK_BUFFER_SIZE/sizeof(TextHook))
WCHAR dll_mutex[0x100];
//WCHAR dll_name[0x100];
WCHAR hm_mutex[0x100];
WCHAR hm_section[0x100];
HINSTANCE hDLL;
HANDLE hSection;
bool running,live = false;
int current_hook = 0,
user_hook_count = 0;
DWORD trigger = 0;
HANDLE hSendThread,
hCmdThread,
hFile,
hMutex,
hmMutex;
DWORD hook_buff_len = HOOK_BUFFER_SIZE;
//DWORD current_process_id;
extern DWORD enter_count;
//extern LPWSTR current_dir;
extern DWORD engine_type;
extern DWORD module_base;
AVLTree<char, FunctionInfo, SCMP, SCPY, SLEN> *tree;
namespace { // unnamed
void AddModule(DWORD hModule, DWORD size, LPWSTR name)
{
IMAGE_DOS_HEADER *DosHdr;
IMAGE_NT_HEADERS *NtHdr;
IMAGE_EXPORT_DIRECTORY *ExtDir;
UINT uj;
FunctionInfo info = {0, hModule, size, name};
char *pcFuncPtr, *pcBuffer;
DWORD dwReadAddr, dwFuncName, dwExportAddr;
WORD wOrd;
DosHdr = (IMAGE_DOS_HEADER *)hModule;
if (IMAGE_DOS_SIGNATURE==DosHdr->e_magic) {
dwReadAddr = hModule + DosHdr->e_lfanew;
NtHdr = (IMAGE_NT_HEADERS *)dwReadAddr;
if (IMAGE_NT_SIGNATURE == NtHdr->Signature) {
dwExportAddr = NtHdr->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
if (dwExportAddr == 0)
return;
dwExportAddr+=hModule;
ExtDir=(IMAGE_EXPORT_DIRECTORY*)dwExportAddr;
dwExportAddr=hModule+ExtDir->AddressOfNames;
for (uj = 0; uj < ExtDir->NumberOfNames; uj++) {
dwFuncName=*(DWORD*)dwExportAddr;
pcBuffer = (char *)(hModule+dwFuncName);
pcFuncPtr=(char *)(hModule+(DWORD)ExtDir->AddressOfNameOrdinals+(uj*sizeof(WORD)));
wOrd = *(WORD *)pcFuncPtr;
pcFuncPtr = (char *)(hModule+(DWORD)ExtDir->AddressOfFunctions+(wOrd*sizeof(DWORD)));
info.addr=hModule+*(DWORD*)pcFuncPtr;
::tree->Insert(pcBuffer,info);
dwExportAddr+=sizeof(DWORD);
}
}
}
}
void GetFunctionNames()
{
// jichi 9/26/2013: AVLTree is already zero
PPEB ppeb;
__asm
{
mov eax,fs:[0x30]
mov ppeb,eax
}
DWORD temp = *(DWORD *)(&ppeb->Ldr->InLoadOrderModuleList);
PLDR_DATA_TABLE_ENTRY it = (PLDR_DATA_TABLE_ENTRY)temp;
while (it->SizeOfImage) {
AddModule((DWORD)it->DllBase, it->SizeOfImage, it->BaseDllName.Buffer);
it=(PLDR_DATA_TABLE_ENTRY)it->InLoadOrderModuleList.Flink;
if (*(DWORD *)it==temp)
break;
}
}
} // unnamed namespace
DWORD IHFAPI GetFunctionAddr(const char *name, DWORD *addr, DWORD *base, DWORD *size, LPWSTR *base_name)
{
TreeNode<char *,FunctionInfo> *node = ::tree->Search(name);
if (node) {
if (addr) *addr = node->data.addr;
if (base) *base = node->data.module;
if (size) *size = node->data.size;
if (base_name) *base_name = node->data.name;
return TRUE;
}
else
return FALSE;
}
void RequestRefreshProfile()
{
if (live) {
BYTE buffer[0x80];
*(DWORD *)buffer = -1;
*(DWORD *)(buffer + 4) = 1;
*(DWORD *)(buffer + 8) = 0;
IO_STATUS_BLOCK ios;
CliLockPipe();
NtWriteFile(hPipe, 0, 0, 0, &ios, buffer, HEADER_SIZE, 0, 0);
CliUnlockPipe();
}
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
//static WCHAR dll_exist[] = L"ITH_DLL_RUNNING";
static WCHAR dll_exist[] = ITH_CLIENT_MUTEX;
static HANDLE hDllExist;
// jichi 9/23/2013: wine deficenciy on mapping sections
// Whe set to false, do not map sections.
//static bool ith_has_section = true;
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
{
LdrDisableThreadCalloutsForDll(hinstDLL);
IthBreak();
module_base = (DWORD)hinstDLL;
IthInitSystemService();
swprintf(hm_section, ITH_SECTION_ L"%d", current_process_id);
// jichi 9/25/2013: Interprocedural communication with vnrsrv.
hSection = IthCreateSection(hm_section, 0x2000, PAGE_EXECUTE_READWRITE);
::hookman = nullptr;
NtMapViewOfSection(hSection, NtCurrentProcess(),
(LPVOID *)&::hookman, 0, hook_buff_len, 0, &hook_buff_len, ViewUnmap, 0,
PAGE_EXECUTE_READWRITE);
//PAGE_EXECUTE_READWRITE);
//if (!::hookman) {
// ith_has_section = false;
// ::hookman = new TextHook[MAX_HOOK];
// memset(::hookman, 0, MAX_HOOK * sizeof(TextHook));
//}
//LPCWSTR p;
//for (p = GetMainModulePath(); *p; p++);
//for (p = p; *p != L'\\'; p--);
//wcscpy(dll_name, p + 1);
//swprintf(dll_mutex,L"ITH_%.4d_%s",current_process_id,current_dir);
swprintf(dll_mutex, ITH_PROCESS_MUTEX_ L"%d", current_process_id);
swprintf(hm_mutex, ITH_HOOKMAN_MUTEX_ L"%d", current_process_id);
hmMutex = IthCreateMutex(hm_mutex, FALSE);
DWORD s;
hMutex = IthCreateMutex(dll_mutex, TRUE, &s); // jichi 9/18/2013: own is true
if (s)
return FALSE;
hDllExist = IthCreateMutex(dll_exist, 0);
hDLL = hinstDLL;
running = true;
current_available = hookman;
::tree = new AVLTree<char, FunctionInfo, SCMP, SCPY, SLEN>;
GetFunctionNames();
InitFilterTable();
InitDefaultHook();
hSendThread = IthCreateThread(WaitForPipe, 0);
hCmdThread = IthCreateThread(CommandPipe, 0);
} break;
case DLL_PROCESS_DETACH:
{
// jichi 10/2/2103: Cannot use __try in functions that require object unwinding
//ITH_TRY {
running = false;
live = false;
const LONGLONG timeout = -50000000; // in nanoseconds = 5 seconds
NtWaitForSingleObject(hSendThread, 0, (PLARGE_INTEGER)&timeout);
NtWaitForSingleObject(hCmdThread, 0, (PLARGE_INTEGER)&timeout);
NtClose(hCmdThread);
NtClose(hSendThread);
for (TextHook *man = hookman; man->RemoveHook(); man++);
//LARGE_INTEGER lint = {-10000, -1};
while (::enter_count)
IthSleep(1); // jichi 9/28/2013: sleep for 1 ms
//NtDelayExecution(0, &lint);
for (TextHook *man = hookman; man < hookman + MAX_HOOK; man++)
man->ClearHook();
//if (ith_has_section)
NtUnmapViewOfSection(NtCurrentProcess(), hookman);
//else
// delete[] ::hookman;
NtClose(hSection);
NtClose(hMutex);
delete ::tree;
IthCloseSystemService();
NtClose(hmMutex);
NtClose(hDllExist);
//} ITH_EXCEPT {}
} break;
}
return TRUE;
}
extern "C" {
DWORD IHFAPI NewHook(const HookParam &hp, LPCWSTR name, DWORD flag)
{
//WCHAR str[0x80];
int current = current_available - hookman;
if (current < MAX_HOOK) {
//flag &= 0xffff;
//if ((flag & HOOK_AUXILIARY) == 0)
flag |= HOOK_ADDITIONAL;
//if (name == 0 || *name == 0) {
// name = str;
// swprintf(name,L"UserHook%d",user_hook_count++);
//}
hookman[current].InitHook(hp, name, flag & 0xffff);
if (hookman[current].InsertHook() == 0)
//OutputConsole(L"Additional hook inserted.");
//swprintf(str,L"Insert address 0x%.8X.", hookman[current].Address());
//OutputConsole(str);
RequestRefreshProfile();
//else
// OutputConsole(L"Unable to insert hook.");
}
return 0;
}
DWORD IHFAPI RemoveHook(DWORD addr)
{
for (int i=0; i<MAX_HOOK; i++)
if (hookman[i].Address ()== addr) {
hookman[i].ClearHook();
return 0;
}
return 0;
}
DWORD IHFAPI SwitchTrigger(DWORD t)
{
trigger = t;
return 0;
}
} // extern "C"
static int filter_count;
static DWORD recv_esp, recv_addr;
static CONTEXT recover_context;
static __declspec(naked) void MySEH()
{
__asm{
mov eax, [esp+0xC]
mov edi,eax
mov ecx,0xB3
mov esi, offset recover_context
rep movs
mov ecx, [recv_esp]
mov [eax+0xC4],ecx
mov edx, [recv_addr]
mov [eax+0xB8],edx
xor eax,eax
retn
}
}
EXCEPTION_DISPOSITION ExceptHandler(
EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
CONTEXT *ContextRecord,
void * DispatcherContext )
{
ContextRecord->Esp=recv_esp;
ContextRecord->Eip=recv_addr;
return ExceptionContinueExecution;
}
int GuardRange(LPWSTR module, DWORD* a, DWORD* b)
{
int flag=0;
__asm
{
mov eax,seh_recover
mov recv_addr,eax
push ExceptHandler
push fs:[0]
mov recv_esp,esp
mov fs:[0],esp
}
flag = FillRange(module,a,b);
__asm
{
seh_recover:
mov eax,[esp]
mov fs:[0],eax
add esp,8
}
return flag;
}
void AddRange(LPWSTR dll)
{
if (GuardRange(dll, &filter[filter_count].lower, &filter[filter_count].upper))
filter_count++;
}
void InitFilterTable()
{
filter_count = 0;
AddRange(L"uxtheme.dll");
AddRange(L"usp10.dll");
AddRange(L"msctf.dll");
AddRange(L"gdiplus.dll");
AddRange(L"lpk.dll");
AddRange(L"psapi.dll");
AddRange(L"user32.dll");
}
// EOF
| 27.297059 | 115 | 0.655964 | wareya |
8677a60aa3dc6bc75db709b630b6bb682d84f647 | 28,240 | cpp | C++ | src/connect/postgres/postgres_avro_utils.cpp | eikeschumann971/kspp | e9665f0d7fb9c976c232393428d2d3e616db7eb5 | [
"BSL-1.0"
] | 103 | 2017-01-13T11:27:52.000Z | 2022-01-22T08:30:41.000Z | src/connect/postgres/postgres_avro_utils.cpp | eikeschumann971/kspp | e9665f0d7fb9c976c232393428d2d3e616db7eb5 | [
"BSL-1.0"
] | 26 | 2017-02-16T13:26:24.000Z | 2022-03-07T18:05:58.000Z | src/connect/postgres/postgres_avro_utils.cpp | eikeschumann971/kspp | e9665f0d7fb9c976c232393428d2d3e616db7eb5 | [
"BSL-1.0"
] | 24 | 2017-05-09T03:44:28.000Z | 2022-02-04T02:40:18.000Z | #include <kspp/connect/postgres/postgres_avro_utils.h>
#include <algorithm>
#include <string>
#include <glog/logging.h>
#include <avro/Specific.hh>
#include <avro/Encoder.hh>
#include <avro/Decoder.hh>
#include <avro/Compiler.hh>
#include <avro/Schema.hh>
#include <avro/AvroSerialize.hh>
#include <boost/algorithm/string.hpp>
#include <kspp/utils/string_utils.h>
//inpiration
//http://upp-mirror.googlecode.com/svn/trunk/uppsrc/PostgreSQL/PostgreSQL.cpp
namespace kspp {
namespace pq {
std::shared_ptr<avro::Schema> schema_for_oid(Oid typid) {
std::shared_ptr<avro::Schema> value_schema;
switch ((PG_OIDS) typid) {
/* Numeric-like types */
case BOOLOID: /* boolean: 'true'/'false' */
value_schema = std::make_shared<avro::BoolSchema>();
break;
case FLOAT4OID: /* real, float4: 32-bit floating point number */
value_schema = std::make_shared<avro::FloatSchema>();
break;
case FLOAT8OID: /* double precision, float8: 64-bit floating point number */
value_schema = std::make_shared<avro::DoubleSchema>();
break;
case INT2OID: /* smallint, int2: 16-bit signed integer */
case INT4OID: /* integer, int, int4: 32-bit signed integer */
value_schema = std::make_shared<avro::IntSchema>();
break;
case INT8OID: /* bigint, int8: 64-bit signed integer */
//case CASHOID: /* money: monetary amounts, $d,ddd.cc, stored as 64-bit signed integer */
case OIDOID: /* oid: Oid is unsigned int */
//case REGPROCOID: /* regproc: RegProcedure is Oid */
case XIDOID: /* xid: TransactionId is uint32 */
case CIDOID: /* cid: CommandId is uint32 */
value_schema = std::make_shared<avro::LongSchema>();
break;
case NUMERICOID: /* numeric(p, s), decimal(p, s): arbitrary precision number */
value_schema = std::make_shared<avro::DoubleSchema>();
break;
/* Date/time types. We don't bother with abstime, reltime and tinterval (which are based
* on Unix timestamps with 1-second resolution), as they are deprecated. */
//case DATEOID: /* date: 32-bit signed integer, resolution of 1 day */
// //return schema_for_date(); not implemented YET
// value_schema = boost::make_shared<avro::Node>(avro::AVRO_STRING);
// break;
// // this is wrong...
case TIMEOID: /* time without time zone: microseconds since start of day */
value_schema = std::make_shared<avro::LongSchema>();
break;
//case TIMETZOID: /* time with time zone, timetz: time of day with time zone */
// //value_schema = schema_for_time_tz(); NOT IMPEMENTED YET
// value_schema = boost::make_shared<avro::Node>(avro::AVRO_STRING);
// break;
case TIMESTAMPOID: /* timestamp without time zone: datetime, microseconds since epoch */
value_schema = std::make_shared<avro::LongSchema>();
break;
// // return schema_for_timestamp(false);NOT IMPEMENTED YET
// value_schema = boost::make_shared<avro::Node>(avro::AVRO_STRING);
// break;
//case TIMESTAMPTZOID: /* timestamp with time zone, timestamptz: datetime with time zone */
// //return schema_for_timestamp(true); NOT IMPEMENTED YET
// value_schema = boost::make_shared<avro::Node>(avro::AVRO_STRING);
// break;
//case INTERVALOID: /* @ <number> <units>, time interval */
// //value_schema = schema_for_interval(); NOT IMPEMENTED YET
// value_schema = boost::make_shared<avro::Node>(avro::AVRO_STRING);
// break;
/* Binary string types */
case BYTEAOID: /* bytea: variable-length byte array */
value_schema = std::make_shared<avro::BytesSchema>();
break;
//case BITOID: /* fixed-length bit string */
//case VARBITOID: /* variable-length bit string */
case UUIDOID: /* UUID datatype */
value_schema = std::make_shared<avro::StringSchema>();
break;
//case LSNOID: /* PostgreSQL LSN datatype */
//case MACADDROID: /* XX:XX:XX:XX:XX:XX, MAC address */
//case INETOID: /* IP address/netmask, host address, netmask optional */
//case CIDROID: /* network IP address/netmask, network address */
/* Geometric types */
//case POINTOID: /* geometric point '(x, y)' */
//case LSEGOID: /* geometric line segment '(pt1,pt2)' */
//case PATHOID: /* geometric path '(pt1,...)' */
//case BOXOID: /* geometric box '(lower left,upper right)' */
//case POLYGONOID: /* geometric polygon '(pt1,...)' */
//case LINEOID: /* geometric line */
//case CIRCLEOID: /* geometric circle '(center,radius)' */
/* range types... decompose like array types? */
/* JSON types */
//case JSONOID: /* json: Text-based JSON */
//case JSONBOID: /* jsonb: Binary JSON */
// key value store of string type
case HSTOREOID: // got 16524 while debugging - is that the only one??
value_schema = std::make_shared<avro::MapSchema>(avro::StringSchema());
break;
case TEXT_ARRAYOID:
value_schema = std::make_shared<avro::ArraySchema>(avro::StringSchema());
break;
/* String-like types: fall through to the default, which is to create a string representation */
case CHAROID: /* "char": single character */
case NAMEOID: /* name: 63-byte type for storing system identifiers */
case TEXTOID: /* text: variable-length string, no limit specified */
//case BPCHAROID: /* character(n), char(length): blank-padded string, fixed storage length */
//case VARCHAROID: /* varchar(length): non-blank-padded string, variable storage length */
value_schema = std::make_shared<avro::StringSchema>();
break;
default:
LOG(WARNING) << "got unknown OID - mapping to string, OID=" << typid;
value_schema = std::make_shared<avro::StringSchema>();
break;
}
/* Make a union of value_schema with null. Some types are already a union,
* in which case they must include null as the first branch of the union,
* and return directly from the function without getting here (otherwise
* we'd get a union inside a union, which is not valid Avro). */
std::shared_ptr<avro::Schema> null_schema = std::make_shared<avro::NullSchema>();
std::shared_ptr<avro::UnionSchema> union_schema = std::make_shared<avro::UnionSchema>();
union_schema->addType(*null_schema);
union_schema->addType(*value_schema);
//avro_schema_decref(null_schema);
//avro_schema_decref(value_schema);
return union_schema;
}
/*std::shared_ptr<avro::ValidSchema> schema_for_table_row(std::string schema_name, const PGresult *res) {
avro::RecordSchema record_schema(schema_name);
int nFields = PQnfields(res);
for (int i = 0; i < nFields; i++) {
Oid col_type = PQftype(res, i);
std::string col_name = PQfname(res, i);
std::shared_ptr<avro::Schema> col_schema = schema_for_oid(col_type);
// TODO ensure that names abide by Avro's requirements
record_schema.addField(col_name, *col_schema);
}
auto result = std::make_shared<avro::ValidSchema>(record_schema);
return result;
}
*/
std::string simple_column_name(std::string column_name) {
std::string simple = column_name;
size_t found = simple.find_last_of('.');
if (found != std::string::npos)
simple = simple.substr(found + 1);
return simple;
}
// if we have a freeform select statement we might need to specify id and ts columns as a.id and b.ts if the fields occur in several tables
// strip this away
std::shared_ptr<avro::ValidSchema>
schema_for_table_key(std::string schema_name, const std::vector<std::string> &keys, const PGresult *res) {
avro::RecordSchema record_schema(schema_name);
for (std::vector<std::string>::const_iterator i = keys.begin(); i != keys.end(); i++) {
std::string simple_key = simple_column_name(*i);
int column_index = PQfnumber(res, simple_key.c_str());
assert(column_index >= 0);
if (column_index >= 0) {
Oid col_type = PQftype(res, column_index);
std::shared_ptr<avro::Schema> col_schema = schema_for_oid(col_type);
/* TODO ensure that names abide by Avro's requirements */
record_schema.addField(simple_key, *col_schema);
}
}
auto result = std::make_shared<avro::ValidSchema>(record_schema);
return result;
}
// std::shared_ptr<avro::ValidSchema> schema_for_table_row(std::string schema_name, const PGresult *res) {
// avro::RecordSchema record_schema(schema_name);
// int nFields = PQnfields(res);
// for (int i = 0; i < nFields; i++) {
// Oid col_oid = PQftype(res, i);
// std::string col_name = PQfname(res, i);
//
// std::shared_ptr<avro::Schema> col_schema;
//
// auto ext_item = extension_oids_.find(col_oid);
// if (ext_item != extension_oids_.end())
// col_schema = ext_item->second;
// else
// col_schema = pq::schema_for_oid(col_oid); // build in types
//
// /* TODO ensure that names abide by Avro's requirements */
// record_schema.addField(col_name, *col_schema);
// }
// auto result = std::make_shared<avro::ValidSchema>(record_schema);
// return result;
// }
// does only support build in types - we have to add a db connection object witrh the extensions to do this right
std::shared_ptr<avro::ValidSchema> schema_for_table_row(std::string schema_name, const PGresult *res) {
avro::RecordSchema record_schema(schema_name);
int nFields = PQnfields(res);
for (int i = 0; i < nFields; i++) {
Oid col_oid = PQftype(res, i);
std::string col_name = PQfname(res, i);
std::shared_ptr<avro::Schema> col_schema;
col_schema = pq::schema_for_oid(col_oid); // build in types
/* TODO ensure that names abide by Avro's requirements */
record_schema.addField(col_name, *col_schema);
}
auto result = std::make_shared<avro::ValidSchema>(record_schema);
return result;
}
class IsChars {
public:
IsChars(const char *charsToRemove) : chars(charsToRemove) {};
bool operator()(char c) {
for (const char *testChar = chars; *testChar != 0; ++testChar) {
if (*testChar == c) { return true; }
}
return false;
}
private:
const char *chars;
};
std::string avro2sql_table_name(std::shared_ptr<avro::ValidSchema> schema, avro::GenericDatum &datum) {
auto r = schema->root();
assert(r->type() == avro::AVRO_RECORD);
if (r->hasName()) {
std::string name = r->name();
//since we use convention tablename.key / table_name.value (until we know what bottledwater does...)
// return namesapace as table name
std::size_t found = name.find_first_of(".");
if (found != std::string::npos) {
std::string ns = name.substr(0, found);
return ns;
}
return r->name();
}
assert(false);
return "unknown_table_name";
}
std::string avro2sql_column_names(std::shared_ptr<avro::ValidSchema> schema, avro::GenericDatum &datum) {
auto r = schema->root();
assert(r->type() == avro::AVRO_RECORD);
std::string s = "(";
size_t sz = r->names();
for (size_t i = 0; i != sz; ++i) {
s += r->nameAt(i);
if (i != sz - 1)
s += ",";
}
s += ")";
/*
schema->toJson(std::cerr);
std::cerr << std::endl;
return "unknown";
*/
return s;
}
static Oid avro_type_to_oid(avro::Type avro_type) {
switch (avro_type) {
case avro::AVRO_STRING:
return TEXTOID;
case avro::AVRO_BYTES:
return BYTEAOID;
case avro::AVRO_INT:
return INT4OID;
case avro::AVRO_LONG:
return INT8OID;
case avro::AVRO_FLOAT:
return FLOAT4OID;
case avro::AVRO_DOUBLE:
return FLOAT8OID;
case avro::AVRO_BOOL:
return BOOLOID;
//case avro::AVRO_ARRAY: // we map arrays to a json string representation of the array eg [ 123, 123 ] or [ "nisse" ]
//return TEXTOID;
case avro::AVRO_ARRAY:
return TEXT_ARRAYOID;
case avro::AVRO_MAP:
return HSTOREOID;
case avro::AVRO_UNION:
case avro::AVRO_RECORD:
case avro::AVRO_ENUM:
case avro::AVRO_FIXED:
case avro::AVRO_NULL:
default:
LOG(FATAL) << "unsupported / non supported type e:" << avro_type;
}
return TEXTOID;
}
static std::string to_string(Oid oid) {
switch ((PG_OIDS) oid) {
case BOOLOID:
return "boolean";
case FLOAT4OID:
return "float4";
case FLOAT8OID:
return "float8";
case INT2OID:
return "smallint";
case INT4OID:
return "integer";
case INT8OID:
return "bigint";
case BYTEAOID:
return "bytea";
case CHAROID:
return "char";
case NAMEOID:
return "name";
case TEXTOID:
return "text";
case HSTOREOID:
return "hstore";
case TEXT_ARRAYOID:
return "ARRAY";
default:
LOG(FATAL) << "unsupported / non supported type e:" << oid;
break;
}
return "unsupported";
}
// this is hackish - if the column is a union type we assume that it can be null
/*static bool avro2sql_is_column_nullable(const avro::GenericDatum &column) {
auto t = column.type();
return (t == avro::AVRO_UNION);
}
*/
static std::string keys2string(std::vector<std::string> keys){
std::string s;
for (auto j : keys)
s += j + ","; // (to snanatize_pg_string...)
if (s.size())
s.pop_back();
return s;
}
std::string
avro2sql_create_table_statement(const std::string &tablename, std::vector<std::string> keys, const avro::ValidSchema &schema) {
auto root = schema.root();
assert(root->type() == avro::AVRO_RECORD);
std::string s = "CREATE TABLE " + tablename + " (\n";
size_t sz = root->names();
for (size_t i = 0; i != sz; ++i) {
auto leaf = root->leafAt(i);
// nullable or not??
if (leaf->type() == avro::AVRO_UNION) {
//auto avro_null = leaf->leafAt(0);
auto avro_val = leaf->leafAt(1);
s += root->nameAt(i) + " " + to_string(avro_type_to_oid(avro_val->type()));
} else {
s += root->nameAt(i) + " " + to_string(avro_type_to_oid(root->leafAt(i)->type())) + " NOT NULL";
}
if (i != sz - 1)
s += ",";
}
std::string key_string = keys2string(keys);
if (key_string.size())
s += ", PRIMARY KEY(" + key_string + ") ";
s += ")";
return s;
}
std::string avro2sql_build_insert_1(const std::string &tablename, const avro::ValidSchema &schema) {
auto r = schema.root();
assert(r->type() == avro::AVRO_RECORD);
std::string s = "INSERT INTO " + tablename + "(\n";
size_t sz = r->names();
for (size_t i = 0; i != sz; ++i) {
s += r->nameAt(i);
if (i != sz - 1)
s += ",";
}
s += ") VALUES\n";
return s;
}
std::string avro2sql_build_upsert_2(const std::string &tablename, const std::vector<std::string> &keys, const avro::ValidSchema &schema) {
auto r = schema.root();
assert(r->type() == avro::AVRO_RECORD);
std::string s = "ON CONFLICT (" + keys2string(keys) + ") DO UPDATE SET (\n";
size_t sz = r->names();
for (size_t i = 0; i != sz; ++i) {
s += r->nameAt(i);
if (i != sz - 1)
s += ",";
}
s += ") = \n(";
for (size_t i = 0; i != sz; ++i) {
s += "EXCLUDED." + r->nameAt(i);
if (i != sz - 1)
s += ",";
}
s += ")\n";
return s;
}
std::string escapeSQLstring(std::string src) {
//we should escape the sql string instead of doing this... - for now this removes ' characters in string
src.erase(std::remove_if(src.begin(), src.end(), IsChars("'")), src.end());
return std::string("'" + src + "'"); // we have to do real escaping here to prevent injection attacks TBD
}
// only maps simple types to value
static std::string avro_2_sql_simple_column_value(const avro::GenericDatum &column) {
auto t = column.type();
switch (t) {
// nullable columns are represented as union of NULL and value
// parse those recursive
case avro::AVRO_UNION: {
LOG(FATAL) << "avro union";
//const avro::GenericUnion &au(column.value<avro::GenericUnion>());
//return avro_2_sql_simple_column_value(au.datum());
}
case avro::AVRO_NULL:
return "NULL";
break;
case avro::AVRO_STRING: {
//auto t = column.logicalType();
std::string s = column.value<std::string>();
return escapeSQLstring(column.value<std::string>());
}
break;
case avro::AVRO_BYTES:
return column.value<std::string>();
break;
case avro::AVRO_INT:
return std::to_string(column.value<int32_t>());
break;
case avro::AVRO_LONG:
return std::to_string(column.value<int64_t>());
break;
case avro::AVRO_FLOAT:
return std::to_string(column.value<float>());
break;
case avro::AVRO_DOUBLE:
return std::to_string(column.value<double>());
break;
case avro::AVRO_BOOL:
return column.value<bool>() ? "True" : "False";
break;
case avro::AVRO_ARRAY: {
const avro::GenericArray &v = column.value<avro::GenericArray>();
const std::vector<avro::GenericDatum>&r = v.value();
if (r.size()==0)
return "'[]'";
std::vector<avro::GenericDatum>::const_iterator second_last = r.end();
--second_last;
std::string s = "[";
for (std::vector<avro::GenericDatum>::const_iterator i = r.begin(); i!=r.end(); ++i){
s += avro_2_sql_simple_column_value(*i);
if (i != second_last)
s += ", ";
}
s += "]";
return escapeSQLstring(s); // TODO - should we really eascape here - does that not mean that we kill strings in strings since they have ' chars???
}
break;
case avro::AVRO_MAP:{
const avro::GenericMap &map = column.value<avro::GenericMap>();
//const std::map<std::string, avro::GenericDatum>&r = map.value();
auto const & v = map.value();
if (v.size()==0)
return "''";
avro::GenericMap::Value::const_iterator second_last = v.end();
--second_last;
std::string s = "";
for (avro::GenericMap::Value::const_iterator i = v.begin(); i!=v.end(); ++i){
// should be '_HOSTIPMI_IP=>10.1.40.23' ie no inner ''
//s += i->first + "=>" + avro_2_sql_simple_column_value(i->second);
// this is a bit inefficient
std::string value_string = avro_2_sql_simple_column_value(i->second);
value_string.erase(std::remove_if(value_string.begin(), value_string.end(), IsChars("'")), value_string.end());
s += i->first + "=>" + value_string;
if (i != second_last)
s += ", ";
}
s += "";
return escapeSQLstring(s);
} break;
case avro::AVRO_RECORD:
case avro::AVRO_ENUM:
case avro::AVRO_FIXED:
default:
LOG(FATAL) << "unexpected / non supported type e:" << column.type();
}
}
// handles both nullable and non nullable columns
std::string avro2sql_values(const avro::ValidSchema &schema, const avro::GenericDatum &datum) {
std::string result = "(";
assert(datum.type() == avro::AVRO_RECORD);
const avro::GenericRecord &record(datum.value<avro::GenericRecord>());
size_t nFields = record.fieldCount();
for (size_t i = 0; i < nFields; i++) {
std::string val = avro_2_sql_simple_column_value(record.fieldAt(i));
if (i < (nFields - 1))
result += val + ", ";
else
result += val + ")";
}
return result;
}
// TODO multiple keys
std::string
avro2sql_key_values(const avro::ValidSchema &schema, const std::vector<std::string> &keys, const avro::GenericDatum &datum) {
assert(datum.type() == avro::AVRO_RECORD);
const avro::GenericRecord &record(datum.value<avro::GenericRecord>());
std::string result;
size_t sz = keys.size();
size_t last =sz-1;
for (size_t i=0; i!=sz; ++i) {
auto x = record.field(keys[i]);
result += avro_2_sql_simple_column_value(x);
if (i!=last)
result += ", ";
}
return result;
}
std::string avro2sql_delete_key_values(const avro::ValidSchema &schema, const std::vector<std::string> &keys,
const avro::GenericDatum &datum) {
if (datum.type() == avro::AVRO_RECORD) {
auto root = schema.root();
assert(root->type() == avro::AVRO_RECORD);
std::string result = "(";
const avro::GenericRecord &record(datum.value<avro::GenericRecord>());
size_t nFields = record.fieldCount();
for (size_t i = 0; i < nFields; i++) {
result += root->nameAt(i) + "=";
std::string val = avro_2_sql_simple_column_value(record.fieldAt(i));
if (i < (nFields - 1))
result += "=" + val + " AND ";
else
result += "=" + val + ")";
}
return result;
} else {
if (keys.size()!=1){
LOG(FATAL) << "keys size!=1 and signal value key";
}
return keys[0] + "=" + avro_2_sql_simple_column_value(datum);
}
}
/*std::vector<std::shared_ptr<avro::GenericDatum>> to_avro(std::shared_ptr<avro::ValidSchema> schema, const PGresult *res){
}
*/
void load_avro_by_name(kspp::generic_avro* avro, PGresult* pgres, size_t row)
{
// key tupe is null if there is no key
if (avro->type() == avro::AVRO_NULL)
return;
assert(avro->type() == avro::AVRO_RECORD);
avro::GenericRecord& record(avro->generic_datum()->value<avro::GenericRecord>());
size_t nFields = record.fieldCount();
for (size_t j = 0; j < nFields; j++)
{
avro::GenericDatum& col = record.fieldAt(j); // expected union
if (!record.fieldAt(j).isUnion()) // this should not hold - but we fail to create correct schemas for not null columns
{
LOG(INFO) << avro->valid_schema()->toJson();
LOG(FATAL) << "unexpected schema - bailing out, type:" << record.fieldAt(j).type();
break;
}
//avro::GenericUnion& au(record.fieldAt(j).value<avro::GenericUnion>());
const std::string& column_name = record.schema()->nameAt(j);
//which pg column has this value?
int column_index = PQfnumber(pgres, column_name.c_str());
if (column_index < 0)
{
LOG(FATAL) << "unknown column - bailing out: " << column_name;
break;
}
if (PQgetisnull(pgres, row, column_index) == 1)
{
col.selectBranch(0); // NULL branch - we hope..
assert(col.type() == avro::AVRO_NULL);
}
else
{
col.selectBranch(1);
//au.selectBranch(1);
//avro::GenericDatum& avro_item(au.datum());
const char* val = PQgetvalue(pgres, row, j);
switch (col.type()) {
case avro::AVRO_STRING:
col.value<std::string>() = val;
break;
case avro::AVRO_BYTES:
col.value<std::string>() = val;
break;
case avro::AVRO_INT:
col.value<int32_t>() = atoi(val);
break;
case avro::AVRO_LONG:
col.value<int64_t>() = std::stoull(val);
break;
case avro::AVRO_FLOAT:
col.value<float>() = (float) atof(val);
break;
case avro::AVRO_DOUBLE:
col.value<double>() = atof(val);
break;
case avro::AVRO_BOOL:
col.value<bool>() = (val[0] == 't' || val[0] == 'T' || val[0] == '1');
break;
case avro::AVRO_MAP: {
std::vector<std::string> kvs;
boost::split(kvs, val, boost::is_any_of(",")); // TODO we cannot handle "dsd,hggg" => "jhgf"
avro::GenericMap& v = col.value<avro::GenericMap>();
avro::GenericMap::Value& r = v.value();
// this is an empty string "" that will be mapped as 1 item of empty size
if (kvs.size()==1 && kvs[0].size() ==0)
break;
r.resize(kvs.size());
int cursor=0;
for(auto& i : kvs){
std::size_t found = i.find("=>");
if (found==std::string::npos)
LOG(FATAL) << "expected => in hstore";
std::string key = i.substr(0, found);
std::string val = i.substr(found +2);
pq_trim(key, "\" ");
pq_trim(val, "\" ");
r[cursor].first = key;
r[cursor].second = avro::GenericDatum(val);
++cursor;
}
}
break;
case avro::AVRO_ARRAY:{
std::vector<std::string> kvs;
std::string trimmed_val = val;
pq_trim(trimmed_val, "{ }");
boost::split(kvs, trimmed_val, boost::is_any_of(",")); // TODO we cannot handle [ "dsd,hg", ljdshf ]
avro::GenericArray& v = col.value<avro::GenericArray>();
avro::GenericArray::Value& r = v.value();
// this is an empty string "" that will be mapped as 1 item of empty size
if (kvs.size()==1 && kvs[0].size() ==0)
break;
r.resize(kvs.size());
int cursor=0;
for(auto& i : kvs) {
r[cursor] = avro::GenericDatum(i);
++cursor;
}
}
break;
case avro::AVRO_RECORD:
case avro::AVRO_ENUM:
case avro::AVRO_UNION:
case avro::AVRO_FIXED:
case avro::AVRO_NULL:
default:
LOG(FATAL) << "unexpected / non supported type e:" << col.type();
}
}
}
}
} // namespace
} // namespace | 38.737997 | 157 | 0.542918 | eikeschumann971 |
86822be5cba9b80d875a6e361f9f5c813c9a1d79 | 6,106 | cpp | C++ | src/apps/mplayerc/PPageFileInfoClip.cpp | chinajeffery/MPC-BE--1.2.3 | 2229fde5535f565ba4a496a7f73267bd2c1ad338 | [
"MIT"
] | null | null | null | src/apps/mplayerc/PPageFileInfoClip.cpp | chinajeffery/MPC-BE--1.2.3 | 2229fde5535f565ba4a496a7f73267bd2c1ad338 | [
"MIT"
] | 1 | 2019-11-14T04:18:32.000Z | 2019-11-14T04:18:32.000Z | src/apps/mplayerc/PPageFileInfoClip.cpp | chinajeffery/MPC-BE--1.2.3 | 2229fde5535f565ba4a496a7f73267bd2c1ad338 | [
"MIT"
] | null | null | null | /*
* $Id: PPageFileInfoClip.cpp 2794 2013-05-27 01:40:05Z aleksoid $
*
* (C) 2003-2006 Gabest
* (C) 2006-2013 see Authors.txt
*
* This file is part of MPC-BE.
*
* MPC-BE is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* MPC-BE 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, see <http://www.gnu.org/licenses/>.
*
*/
#include "stdafx.h"
#include "MainFrm.h"
#include "PPageFileInfoClip.h"
#include <qnetwork.h>
#include "../../DSUtil/WinAPIUtils.h"
// CPPageFileInfoClip dialog
IMPLEMENT_DYNAMIC(CPPageFileInfoClip, CPropertyPage)
CPPageFileInfoClip::CPPageFileInfoClip(CString fn, IFilterGraph* pFG)
: CPropertyPage(CPPageFileInfoClip::IDD, CPPageFileInfoClip::IDD)
, m_fn(fn)
, m_pFG(pFG)
, m_clip(ResStr(IDS_AG_NONE))
, m_author(ResStr(IDS_AG_NONE))
, m_copyright(ResStr(IDS_AG_NONE))
, m_rating(ResStr(IDS_AG_NONE))
, m_location_str(ResStr(IDS_AG_NONE))
, m_album(ResStr(IDS_AG_NONE))
, m_hIcon(NULL)
{
}
CPPageFileInfoClip::~CPPageFileInfoClip()
{
if (m_hIcon) {
DestroyIcon(m_hIcon);
}
}
BOOL CPPageFileInfoClip::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_LBUTTONDBLCLK && pMsg->hwnd == m_location.m_hWnd && !m_location_str.IsEmpty()) {
CString path = m_location_str;
if (path[path.GetLength() - 1] != '\\') {
path += _T("\\");
}
path += m_fn;
if (path.Find(_T("://")) == -1 && ExploreToFile(path)) {
return TRUE;
}
}
return __super::PreTranslateMessage(pMsg);
}
void CPPageFileInfoClip::DoDataExchange(CDataExchange* pDX)
{
__super::DoDataExchange(pDX);
DDX_Control(pDX, IDC_DEFAULTICON, m_icon);
DDX_Text(pDX, IDC_EDIT1, m_fn);
DDX_Text(pDX, IDC_EDIT4, m_clip);
DDX_Text(pDX, IDC_EDIT3, m_author);
DDX_Text(pDX, IDC_EDIT8, m_album);
DDX_Text(pDX, IDC_EDIT2, m_copyright);
DDX_Text(pDX, IDC_EDIT5, m_rating);
DDX_Control(pDX, IDC_EDIT6, m_location);
DDX_Control(pDX, IDC_EDIT7, m_desc);
}
#define SETPAGEFOCUS WM_APP+252 // arbitrary number, can be changed if necessary
BEGIN_MESSAGE_MAP(CPPageFileInfoClip, CPropertyPage)
ON_WM_SIZE()
ON_MESSAGE(SETPAGEFOCUS, OnSetPageFocus)
END_MESSAGE_MAP()
// CPPageFileInfoClip message handlers
BOOL CPPageFileInfoClip::OnInitDialog()
{
__super::OnInitDialog();
if (m_fn.IsEmpty()) {
BeginEnumFilters(m_pFG, pEF, pBF) {
CComQIPtr<IFileSourceFilter> pFSF = pBF;
if (pFSF) {
LPOLESTR pFN = NULL;
AM_MEDIA_TYPE mt;
if (SUCCEEDED(pFSF->GetCurFile(&pFN, &mt)) && pFN && *pFN) {
m_fn = CStringW(pFN);
CoTaskMemFree(pFN);
}
break;
}
}
EndEnumFilters
}
m_hIcon = LoadIcon(m_fn, false);
if (m_hIcon) {
m_icon.SetIcon(m_hIcon);
}
m_fn.TrimRight('/');
if (m_fn.Find(_T("://")) > 0) {
if (m_fn.Find(_T("/"), m_fn.Find(_T("://")) + 3) < 0) {
m_location_str = m_fn;
}
}
if (m_location_str.IsEmpty() || m_location_str == ResStr(IDS_AG_NONE)) {
int i = max(m_fn.ReverseFind('\\'), m_fn.ReverseFind('/'));
if (i >= 0 && i < m_fn.GetLength()-1) {
m_location_str = m_fn.Left(i);
m_fn = m_fn.Mid(i+1);
if (m_location_str.GetLength() == 2 && m_location_str[1] == ':') {
m_location_str += '\\';
}
}
}
m_location.SetWindowText(m_location_str);
BeginEnumFilters(m_pFG, pEF, pBF) {
if (CComQIPtr<IPropertyBag> pPB = pBF) {
CComVariant var;
if (SUCCEEDED(pPB->Read(CComBSTR(_T("ALBUM")), &var, NULL))) {
m_album = var.bstrVal;
}
}
if (CComQIPtr<IAMMediaContent, &IID_IAMMediaContent> pAMMC = pBF) {
CComBSTR bstr;
if (SUCCEEDED(pAMMC->get_Title(&bstr)) && bstr.Length()) {
m_clip = bstr.m_str;
bstr.Empty();
}
if (SUCCEEDED(pAMMC->get_AuthorName(&bstr)) && bstr.Length()) {
m_author = bstr.m_str;
bstr.Empty();
}
if (SUCCEEDED(pAMMC->get_Copyright(&bstr)) && bstr.Length()) {
m_copyright = bstr.m_str;
bstr.Empty();
}
if (SUCCEEDED(pAMMC->get_Rating(&bstr)) && bstr.Length()) {
m_rating = bstr.m_str;
bstr.Empty();
}
if (SUCCEEDED(pAMMC->get_Description(&bstr)) && bstr.Length()) {
CString desc(bstr.m_str);
desc.Replace(_T(";"), _T("\r\n"));
m_desc.SetWindowText(desc);
bstr.Empty();
}
}
}
EndEnumFilters;
CString strTitleAlt = ((CMainFrame*)AfxGetMyApp()->GetMainWnd())->m_strTitleAlt;
if (!strTitleAlt.IsEmpty()) {
m_clip = strTitleAlt.Left(strTitleAlt.GetLength() - 4);
}
CString strAuthorAlt = ((CMainFrame*)AfxGetMyApp()->GetMainWnd())->m_strAuthorAlt;
if (!strAuthorAlt.IsEmpty()) {
m_author = strAuthorAlt;
}
UpdateData(FALSE);
return TRUE;
}
BOOL CPPageFileInfoClip::OnSetActive()
{
BOOL ret = __super::OnSetActive();
PostMessage(SETPAGEFOCUS, 0, 0L);
return ret;
}
LRESULT CPPageFileInfoClip::OnSetPageFocus(WPARAM wParam, LPARAM lParam)
{
CPropertySheet* psheet = (CPropertySheet*) GetParent();
psheet->GetTabControl()->SetFocus();
return 0;
}
void CPPageFileInfoClip::OnSize(UINT nType, int cx, int cy)
{
int dx = cx - m_rCrt.Width();
int dy = cy - m_rCrt.Height();
GetClientRect(&m_rCrt);
CRect r(0, 0, 0, 0);
if (::IsWindow(m_desc.GetSafeHwnd())) {
m_desc.GetWindowRect(&r);
r.right += dx;
r.bottom += dy;
m_desc.SetWindowPos(NULL, 0, 0, r.Width(), r.Height(), SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
}
HDWP hDWP = ::BeginDeferWindowPos(1);
for (CWnd *pChild = GetWindow(GW_CHILD); pChild != NULL; pChild = pChild->GetWindow(GW_HWNDNEXT)) {
if (pChild != GetDlgItem(IDC_EDIT7) && pChild != GetDlgItem(IDC_DEFAULTICON)) {
pChild->GetWindowRect(&r);
ScreenToClient(&r);
r.right += dx;
::DeferWindowPos(hDWP, pChild->m_hWnd, NULL, 0, 0, r.Width(), r.Height(), SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
}
}
::EndDeferWindowPos(hDWP);
}
| 25.3361 | 117 | 0.679659 | chinajeffery |
86868f8fde23e03143f1b0b8b22bda835cc70e37 | 23,018 | hpp | C++ | diff.hpp | WindowsNT/mt | 9b29630aff17d33c7adb0adef21e1657b84f6b15 | [
"MIT"
] | 19 | 2019-04-11T14:51:18.000Z | 2022-03-05T13:25:24.000Z | diff.hpp | WindowsNT/mt | 9b29630aff17d33c7adb0adef21e1657b84f6b15 | [
"MIT"
] | 1 | 2018-12-14T13:42:46.000Z | 2018-12-15T09:42:21.000Z | diff.hpp | WindowsNT/mt | 9b29630aff17d33c7adb0adef21e1657b84f6b15 | [
"MIT"
] | 15 | 2019-05-05T20:20:47.000Z | 2022-03-05T13:25:27.000Z | // Diff Library
// Chourdakis Michael
#include <winsock2.h>
#include <windows.h>
#include <wininet.h>
#include <process.h>
#include <commctrl.h>
#include <stdio.h>
#include <shellapi.h>
#include <string>
#include <memory>
#include <vector>
#include <tchar.h>
#include <msrdc.h>
#include <comdef.h>
#include <atlbase.h>
#ifndef _DIFF_H
#define _DIFF_H
#pragma warning(disable: 4456)
#pragma warning(disable: 4458)
namespace DIFFLIB
{
using namespace std;
// Class to read from memory
class MemoryRdcFileReader : public IRdcFileReader
{
private:
int refNum;
const char* d;
unsigned long long datasz;
unsigned long long ptr;
public:
MemoryRdcFileReader(const char* dd,unsigned long long size)
{
d = dd;
ptr = 0;
datasz = size;
refNum = 1;
}
unsigned long long size()
{
return datasz;
}
// IUnknown
HRESULT WINAPI QueryInterface(REFIID riid,void ** object)
{
if (!object)
return E_POINTER;
*object = 0;
if (IsEqualIID(riid, IID_IUnknown)) *object = this;
if (IsEqualIID(riid, __uuidof(IRdcFileReader))) *object = this;
if (*object)
{
IUnknown* u = (IUnknown*)*object;
u->AddRef();
}
return *object ? S_OK : E_NOINTERFACE;
}
DWORD WINAPI AddRef()
{
return ++refNum;
}
DWORD WINAPI Release()
{
if (refNum == 1)
{
refNum--;
delete this;
return 0;
}
return --refNum;
}
virtual HRESULT STDMETHODCALLTYPE GetFileSize(ULONGLONG *fileSize)
{
if (!fileSize)
return E_POINTER;
*fileSize = datasz;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Read(ULONGLONG offsetFileStart,ULONG bytesToRead,ULONG *bytesActuallyRead,BYTE *buffer,BOOL *eof)
{
ptr = offsetFileStart;
unsigned long long sz = datasz;
if (offsetFileStart >= sz)
{
*bytesActuallyRead = 0;
*eof = TRUE;
return S_OK;
}
unsigned long long available = sz - offsetFileStart;
if (available >= bytesToRead)
{
*eof = FALSE;
memcpy(buffer, d + offsetFileStart, bytesToRead);
*bytesActuallyRead = bytesToRead;
ptr += bytesToRead;
}
else
{
*eof = TRUE;
memcpy(buffer, d + offsetFileStart, (size_t)available);
*bytesActuallyRead = (unsigned long)available;
ptr += available;
}
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE GetFilePosition(ULONGLONG *offsetFromStart)
{
if (!offsetFromStart)
return E_POINTER;
*offsetFromStart = ptr;
return S_OK;
}
};
// Class to read from file
class FileRdcFileReader : public IRdcFileReader
{
private:
int refNum;
HANDLE hF = 0;
void*d;
public:
FileRdcFileReader(HANDLE h)
{
hF = h;
refNum = 1;
}
virtual unsigned long long size()
{
LARGE_INTEGER li;
GetFileSizeEx(hF, &li);
return li.QuadPart;
}
// IUnknown
HRESULT WINAPI QueryInterface(REFIID riid,void ** object)
{
if (!object)
return E_POINTER;
*object = 0;
if (IsEqualIID(riid, IID_IUnknown)) *object = this;
if (IsEqualIID(riid, __uuidof(IRdcFileReader))) *object = this;
if (*object)
{
IUnknown* u = (IUnknown*)*object;
u->AddRef();
}
return *object ? S_OK : E_NOINTERFACE;
}
DWORD WINAPI AddRef()
{
return ++refNum;
}
DWORD WINAPI Release()
{
if (refNum == 1)
{
refNum--;
delete this;
return 0;
}
return --refNum;
}
virtual HRESULT STDMETHODCALLTYPE GetFileSize(ULONGLONG *fileSize)
{
if (!fileSize)
return E_POINTER;
*fileSize = size();
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Read(ULONGLONG offsetFileStart,ULONG bytesToRead,ULONG *bytesActuallyRead,BYTE *buffer,BOOL *eof)
{
LARGE_INTEGER li;
li.QuadPart = offsetFileStart;
unsigned long long sz = size();
if (offsetFileStart >= sz)
{
*bytesActuallyRead = 0;
*eof = TRUE;
return S_OK;
}
if (!SetFilePointerEx(hF, li, 0, FILE_BEGIN))
return E_FAIL;
unsigned long long available = sz - offsetFileStart;
if (available >= bytesToRead)
{
*eof = FALSE;
DWORD ba = 0;
ReadFile(hF, buffer, bytesToRead, &ba, 0);
if (bytesActuallyRead)
*bytesActuallyRead = ba;
}
else
{
*eof = TRUE;
DWORD ba = 0;
ReadFile(hF, buffer, bytesToRead, &ba, 0);
if (bytesActuallyRead)
*bytesActuallyRead = (ULONG)available;
}
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE GetFilePosition(ULONGLONG *offsetFromStart)
{
if (!offsetFromStart)
return E_POINTER;
LARGE_INTEGER li1 = { 0 };
LARGE_INTEGER li2;
SetFilePointerEx(hF, li1, &li2, FILE_CURRENT);
*offsetFromStart = li2.QuadPart;
return S_OK;
}
};
// Class to read from file
class PartialFileRdcFileReader : public IRdcFileReader
{
private:
int refNum;
unsigned long long from = 0;
unsigned long long sz = 0;
HANDLE hF = 0;
void*d;
public:
PartialFileRdcFileReader(HANDLE h,unsigned long long frm, unsigned long long siz)
{
hF = h;
from = frm;
sz = siz;
refNum = 1;
}
virtual unsigned long long size()
{
return sz;
}
// IUnknown
HRESULT WINAPI QueryInterface(REFIID riid,void ** object)
{
if (!object)
return E_POINTER;
*object = 0;
if (IsEqualIID(riid, IID_IUnknown)) *object = this;
if (IsEqualIID(riid, __uuidof(IRdcFileReader))) *object = this;
if (*object)
{
IUnknown* u = (IUnknown*)*object;
u->AddRef();
}
return *object ? S_OK : E_NOINTERFACE;
}
DWORD WINAPI AddRef()
{
return ++refNum;
}
DWORD WINAPI Release()
{
if (refNum == 1)
{
refNum--;
delete this;
return 0;
}
return --refNum;
}
virtual HRESULT STDMETHODCALLTYPE GetFileSize(ULONGLONG *fileSize)
{
if (!fileSize)
return E_POINTER;
*fileSize = size();
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Read(ULONGLONG offsetFileStart,ULONG bytesToRead,ULONG *bytesActuallyRead,BYTE *buffer,BOOL *eof)
{
LARGE_INTEGER li;
li.QuadPart = offsetFileStart + from;
unsigned long long sz = size();
if (offsetFileStart >= sz)
{
*bytesActuallyRead = 0;
*eof = TRUE;
return S_OK;
}
if (!SetFilePointerEx(hF, li, 0, FILE_BEGIN))
return E_FAIL;
unsigned long long available = sz - offsetFileStart;
if (available >= bytesToRead)
{
*eof = FALSE;
DWORD ba = 0;
ReadFile(hF, buffer, bytesToRead, &ba, 0);
if (bytesActuallyRead)
*bytesActuallyRead = ba;
}
else
{
*eof = TRUE;
DWORD ba = 0;
ReadFile(hF, buffer, bytesToRead, &ba, 0);
if (bytesActuallyRead)
*bytesActuallyRead = (ULONG)available;
}
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE GetFilePosition(ULONGLONG *offsetFromStart)
{
if (!offsetFromStart)
return E_POINTER;
LARGE_INTEGER li1 = { 0 };
LARGE_INTEGER li2;
SetFilePointerEx(hF, li1, &li2, FILE_CURRENT);
*offsetFromStart = li2.QuadPart - from;
return S_OK;
}
};
// Class to read from IStream
class StreamRdcFileReader : public IRdcFileReader
{
private:
int refNum;
CComPtr<IStream> str;
public:
StreamRdcFileReader(CComPtr<IStream> s)
{
str = s;
refNum = 1;
}
// IUnknown
HRESULT WINAPI QueryInterface(REFIID riid,void ** object)
{
if (!object)
return E_POINTER;
*object = 0;
if (IsEqualIID(riid,IID_IUnknown)) *object = this;
if (IsEqualIID(riid,__uuidof(IRdcFileReader))) *object = this;
if (*object)
{
IUnknown* u = (IUnknown*)*object;
u->AddRef();
}
return *object ? S_OK : E_NOINTERFACE;
}
DWORD WINAPI AddRef()
{
return ++refNum;
}
DWORD WINAPI Release()
{
if (refNum == 1)
{
refNum--;
delete this;
return 0;
}
return --refNum;
}
virtual HRESULT STDMETHODCALLTYPE GetFileSize(ULONGLONG *fileSize)
{
if (!fileSize || !str)
return E_POINTER;
STATSTG ss = { 0 };
HRESULT hr = str->Stat(&ss, STATFLAG_NONAME);
if (FAILED(hr))
return E_FAIL;
*fileSize = ss.cbSize.QuadPart;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Read(ULONGLONG offsetFileStart,ULONG bytesToRead,ULONG *bytesActuallyRead,BYTE *buffer,BOOL *eof)
{
if (!str)
return E_POINTER;
// Seek
LARGE_INTEGER s;
s.QuadPart = offsetFileStart;
if (FAILED(str->Seek(s, STREAM_SEEK_SET, 0)))
return E_FAIL;
HRESULT hr = str->Read(buffer, bytesToRead, bytesActuallyRead);
*eof = FALSE;
if (*bytesActuallyRead != bytesToRead)
*eof = TRUE;
return hr;
}
virtual HRESULT STDMETHODCALLTYPE GetFilePosition(ULONGLONG *offsetFromStart)
{
if (!offsetFromStart || !str)
return E_POINTER;
LARGE_INTEGER li = { 0 };
ULARGE_INTEGER ul = { 0 };
if (FAILED(str->Seek(li, STREAM_SEEK_CUR, &ul)))
return E_FAIL;
*offsetFromStart = ul.QuadPart;
return S_OK;
}
};
// Class to get a RdcFileReader from a Structured OLE file
class InputStructuredFile
{
};
// Main writer that all our functions want
class DIFFWRITER
{
public:
virtual HRESULT Write(const char*,ULONG sz) = 0;
virtual CComPtr<IRdcFileReader> GetReader(int idx = 0) = 0;
virtual HRESULT WriteMulti(vector<RdcBufferPointer*>& outs) = 0;
};
// Class to write to file
class FileDiffWriter : public DIFFWRITER
{
private:
HANDLE hF = 0;
public:
FileDiffWriter(HANDLE h)
{
hF = h;
}
virtual HRESULT Write(const char* d,ULONG sz)
{
DWORD A = 0;
if (!WriteFile(hF, d, sz, &A, 0))
return E_FAIL;
if (sz != A)
return E_FAIL;
return S_OK;
}
virtual CComPtr<IRdcFileReader> GetReader(int idx = 0)
{
CComPtr<IRdcFileReader> r;
r.Attach(new FileRdcFileReader(hF));
return r;
}
virtual HRESULT WriteMulti(vector<RdcBufferPointer*>& outs)
{
return E_NOTIMPL;
}
};
// Class to write to IStream
class StreamWriter : public DIFFWRITER
{
private:
CComPtr<IStream> str = 0;
public:
StreamWriter(CComPtr<IStream> h)
{
str = h;
}
virtual HRESULT Write(const char* d,ULONG sz)
{
if (!str)
return E_FAIL;
ULONG r = 0;
if (FAILED(str->Write(d, sz, &r)))
return E_FAIL;
if (r != sz)
return E_FAIL;
return S_OK;
}
virtual CComPtr<IRdcFileReader> GetReader(int idx = 0)
{
if (!str)
return 0;
CComPtr<IStream> s2;
str->Clone(&s2);
if (!s2)
return 0;
LARGE_INTEGER li = { 0 };
s2->Seek(li, STREAM_SEEK_SET, 0);
CComPtr<IRdcFileReader> streamreader;
streamreader.Attach(new StreamRdcFileReader(s2));
return streamreader;
}
virtual HRESULT WriteMulti(vector<RdcBufferPointer*>& outs)
{
return E_NOTIMPL;
}
};
// Class to write multiple depth signatures to structured file
class MultipleLevelFileDiffWriter : public DIFFWRITER
{
private:
HRESULT hr = S_OK;
CComPtr<IStorage> pStorage;
wstring fil;
public:
MultipleLevelFileDiffWriter(const wchar_t* f)
{
hr = StgCreateStorageEx(f, STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE, STGFMT_STORAGE, 0, 0, 0, __uuidof(IStorage), (void**)&pStorage);
if (FAILED(hr))
return;
}
virtual HRESULT Write(const char* d,ULONG sz)
{
return E_NOTIMPL;
}
virtual CComPtr<IRdcFileReader> GetReader(int idx = 0)
{
hr = 0;
if (!pStorage)
return 0;
TCHAR xu[100] = { 0 };
swprintf_s(xu, 100, L"%u", idx);
CComPtr<IStream> str;
pStorage->OpenStream(xu, 0, STGM_SHARE_EXCLUSIVE | STGM_READWRITE, 0, &str);
if (!str)
return 0;
CComPtr<IRdcFileReader> streamreader;
streamreader.Attach(new StreamRdcFileReader(str));
return streamreader;
}
virtual HRESULT WriteMulti(vector<RdcBufferPointer*>& outs)
{
hr = 0;
if (!pStorage)
return E_FAIL;
// These are the levels of storage
for (unsigned int i = 0; i < outs.size(); i++)
{
auto& p = outs[i];
TCHAR xu[100] = { 0 };
swprintf_s(xu, 100, L"%u", i);
CComPtr<IStream> str;
hr = pStorage->OpenStream(xu, 0, STGM_SHARE_EXCLUSIVE | STGM_READWRITE, 0, &str);
if (!str)
// Create it...
hr = pStorage->CreateStream(xu, STGM_SHARE_EXCLUSIVE | STGM_READWRITE, 0, 0, &str);
if (!str)
return E_FAIL;
// Go to end of this stream
LARGE_INTEGER li = { 0 };
str->Seek(li, STREAM_SEEK_END, 0);
ULONG cb = 0;
hr = str->Write(p->m_Data, p->m_Used, &cb);
if (cb != p->m_Used)
return E_FAIL;
}
return S_OK;
}
};
// Class to write to memory
class MemoryDiffWriter : public DIFFWRITER
{
private:
vector<char> d;
public:
vector<char>& p()
{
return d;
}
size_t sz()
{
return d.size();
}
HRESULT Write(const char* dd,ULONG sz)
{
if (!dd)
return E_INVALIDARG;
size_t c = d.size();
d.resize(c + sz);
memcpy(d.data() + c, dd, sz);
return S_OK;
}
virtual CComPtr<IRdcFileReader> GetReader(int idx = 0)
{
CComPtr<IRdcFileReader> rdr;
rdr.Attach(new MemoryRdcFileReader((const char*)d.data(), d.size()));
return rdr;
}
virtual HRESULT WriteMulti(vector<RdcBufferPointer*>& outs)
{
return E_NOTIMPL;
}
};
// Main class
class DIFF
{
private:
HRESULT hr;
CComPtr<IRdcLibrary> pRdcLibrary = 0;
public:
CComPtr<IRdcLibrary> GetLib() { return pRdcLibrary; }
DIFF()
{
// Load the RdcLibrary
hr = pRdcLibrary.CoCreateInstance(__uuidof(RdcLibrary));
if (FAILED(hr))
{
MessageBox(0, L"DiffLib not available", 0, 0);
DebugBreak();
throw(hr);
}
}
HRESULT GenerateSignature(IRdcFileReader* r1,DIFFWRITER& sig)
{
HRESULT hr = 0;
if (!r1)
return E_INVALIDARG;
// Create Generator Parameters
CComPtr<IRdcGeneratorParameters> params = 0;
hr = pRdcLibrary->CreateGeneratorParameters(RDCGENTYPE_FilterMax, MSRDC_MINIMUM_DEPTH, ¶ms);
if (FAILED(hr)) return hr;
CComPtr<IRdcGenerator> gen = 0;
IRdcGeneratorParameters* p2 = params; // Guess the next function needs a raw COM interface :)
hr = pRdcLibrary->CreateGenerator(MSRDC_MINIMUM_DEPTH, &p2, &gen);
if (FAILED(hr)) return hr;
// CComQIPtr<IRdcSimilarityGenerator> sim;
// sim = gen;
// hr = sim->EnableSimilarity();
// Generate the signatures
const ULONGLONG sz = 10000;
char buff[sz] = { 0 };
ULONGLONG read = 0;
vector<char> Signature;
for (;;)
{
ULONGLONG fs = 0;
r1->GetFileSize(&fs);
ULONGLONG cur = fs - read;
bool EndOfInput = true;
if (cur > sz)
{
cur = sz;
EndOfInput = false;
}
BOOL EndOfOutput = 0;
RDC_ErrorCode rerr;
RdcBufferPointer rbp;
rbp.m_Size = (ULONG)cur;
rbp.m_Data = (BYTE*)buff;
BOOL eof = 0;
ULONG actual = 0;
r1->Read(read, (ULONG)cur, &actual, (BYTE*)buff, &eof);
if (actual != cur)
return E_FAIL;
rbp.m_Used = 0;
vector<char> OutputBuffer(sz);
RdcBufferPointer outx = { 0 };
outx.m_Data = (BYTE*)OutputBuffer.data();
outx.m_Size = (ULONG)sz;
RdcBufferPointer* outputPointers = 0;
outputPointers = &outx;
hr = gen->Process(EndOfInput, &EndOfOutput, &rbp, MSRDC_MINIMUM_DEPTH, &outputPointers, &rerr);
if (FAILED(hr))
return hr;
read += rbp.m_Used;
// Append the siganture
if (outx.m_Used)
{
if (FAILED(sig.Write((const char*)outx.m_Data, outx.m_Used)))
return E_FAIL;
}
if (EndOfOutput)
break;
}
// CComQIPtr<ISimilarity> simi;
// simi.CoCreateInstance(__uuidof(ISimilarity));
return S_OK;
}
HRESULT GenerateMultiDepthSignature(IRdcFileReader* r1,ULONG de,DIFFWRITER& sig)
{
HRESULT hr = 0;
if (!r1)
return E_INVALIDARG;
ULONG fd = de - MSRDC_MINIMUM_DEPTH + 1;
// Create Generator Parameters
vector<CComPtr<IRdcGeneratorParameters>> params;
for (ULONG d = 0; d < de; d++)
{
CComPtr<IRdcGeneratorParameters> p2;
hr = pRdcLibrary->CreateGeneratorParameters(RDCGENTYPE_FilterMax, d + MSRDC_MINIMUM_DEPTH, &p2);
if (FAILED(hr))
return hr;
params.push_back(p2);
}
CComPtr<IRdcGenerator> gen = 0;
vector<IRdcGeneratorParameters*> p2(fd);
for (ULONG d = 0; d < de; d++)
p2[d] = params[d].operator->();
hr = pRdcLibrary->CreateGenerator(de, p2.data(), &gen);
if (FAILED(hr)) return hr;
// Generate the signatures
const ULONGLONG sz = 10000;
char buff[sz] = { 0 };
ULONGLONG read = 0;
vector<char> Signature;
for (;;)
{
ULONGLONG fs = 0;
r1->GetFileSize(&fs);
ULONGLONG cur = fs - read;
bool EndOfInput = true;
if (cur > sz)
{
cur = sz;
EndOfInput = false;
}
BOOL EndOfOutput = 0;
RDC_ErrorCode rerr;
RdcBufferPointer rbp;
rbp.m_Size = (ULONG)cur;
rbp.m_Data = (BYTE*)buff;
BOOL eof = 0;
ULONG actual = 0;
r1->Read(read, (ULONG)cur, &actual, (BYTE*)buff, &eof);
if (actual != cur)
return E_FAIL;
rbp.m_Used = 0;
vector<vector<char>> OutputBuffer(fd);
vector<RdcBufferPointer> outputPointers(fd);
for (ULONG d = 0; d < de; d++)
{
OutputBuffer[d].resize(sz);
outputPointers[d].m_Data = (BYTE*)OutputBuffer[d].data();
outputPointers[d].m_Size = (ULONG)sz;
}
vector<RdcBufferPointer*> outs(fd);
for (ULONG d = 0; d < de; d++)
outs[d] = &outputPointers[d];
hr = gen->Process(EndOfInput, &EndOfOutput, &rbp, de, outs.data(), &rerr);
if (FAILED(hr))
return hr;
read += rbp.m_Used;
if (FAILED(sig.WriteMulti(outs)))
return E_FAIL;
if (EndOfOutput)
break;
}
return S_OK;
}
// HRESULT GenerateMultipleLevelDiff(IRdcFileReader* first_sig,IRdcFileReader* second_sig,IRdcFileReader* r2,DIFFWRITER& diff)
HRESULT GenerateDiff(IRdcFileReader* first_sig,IRdcFileReader* second_sig,IRdcFileReader* r2,DIFFWRITER& diff)
{
// Create the signature reader
ULONGLONG firstsz = 0;
first_sig->GetFileSize(&firstsz);
CComPtr<IRdcComparator> pRdcComparator = 0;
hr = pRdcLibrary->CreateComparator(first_sig, MSRDC_DEFAULT_COMPAREBUFFER, &pRdcComparator);
if (FAILED(hr))
return hr;
const ULONGLONG sz = 10000;
vector<char> buff(sz);
ULONGLONG read = 0;
bool EndOfInput = false;
for (;;)
{
ULONGLONG fs = 0;
second_sig->GetFileSize(&fs);
ULONGLONG cur = fs - read;
if (cur == 0)
break;
if (cur > sz)
cur = sz;
else
EndOfInput = true;
BOOL EndOfOutput = 0;
RDC_ErrorCode rerr;
RdcBufferPointer rbp = { 0 };
rbp.m_Size = (ULONG)cur;
// (second_sig.data() + read);
ULONG a = 0;
BOOL eof = 0;
if (FAILED(second_sig->Read(read, (ULONG)cur, &a, (BYTE*)buff.data(), &eof)))
return E_FAIL;
if (a != cur)
return E_FAIL;
rbp.m_Data = (BYTE*)buff.data();
rbp.m_Used = 0;
int nArr = 16384;
vector<RdcNeed> needsArray(nArr);
RdcNeedPointer rnp;
rnp.m_Data = needsArray.data();
rnp.m_Size = nArr;
rnp.m_Used = 0;
EndOfOutput = 0;
for (;;)
{
hr = pRdcComparator->Process(EndOfInput, &EndOfOutput, &rbp, &rnp, &rerr);
if (FAILED(hr))
return hr;
read += rbp.m_Used;
if (rnp.m_Used == 0)
break;
for (unsigned int ir = 0; ir < rnp.m_Used; ir++)
{
RdcNeed& rn = needsArray[ir];
// copy it to diff
if (FAILED(diff.Write((const char*)&rn, sizeof(rn))))
return E_FAIL;
if (rn.m_BlockType == RDCNEED_SOURCE)
{
if (r2)
{
std::unique_ptr<char> bu(new char[(size_t)rn.m_BlockLength]);
BOOL eof = 0;
ULONG a = 0;
if (FAILED(r2->Read(rn.m_FileOffset, (ULONG)rn.m_BlockLength, &a, (BYTE*)bu.get(), &eof)))
return E_FAIL;
if (rn.m_BlockLength != a)
return E_FAIL;
if (FAILED(diff.Write(bu.get(), (ULONG)rn.m_BlockLength)))
return E_FAIL;
}
}
}
if (EndOfOutput)
break;
EndOfOutput = 0;
rnp.m_Data = needsArray.data();
rnp.m_Size = nArr;
rnp.m_Used = 0;
cur = 0;
// rbp.m_Size = 0;
// rbp.m_Data = 0;
rbp.m_Size = rbp.m_Size - rbp.m_Used;
rbp.m_Used = 0;
}
}
return S_OK;
}
HRESULT Reconstruct(IRdcFileReader* r1,IRdcFileReader* diff,IRdcFileReader* r2,DIFFWRITER& reco)
{
if (!r1)
return E_INVALIDARG;
unsigned long long diffsize = 0;
diff->GetFileSize(&diffsize);
for (unsigned long long ii = 0; ii < diffsize;)
{
//Read RdcNeed
RdcNeed rn;
rn.m_BlockLength = 0;
rn.m_BlockType = RDCNEED_SOURCE;
rn.m_FileOffset = 0;
ULONG act = 0;
BOOL eof = 0;
if (FAILED(diff->Read(ii, sizeof(rn), &act, (BYTE*)&rn, &eof)))
return E_FAIL;
if (act != sizeof(rn))
return E_FAIL;
if (rn.m_BlockType == RDCNEED_SEED)
{
BOOL eof = 0;
ULONG a = 0;
std::unique_ptr<char> bu(new char[(size_t)rn.m_BlockLength]);
if (FAILED(r1->Read(rn.m_FileOffset, (ULONG)rn.m_BlockLength, &a, (BYTE*)bu.get(), &eof)))
return E_FAIL;
if (rn.m_BlockLength != a)
return E_FAIL;
if (FAILED(reco.Write(bu.get(), (ULONG)rn.m_BlockLength)))
return E_FAIL;
ii += sizeof(RdcNeed);
continue;
}
if (rn.m_BlockType == RDCNEED_SOURCE)
{
// Copy from remote
ii += sizeof(RdcNeed);
if (!r2)
{
BOOL eof = 0;
ULONG a = 0;
std::unique_ptr<char> bu(new char[(size_t)rn.m_BlockLength]);
if (FAILED(diff->Read(ii, (ULONG)rn.m_BlockLength, &a, (BYTE*)bu.get(), &eof)))
return E_FAIL;
if (rn.m_BlockLength != a)
return E_FAIL;
if (FAILED(reco.Write(bu.get(), (ULONG)rn.m_BlockLength)))
return E_FAIL;
ii += rn.m_BlockLength;
}
else
{
std::unique_ptr<char> bu(new char[(size_t)rn.m_BlockLength]);
DWORD a = 0;
BOOL eof = 0;
if (FAILED(r2->Read(rn.m_FileOffset, (ULONG)rn.m_BlockLength, &a, (BYTE*)bu.get(), &eof)))
return E_FAIL;
if (rn.m_BlockLength != a)
return E_FAIL;
if (FAILED(reco.Write(bu.get(), (ULONG)rn.m_BlockLength)))
return E_FAIL;
}
}
}
return S_OK;
}
};
};
#endif // _DIFF_H | 21.43203 | 148 | 0.596881 | WindowsNT |
868878341f16e8471bce3ea9efa7c5293af18512 | 2,058 | cpp | C++ | controller_manager/test/test_components/test_sensor.cpp | ckenwood/ros2_control | 7f879d7fed6905d7d59acf792d24d021d30ec8ba | [
"Apache-2.0"
] | null | null | null | controller_manager/test/test_components/test_sensor.cpp | ckenwood/ros2_control | 7f879d7fed6905d7d59acf792d24d021d30ec8ba | [
"Apache-2.0"
] | null | null | null | controller_manager/test/test_components/test_sensor.cpp | ckenwood/ros2_control | 7f879d7fed6905d7d59acf792d24d021d30ec8ba | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 ros2_control Development Team
//
// 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 <memory>
#include <vector>
#include "hardware_interface/components/sensor_interface.hpp"
using hardware_interface::status;
using hardware_interface::return_type;
using hardware_interface::StateInterface;
class TestSensor : public hardware_interface::components::SensorInterface
{
return_type configure(const hardware_interface::HardwareInfo & sensor_info) override
{
sensor_info_ = sensor_info;
// can only give feedback state for velocity
if (sensor_info_.sensors[0].state_interfaces.size() != 1) {return return_type::ERROR;}
return return_type::OK;
}
std::vector<StateInterface> export_state_interfaces() override
{
std::vector<StateInterface> state_interfaces;
state_interfaces.emplace_back(
hardware_interface::StateInterface(
sensor_info_.sensors[0].name,
sensor_info_.sensors[0].state_interfaces[0].name,
&velocity_state_));
return state_interfaces;
}
return_type start() override
{
return return_type::OK;
}
return_type stop() override
{
return return_type::OK;
}
status get_status() const override
{
return status::UNKNOWN;
}
return_type read() override
{
return return_type::OK;
}
private:
double velocity_state_ = 0.0;
hardware_interface::HardwareInfo sensor_info_;
};
#include "pluginlib/class_list_macros.hpp" // NOLINT
PLUGINLIB_EXPORT_CLASS(TestSensor, hardware_interface::components::SensorInterface)
| 28.191781 | 90 | 0.74587 | ckenwood |
869704f5940f2c079bccbdffc9dcc44a23ae2423 | 4,875 | cpp | C++ | Project1/Main.cpp | TheTastyGravy/Double-Linked-List | 2b34bd750dd39a3e901bb232b17d9b7e8c89f93b | [
"MIT"
] | null | null | null | Project1/Main.cpp | TheTastyGravy/Double-Linked-List | 2b34bd750dd39a3e901bb232b17d9b7e8c89f93b | [
"MIT"
] | null | null | null | Project1/Main.cpp | TheTastyGravy/Double-Linked-List | 2b34bd750dd39a3e901bb232b17d9b7e8c89f93b | [
"MIT"
] | null | null | null | #include "raylib.h"
#include "DLList.h"
#include "ButtonClass.h"
#include "TextboxClass.h"
// A more general purpose function. PosX is the center, not left side
void drawTextNew(std::string text, int posX, int posY, int fontSize = 15, Color color = BLACK);
// Draw the lables and values of the current and adjasent nodes
void drawNodeValues(DLListNode* node);
int main()
{
const int SCREEN_WIDTH = 800;
const int SCREEN_HIGHT = 450;
InitWindow(SCREEN_WIDTH, SCREEN_HIGHT, "Double-Linked List demo");
SetTargetFPS(60);
// The list of data, and the current node
DLList list;
DLListNode* current = nullptr;
// Used to get input for new node values
TextboxClass textBox(Rectangle{ 325, 350, 150, 50 }, 9, 23);
// Navigation buttons
ButtonClass goToFirstBtn(Rectangle{ 25, 50, 100, 30 }, "go to first", 15);
ButtonClass goToLastBtn(Rectangle{ 675, 50, 100, 30 }, "go to last", 15);
ButtonClass previousBtn(Rectangle{ 150, 50, 100, 30 }, "previous", 15);
ButtonClass nextBtn(Rectangle{ 550, 50, 100, 30 }, "next", 15);
// Add and remove buttons
ButtonClass delFirstBtn(Rectangle{ 125, 200, 150, 30 }, "delete first", 15);
ButtonClass delLastBtn(Rectangle{ 525, 200, 150, 30 }, "delete last", 15);
ButtonClass delCurrentBtn(Rectangle{ 325, 200, 150, 30 }, "delete current", 15);
ButtonClass addFirstBtn(Rectangle{ 125, 250, 150, 30 }, "add to start", 15);
ButtonClass addLastBtn(Rectangle{ 525, 250, 150, 30 }, "add to end", 15);
ButtonClass addCurrentBtn(Rectangle{ 325, 250, 150, 30 }, "insert at current", 15);
// Sort button
ButtonClass sortBtn(Rectangle{ 350, 50, 100, 30 }, "sort", 15);
// Game loop
while (!WindowShouldClose())
{
// Get input for textbox
textBox.update();
// First and last buttons
if (goToFirstBtn.isClicked())
current = list.getFirst();
else if (goToLastBtn.isClicked())
current = list.getLast();
// Previous and next buttons
if (current != nullptr)
{
if (previousBtn.isClicked() && current->previous != nullptr)
current = current->previous;
else if (nextBtn.isClicked() && current->next != nullptr)
current = current->next;
}
// Delete buttons
// Note: Where current is also first, it will be removed and current is left as
// a dangling pointer, not a null pointer. To get around this, current is set
// to a null pointer every time a node is deleted.
if (delFirstBtn.isClicked())
{
list.popFront();
current = nullptr;
}
else if (delLastBtn.isClicked())
{
list.popEnd();
current = nullptr;
}
else if (delCurrentBtn.isClicked())
{
list.removeFromList(current);
delete current;
current = nullptr;
}
// Add buttons. There must be text to create a node
if (!textBox.isEmpty())
{
if (addFirstBtn.isClicked())
list.pushFront(std::stoi(textBox.getTextAndClear()));
if (addLastBtn.isClicked())
list.pushEnd(std::stoi(textBox.getTextAndClear()));
if (addCurrentBtn.isClicked() && current != nullptr)
list.insert(std::stoi(textBox.getTextAndClear()), current);
}
// Sort button. List cant be empty when sort
if (sortBtn.isClicked() && !list.isEmpty())
{
list.sort();
// Current may have been moved, in which case it is now dangling
current = nullptr;
}
// Draw to screen
BeginDrawing();
ClearBackground(RAYWHITE);
// Display list values
drawNodeValues(current);
// Display the lists size and if it's empty
drawTextNew("Size: " + std::to_string(list.count()), 200, 20, 20);
std::string res = list.isEmpty() ? "Yes" : "No";
drawTextNew("Is empty? " + res, 600, 20, 20);
// Display the input text box
drawTextNew("Value:", 400, 320, 20);
textBox.draw();
// Display buttons
goToFirstBtn.draw();
goToLastBtn.draw();
previousBtn.draw();
nextBtn.draw();
delFirstBtn.draw();
delLastBtn.draw();
delCurrentBtn.draw();
addFirstBtn.draw();
addLastBtn.draw();
addCurrentBtn.draw();
sortBtn.draw();
EndDrawing();
}
CloseWindow();
return 0;
}
void drawTextNew(std::string text, int posX, int posY, int fontSize, Color color)
{
DrawText(text.c_str(), posX - MeasureText(text.c_str(), fontSize) / 2, posY, fontSize, color);
}
void drawNodeValues(DLListNode* node)
{
drawTextNew("Previous:", 100, 100, 17);
drawTextNew("Current:", 400, 100, 17);
drawTextNew("Next:", 700, 100, 17);
// If current is null, the other two dont exist
if (node == nullptr)
{
drawTextNew("NA", 100, 125, 30);
drawTextNew("nullptr", 400, 125, 30);
drawTextNew("NA", 700, 125, 30);
}
else
{
// Check if the adjasent nodes are nullptrs
drawTextNew( (node->previous == nullptr) ?
"nullptr" : std::to_string(node->previous->value),
100, 125, 30);
drawTextNew( std::to_string(node->value), 400, 125, 30);
drawTextNew( (node->next == nullptr) ?
"nullptr" : std::to_string(node->next->value),
700, 125, 30);
}
} | 27.38764 | 95 | 0.669538 | TheTastyGravy |
86989cf38d7075b97ace64e9b4d62e5dd10547d4 | 8,363 | cpp | C++ | source/plugin/after_effects/win/ui.cpp | GregBakker/adobe-cc-codec-foundation | 302805206994c45675b77e4a8b137bdd487ae080 | [
"BSD-2-Clause"
] | 1 | 2019-09-07T12:50:20.000Z | 2019-09-07T12:50:20.000Z | source/plugin/after_effects/win/ui.cpp | codec-foundation/adobe-cc | 302805206994c45675b77e4a8b137bdd487ae080 | [
"BSD-2-Clause"
] | 10 | 2019-10-10T00:49:03.000Z | 2020-07-10T10:42:46.000Z | source/plugin/after_effects/win/ui.cpp | codec-foundation/adobe-cc | 302805206994c45675b77e4a8b137bdd487ae080 | [
"BSD-2-Clause"
] | 1 | 2019-09-04T17:01:45.000Z | 2019-09-04T17:01:45.000Z | #include "../ui.h"
#include <stdint.h>
#include <vector>
#include <Windows.h>
#include "codec_registration.hpp"
// dialog comtrols
enum : int32_t {
OUT_noUI = -1,
OUT_OK = IDOK,
OUT_Cancel = IDCANCEL,
OUT_SubTypes_Menu = 3,
OUT_SubTypes_Label = 4,
OUT_Quality_Menu = 5,
OUT_Quality_Label = 6,
OUT_ChunkCount_Menu = 7,
OUT_ChunkCount_Label = 8
};
// globals
HINSTANCE hDllInstance = NULL;
static WORD g_item_clicked = 0;
static LRESULT g_SubType = 0;
static LRESULT g_Quality = 0;
static LRESULT g_ChunkCount = 0;
static BOOL CALLBACK DialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
do{
const auto& codec = *CodecRegistry::codec();
{
HWND menu = GetDlgItem(hwndDlg, OUT_SubTypes_Menu);
bool hasSubTypes(codec.details().subtypes.size() > 0);
if (hasSubTypes) {
// set up the menu
auto subTypes = codec.details().subtypes;
auto subType = subTypes.begin();
for (int i = 0; i < subTypes.size(); ++i, ++subType)
{
SendMessage(menu, (UINT)CB_ADDSTRING, (WPARAM)wParam, (LPARAM)(LPCTSTR)subType->second.c_str());
DWORD subTypeVal = reinterpret_cast<DWORD&>(subType->first);
SendMessage(menu, (UINT)CB_SETITEMDATA, (WPARAM)i, (LPARAM)subTypeVal); // subtype fourcc
if (subTypeVal == g_SubType)
SendMessage(menu, CB_SETCURSEL, (WPARAM)i, (LPARAM)0);
}
}
else
{
// do not show subtypes item or label
ShowWindow(menu, SW_HIDE);
HWND label = GetDlgItem(hwndDlg, OUT_SubTypes_Label);
ShowWindow(label, SW_HIDE);
}
}
{
HWND menu = GetDlgItem(hwndDlg, OUT_Quality_Menu);
if (codec.details().quality.hasQualityForAnySubType)
{
// set up the menu
auto qualities = codec.details().quality.descriptions;
auto quality = qualities.begin();
for (int i = 0; i < qualities.size(); ++i, ++quality)
{
SendMessage(menu, (UINT)CB_ADDSTRING, (WPARAM)wParam, (LPARAM)(LPCTSTR)quality->second.c_str());
SendMessage(menu, (UINT)CB_SETITEMDATA, (WPARAM)i, (LPARAM)(DWORD)quality->first); // this is the quality enum
if (quality->first == g_Quality)
SendMessage(menu, CB_SETCURSEL, (WPARAM)i, (LPARAM)0);
}
// enable / disable depending upon selected codec subtype
auto enabledForSelectedCodecSubtype = codec.details().hasQualityForSubType(reinterpret_cast<Codec4CC&>(g_SubType));
EnableWindow( menu, enabledForSelectedCodecSubtype ? TRUE : FALSE );
}
else
{
// do not show qualities item
ShowWindow(menu, SW_HIDE);
}
}
{
HWND menu = GetDlgItem(hwndDlg, OUT_ChunkCount_Menu);
if (codec.details().hasChunkCount)
{
// set up the menu
auto descriptions = std::array<std::pair<int, std::string>, 9>{
{ {0, "Auto"}, {1, "1"}, {2, "2"}, { 3, "3"}, { 4, "4"},
{ 5, "5"}, { 6, "6"}, { 7, "7" }, { 8, "8" }
} };
auto description = descriptions.begin();
for (int i = 0; i < descriptions.size(); ++i, ++description)
{
SendMessage(menu, (UINT)CB_ADDSTRING, (WPARAM)wParam, (LPARAM)(LPCTSTR)description->second.c_str());
SendMessage(menu, (UINT)CB_SETITEMDATA, (WPARAM)i, (LPARAM)(DWORD)description->first);
if (description->first == g_ChunkCount) {
SendMessage(menu, CB_SETCURSEL, (WPARAM)i, (LPARAM)0);
}
}
}
else
{
// do not show qualities item
ShowWindow(menu, SW_HIDE);
HWND label = GetDlgItem(hwndDlg, OUT_ChunkCount_Label);
ShowWindow(label, SW_HIDE);
}
}
} while(0);
return TRUE;
case WM_COMMAND:
g_item_clicked = LOWORD(wParam);
switch (LOWORD(wParam))
{
case OUT_OK:
case OUT_Cancel: // do the same thing, but g_item_clicked will be different
do{
// subType
const auto& codec = *CodecRegistry::codec();
bool hasSubTypes(codec.details().subtypes.size() > 0);
if (hasSubTypes) {
HWND menu = GetDlgItem(hwndDlg, OUT_SubTypes_Menu);
LRESULT cur_sel = SendMessage(menu, (UINT)CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
g_SubType = SendMessage(menu, (UINT)CB_GETITEMDATA, (WPARAM)cur_sel, (LPARAM)0);
}
// quality
if (codec.details().quality.hasQualityForAnySubType)
{
HWND menu = GetDlgItem(hwndDlg, OUT_Quality_Menu);
// get the channel index associated with the selected menu item
LRESULT cur_sel = SendMessage(menu, (UINT)CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
g_Quality = SendMessage(menu, (UINT)CB_GETITEMDATA, (WPARAM)cur_sel, (LPARAM)0);
}
// chunk count
if (codec.details().hasChunkCount)
{
HWND menu = GetDlgItem(hwndDlg, OUT_ChunkCount_Menu);
LRESULT cur_sel = SendMessage(menu, (UINT)CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
g_ChunkCount = SendMessage(menu, (UINT)CB_GETITEMDATA, (WPARAM)cur_sel, (LPARAM)0);
}
}while(0);
//PostMessage((HWND)hwndDlg, WM_QUIT, (WPARAM)WA_ACTIVE, lParam);
EndDialog(hwndDlg, 0);
//DestroyWindow(hwndDlg);
return TRUE;
}
}
return FALSE;
}
bool
ui_OutDialog(Codec4CC& subType, int& quality, int &chunkCount, void *platformSpecific)
{
// set globals
g_SubType = reinterpret_cast<DWORD&>(subType);
g_Quality = quality;
g_ChunkCount = chunkCount;
// do dialog
HWND* hwndOwner = (HWND *)platformSpecific;
DialogBox(hDllInstance, (LPSTR)"OUTDIALOG", *hwndOwner, (DLGPROC)DialogProc);
if(g_item_clicked == OUT_OK)
{
const auto& codec = *CodecRegistry::codec();
bool hasSubTypes = (codec.details().subtypes.size() > 0);
if (hasSubTypes)
subType = reinterpret_cast<Codec4CC&>(g_SubType);
if (codec.details().quality.hasQualityForAnySubType)
quality = (int)g_Quality;
if (codec.details().hasChunkCount)
chunkCount = (int)g_ChunkCount;
return true;
}
else
return false;
}
BOOL WINAPI DllMain(HANDLE hInstance, DWORD fdwReason, LPVOID lpReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
hDllInstance = (HINSTANCE)hInstance;
return TRUE; // Indicate that the DLL was initialized successfully.
}
| 38.362385 | 140 | 0.478895 | GregBakker |
869dad075b438fe3daeae7b77aaa6419d1060268 | 2,114 | hpp | C++ | query_optimizer/LogicalToPhysicalMapper.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | query_optimizer/LogicalToPhysicalMapper.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | query_optimizer/LogicalToPhysicalMapper.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.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 QUICKSTEP_QUERY_OPTIMIZER_LOGICAL_TO_PHYSICAL_MAPPER_HPP_
#define QUICKSTEP_QUERY_OPTIMIZER_LOGICAL_TO_PHYSICAL_MAPPER_HPP_
#include "query_optimizer/logical/Logical.hpp"
#include "query_optimizer/physical/Physical.hpp"
#include "utility/Macros.hpp"
namespace quickstep {
namespace optimizer {
/** \addtogroup QueryOptimizer
* @{
*/
/**
* @brief Abstract base class for PhysicalGenerator that provides a single
* method needed by Strategy objects. This class exists to resolve a
* cyclic dependency between PhysicalGenerator and the various
* subclasses of Strategy.
**/
class LogicalToPhysicalMapper {
public:
virtual ~LogicalToPhysicalMapper() {
}
/**
* @brief Returns the physical plan for \p logical_plan.
* Creates the physical plan if it is not yet created.
*
* @param logical_plan The input logical plan.
* @return The physical plan for the logical plan.
*/
virtual physical::PhysicalPtr createOrGetPhysicalFromLogical(
const logical::LogicalPtr &logical_plan) = 0;
protected:
LogicalToPhysicalMapper() {
}
private:
DISALLOW_COPY_AND_ASSIGN(LogicalToPhysicalMapper);
};
/** @} */
} // namespace optimizer
} // namespace quickstep
#endif // QUICKSTEP_QUERY_OPTIMIZER_LOGICAL_TO_PHYSICAL_MAPPER_HPP_
| 30.637681 | 75 | 0.747871 | Hacker0912 |
86a4c62482bd3440ff9342598c267d0afe4baf07 | 36,082 | cpp | C++ | source/LibFgBase/src/FgCmdMeshops.cpp | MikhailGorobets/FaceGenBaseLibrary | 3ea688f9e3811943adb18e23e7bb2addc5f688a5 | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgCmdMeshops.cpp | MikhailGorobets/FaceGenBaseLibrary | 3ea688f9e3811943adb18e23e7bb2addc5f688a5 | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgCmdMeshops.cpp | MikhailGorobets/FaceGenBaseLibrary | 3ea688f9e3811943adb18e23e7bb2addc5f688a5 | [
"MIT"
] | 1 | 2020-05-27T17:23:50.000Z | 2020-05-27T17:23:50.000Z | //
// Coypright (c) 2020 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
#include "stdafx.h"
#include "FgCommand.hpp"
#include "FgSyntax.hpp"
#include "Fg3dMeshIo.hpp"
#include "Fg3dMeshOps.hpp"
#include "FgGeometry.hpp"
#include "FgMetaFormat.hpp"
#include "Fg3dNormals.hpp"
#include "FgSimilarity.hpp"
#include "Fg3dTopology.hpp"
#include "Fg3dDisplay.hpp"
#include "FgBestN.hpp"
using namespace std;
namespace Fg {
namespace {
void
combinesurfs(CLArgs const & args)
{
Syntax syn(args,
"(<mesh>.<extIn>)+ <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription() + "\n"
" All input meshes must have identical vertex lists.\n"
);
Mesh mesh = loadMesh(syn.next());
while (syn.more()) {
string name = syn.next();
if (syn.more()) {
Mesh next = loadMesh(name);
cat_(mesh.surfaces,next.surfaces);
}
else
saveMesh(mesh,name);
}
}
void
convert(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
saveMesh(mesh,syn.next());
}
void
copyUvList(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext0> <out>.<ext1>\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + meshSaveFormatsCLDescription()
);
Mesh in = loadMesh(syn.next());
Mesh out = loadMesh(syn.next());
if (in.uvs.size() != out.uvs.size())
syn.error("Incompatible UV list sizes");
out.uvs = in.uvs;
saveMesh(out,syn.curr());
return;
}
void
copyUvs(CLArgs const & args)
{
Syntax syn(args,
"<from>.<ext0> <to>.<ext1>\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + meshSaveFormatsCLDescription()
);
Mesh in = loadMesh(syn.next());
Mesh out = loadMesh(syn.next());
out.uvs = in.uvs;
if (in.surfaces.size() != out.surfaces.size())
fgThrow("Incompatible number of surfaces");
for (size_t ss=0; ss<in.surfaces.size(); ++ss) {
Surf const & sin = in.surfaces[ss];
Surf & sout = out.surfaces[ss];
if ((sin.tris.size() != sout.tris.size()) ||
(sin.quads.size() != sout.quads.size()))
fgThrow("Incompatible facet counts");
sout.tris.uvInds = sin.tris.uvInds;
sout.quads.uvInds = sin.quads.uvInds;
}
saveMesh(out,syn.curr());
return;
}
void
copyverts(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext0> <out>.<ext1>\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + meshSaveFormatsCLDescription() + "\n"
" <out> is modified to have the vertex list from <in>"
);
Mesh in = loadMesh(syn.next());
Mesh out = loadMesh(syn.next());
if (in.verts.size() != out.verts.size())
syn.error("Incompatible vertex list sizes");
out.verts = in.verts;
saveMesh(out,syn.curr());
return;
}
void
emboss(CLArgs const & args)
{
Syntax syn(args,
"<uvImage>.<img> <meshin>.<ext0> <val> <out>.<ext1>\n"
" <uvImage> = a UV-layout image whose grescale values will be used to emboss (0 - none, 255 - full)\n"
" <img> = " + imgFileExtensionsDescription() + "\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <val> = Embossing factor as ratio of the max bounding box dimension.\n"
" <ext1> = " + meshSaveFormatsCLDescription()
);
ImgUC img;
loadImage_(syn.next(),img); // Treat as greyscale
Mesh mesh = loadMesh(syn.next());
if (mesh.uvs.empty())
fgThrow("Mesh has no UVs",syn.curr());
if (mesh.surfaces.size() != 1)
fgThrow("Only 1 surface currently supported",syn.curr());
float val = syn.nextAs<float>();
if (!(val > 0.0f))
fgThrow("Emboss value must be > 0",toStr(val));
mesh.verts = embossMesh(mesh,img,val);
saveMesh(mesh,syn.next());
}
void
invWind(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription() + "\n"
" Inverts the winding of all facets in <in> and saves to <out>"
);
Mesh mesh = loadMesh(syn.next());
for (size_t ss=0; ss<mesh.surfaces.size(); ++ss) {
Surf & surf = mesh.surfaces[ss];
for (size_t ii=0; ii<surf.tris.size(); ++ii)
std::swap(surf.tris.posInds[ii][1],surf.tris.posInds[ii][2]);
for (size_t ii=0; ii<surf.tris.uvInds.size(); ++ii)
std::swap(surf.tris.uvInds[ii][1],surf.tris.uvInds[ii][2]);
for (size_t ii=0; ii<surf.quads.size(); ++ii)
std::swap(surf.quads.posInds[ii][1],surf.quads.posInds[ii][3]);
for (size_t ii=0; ii<surf.quads.uvInds.size(); ++ii)
std::swap(surf.quads.uvInds[ii][1],surf.quads.uvInds[ii][3]);
}
saveMesh(mesh,syn.next());
}
void
markVerts(CLArgs const & args)
{
Syntax syn(args,
"<in>.tri <verts>.<ext> <out>.tri\n"
" <ext> = " + meshLoadFormatsCLDescription() + "\n"
" <out>.tri will be saved after marking a vertex in <in>.tri that is closest to each vertex in <verts>.<ext>."
);
Mesh mesh = loadTri(syn.next());
Vec3Fs verts = loadMesh(syn.next()).verts;
float dim = cMaxElem(cDims(mesh.verts));
uint poorMatches = 0,
totalMatches = 0;
for (size_t vv=0; vv<verts.size(); ++vv) {
Vec3F v = verts[vv];
float bestMag = maxFloat();
uint bestIdx = 0;
for (size_t ii=0; ii<mesh.verts.size(); ++ii) {
float mag = cMag(mesh.verts[ii]-v);
if (mag < bestMag) {
bestMag = mag;
bestIdx = uint(ii);
}
}
if (sqrt(bestMag) / dim > 0.00001f)
++poorMatches;
if (!contains(mesh.markedVerts,bestIdx)) {
mesh.markedVerts.push_back(MarkedVert(bestIdx));
++totalMatches;
}
}
if (poorMatches > 0)
fgout << fgnl << "WARNING: " << poorMatches << " poor matches.";
if (totalMatches < verts.size())
fgout << fgnl << "WARNING: duplicate matches.";
fgout << fgnl << totalMatches << " vertices marked.";
saveTri(syn.next(),mesh);
}
void
mmerge(CLArgs const & args)
{
Syntax syn(args,
"(<mesh>.<extIn>)+ <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
while (syn.more()) {
string name = syn.next();
if (syn.more())
mesh = mergeMeshes(mesh,loadMesh(name));
else
saveMesh(mesh,name);
}
}
void
mergesurfs(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
if (mesh.surfaces.size() < 2)
fgout << "WARNING: No extra surfaces to merge.";
else
mesh.surfaces = {mergeSurfaces(mesh.surfaces)};
saveMesh(mesh,syn.next());
}
void
rdf(CLArgs const & args)
{
Syntax syn(args,
"<in>.tri [<out>.tri]\n"
" <in>.tri - Will be overwritten if <out>.tri is not specified\n"
"NOTES:\n"
" Duplicates are determined by vertex index. To remove duplicates by vertex\n"
" value, first remove duplicate vertices."
);
Ustring fni(syn.next()),
fno = fni;
if (syn.more())
fno = syn.next();
saveTri(fno,removeDuplicateFacets(loadTri(fni)));
}
void
rt(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut> (<surfIndex> <triEquivIndex>)+\n"
" <extIn> - " + meshLoadFormatsCLDescription() + "\n"
" <extOut> - " + meshSaveFormatsCLDescription() + "\n"
" <triEquivIndex> - Tri-equivalent index of triangle or half-quad to remove."
);
Mesh mesh = loadMesh(syn.next());
Ustring outName = syn.next();
while (syn.more()) {
size_t si = syn.nextAs<size_t>(),
ti = syn.nextAs<size_t>();
if (si >= mesh.surfaces.size())
fgThrow("Surface index out of bounds",toStr(si),toStr(mesh.surfaces.size()));
Surf & surf = mesh.surfaces[si];
if (ti >= surf.numTriEquivs())
fgThrow("Tri equiv index out of bounds",toStr(ti),toStr(surf.numTriEquivs()));
if (ti < surf.tris.size())
surf.removeTri(ti);
else {
ti -= surf.tris.size();
Vec4UI qvs = surf.quads.posInds[ti/2];
Vec4UI uvs(0);
if (!surf.quads.uvInds.empty())
uvs = surf.quads.uvInds[ti/2];
surf.removeQuad(ti/2);
// The other tri making up the quad needs to be appended to tris:
if (ti & 0x1)
surf.tris.posInds.push_back(Vec3UI(qvs[0],qvs[1],qvs[2]));
else
surf.tris.posInds.push_back(Vec3UI(qvs[2],qvs[3],qvs[0]));
if (!surf.tris.uvInds.empty()) {
if (ti & 0x1)
surf.tris.uvInds.push_back(Vec3UI(uvs[0],uvs[1],uvs[2]));
else
surf.tris.uvInds.push_back(Vec3UI(uvs[2],uvs[3],uvs[0]));
}
}
}
saveMesh(mesh,outName);
}
void
ruv(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
mesh = meshRemoveUnusedVerts(mesh);
saveMesh(mesh,syn.next());
}
void
sortFacets(CLArgs const & args)
{
Syntax syn(args,
"<meshIn>.<ext> <albedo>.<img> <meshOut>.<ext> [<opaque>.<ext>]*\n"
" <mesh> - Mesh to have facets sorted\n"
" <ext> - " + meshLoadFormatsCLDescription() + "\n"
" <albedo> - Map containing the alpha channel\n"
" <img> - " + imgFileExtensionsDescription() + "\n"
" <opaque> - Any opaque objects blocking view which affects sorting\n"
"Will find the best compromise sorted rendering order for front/back (+/-Z), side (+/-X)\n"
"and top (Y) views, on a per-surface basis, and save the sorted result. All quads are\n"
"converted to tris and all surfaces are merged into one.");
Mesh mesh = loadMesh(syn.next());
ImgC4UC albedo = loadImage(syn.next());
Ustring outName = syn.next();
Mesh opaque;
while (syn.more())
opaque = mergeMeshes(opaque,loadMesh(syn.next()));
mesh = sortTransparentFaces(mesh,albedo,opaque);
saveMesh(mesh,outName);
}
void
mergenamedsurfs(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
mesh = mergeSameNameSurfaces(mesh);
saveMesh(mesh,syn.next());
}
static void
retopo(CLArgs const & args)
{
Syntax syn { args,
"<baseName> <retopoBase> <outBase>\n"
" <baseName>.tri must exist and optionally <baseName>.egm\n"
" <retopoBase>.tri and optionally <retopoBase>.emg will be created\n"
"DESCRIPTION:\n"
" * the surfaces must be in exact alignment\n"
" * unchanged verts will preserve their morph and EGM values\n"
" * new verts will have zero values for morph and EGM\n"
" * surface points and marked verts are discarded"
};
string baseIn = syn.next(),
baseRe = syn.next(),
baseOut = syn.next();
syn.noMoreArgsExpected();
Mesh meshIn = loadTri(baseIn+".tri"),
meshRe = loadTri(baseRe+".tri");
float maxDim = cMaxElem(cDims(meshIn.verts)),
threshMag = maxDim * 0.000001f; // One part in 1M match threshold
Uints mapRI;
for (Vec3F vr : meshRe.verts) {
float bestMag = floatMax;
uint bestIdx;
for (size_t vv=0; vv<meshIn.verts.size(); ++vv) {
Vec3F const & vi = meshIn.verts[vv];
float mag = cMag(vi-vr);
if (mag < bestMag) {
bestMag = mag;
bestIdx = uint(vv);
}
}
if (bestMag < threshMag)
mapRI.push_back(bestIdx);
else
mapRI.push_back(uintMax);
}
Uints mapIR(meshIn.verts.size(),uintMax);
for (size_t rr=0; rr<mapRI.size(); ++rr) {
uint ii = mapRI[rr];
if (ii != uintMax) {
FGASSERT(ii < mapIR.size());
mapIR[ii] = uint(rr);
}
}
Mesh meshOut = meshRe;
for (Morph const & morphIn : meshIn.deltaMorphs) {
Morph morphOut {morphIn.name};
for (size_t vv=0; vv<meshRe.verts.size(); ++vv) {
uint idx = mapRI[vv];
if (idx == uintMax)
morphOut.verts.push_back(Vec3F{0});
else
morphOut.verts.push_back(morphIn.verts[idx]);
}
meshOut.deltaMorphs.push_back(morphOut);
}
for (IndexedMorph const & morphIn : meshIn.targetMorphs) {
IndexedMorph morphOut {morphIn.name,{},{}};
for (size_t vv=0; vv<morphIn.baseInds.size(); ++vv) {
uint idxI = morphIn.baseInds[vv],
idxR = mapIR[idxI];
if (idxR != uintMax) {
morphOut.baseInds.push_back(idxR);
morphOut.verts.push_back(morphIn.verts[vv]);
}
}
meshOut.targetMorphs.push_back(morphOut);
}
saveTri(baseOut+".tri",meshOut);
}
static void
seams(CLArgs const & args)
{
Syntax syn(args,"<in>.<ext>\n"
" <ext> - " + meshLoadFormatsCLDescription() + "\n"
" Saves a mesh to <in>_<num>.tri for each contiguous seam in <in> with the vertices of that seam marked."
);
string fname = syn.next();
Mesh mesh = loadMesh(fname);
MeshTopology topo(mesh.verts.size(),mesh.asTriSurf().tris);
Svec<set<uint> > seams = topo.seams();
Ustring fbase = pathToBase(fname) + "_";
size_t cnt = 0;
for (set<uint> const & seam : seams) {
Mesh mm = mesh;
for (uint vv : seam)
mm.markedVerts.push_back(MarkedVert{vv});
saveTri(fbase + toStrDigits(cnt++,2) + ".tri",mm);
}
}
void
splitObjByMtl(CLArgs const & args)
{
Syntax syn(args,
"<mesh>.[w]obj <base>\n"
" Creates a <base>_<name>.tri file for each 'usemtl' name referenced");
Mesh mesh = loadWObj(syn.next(),"usemtl");
string base = syn.next();
Mesh m = mesh;
for (size_t ii=0; ii<mesh.surfaces.size(); ++ii) {
m.surfaces = svec(mesh.surfaces[ii]);
saveTri(base+"_"+mesh.surfaces[ii].name+".tri",m);
}
}
void
splitsurfsbyuvs(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
mesh = splitSurfsByUvs(mesh);
saveMesh(mesh,syn.next());
}
void
splitCont(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
"COMMENTS:\n"
" * Splits surfaces by connected vertex indices.\n"
" * Stores results to separate meshes with suffix '_<num>.tri'"
);
Mesh mesh = loadMesh(syn.next());
Ustring base = pathToBase(syn.curr());
uint idx = 0;
Mesh out = mesh;
for (size_t ss=0; ss<mesh.surfaces.size(); ++ss) {
Surfs surfs = splitByContiguous(mesh.surfaces[ss]);
for (size_t ii=0; ii<surfs.size(); ++ii) {
out.surfaces = svec(surfs[ii]);
saveTri(base+"_"+toStr(idx++)+".tri",out);
}
}
}
void
surfAdd(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext> <name> <out>.fgmesh\n"
" <ext> - " + meshLoadFormatsCLDescription() + "\n"
" <name> - Surface name"
);
Mesh mesh = loadMesh(syn.next());
Surf surf;
surf.name = syn.next();
mesh.surfaces.push_back(surf);
saveFgmesh(syn.next(),mesh);
}
void
surfCopy(CLArgs const & args)
{
Syntax syn(args,
"<from>.fgmesh <to>.<ext> <out>.fgmesh\n"
" <ext> - " + meshLoadFormatsCLDescription() + "\n"
" * tris only, uvs not preserved."
);
Mesh from = loadFgmesh(syn.next()),
to = loadMesh(syn.next());
saveFgmesh(syn.next(),copySurfaceStructure(from,to));
}
void
surfDel(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext> <idx> <out>.<ext>\n"
" <ext> - " + meshLoadFormatsCLDescription() + "\n"
" <idx> - Which surface index to delete"
);
Mesh mesh = loadMesh(syn.next());
size_t idx = syn.nextAs<uint>();
if (idx >= mesh.surfaces.size())
syn.error("Selected surface index out of range",toStr(idx));
mesh.surfaces.erase(mesh.surfaces.begin()+idx);
saveMesh(mesh,syn.next());
}
void
surfList(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext>\n"
" <ext> - " + meshLoadFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
for (size_t ss=0; ss<mesh.surfaces.size(); ++ss) {
Surf const & surf = mesh.surfaces[ss];
fgout << fgnl << ss << ": " << surf.name;
}
}
void
surfRen(CLArgs const & args)
{
Syntax syn(args,
"<in>.fgmesh <idx> <name>\n"
" <idx> - Which surface\n"
" <name> - Surface name"
);
Ustring meshFname = syn.next();
Mesh mesh = loadFgmesh(meshFname);
size_t idx = syn.nextAs<size_t>();
if (idx >= mesh.surfaces.size())
fgThrow("Index value larger than available surfaces");
mesh.surfaces[idx].name = syn.next();
saveFgmesh(meshFname,mesh);
}
void
spCopy(CLArgs const & args)
{
Syntax syn(args,"<from>.<mi> <to>.<mi> <out>.<mo>\n"
" <mi> - " + meshLoadFormatsCLDescription() + "\n"
" <mo> - " + meshSaveFormatsCLDescription()
);
Mesh from = loadMesh(syn.next()),
to = loadMesh(syn.next());
if (from.surfaces.size() != to.surfaces.size())
fgThrow("'from' and 'to' meshes have different surface counts");
for (size_t ss=0; ss<to.surfaces.size(); ++ss)
cat_(to.surfaces[ss].surfPoints,from.surfaces[ss].surfPoints);
saveMesh(to,syn.next());
}
void
spDel(CLArgs const & args)
{
Syntax syn(args,
"<in>.tri <ptIdx>\n"
" <spIdx> - Which point on that surface to delete"
);
Ustring meshFname = syn.next();
Mesh mesh = loadTri(meshFname);
size_t ii = syn.nextAs<size_t>();
Surf & surf = mesh.surfaces[0];
if (ii >= surf.surfPoints.size())
fgThrow("Point index value larger than availables points");
surf.surfPoints.erase(surf.surfPoints.begin() + ii);
saveTri(meshFname,mesh);
}
void
spList(CLArgs const & args)
{
Syntax syn(args,"<in>.fgmesh");
Mesh mesh = loadMesh(syn.next());
for (size_t ss=0; ss<mesh.surfaces.size(); ++ss) {
Surf const & surf = mesh.surfaces[ss];
fgout << fgnl << "Surface " << ss << ": " << surf.name << fgpush;
for (size_t ii=0; ii<surf.surfPoints.size(); ++ii)
fgout << fgnl << ii << " : " << surf.surfPoints[ii].label;
fgout << fgpop;
}
}
void
spRen(CLArgs const & args)
{
Syntax syn(args,
"<in>.fgmesh <surfIdx> <ptIdx> <name>\n"
" <surfIdx> - Which surface\n"
" <spIdx> - Which point on that surface\n"
" <name> - Name"
);
Ustring meshFname = syn.next();
Mesh mesh = loadFgmesh(meshFname);
size_t ss = syn.nextAs<size_t>(),
ii = syn.nextAs<size_t>();
if (ss >= mesh.surfaces.size())
fgThrow("Surface index value larger than available surfaces");
Surf & surf = mesh.surfaces[ss];
if (ii >= surf.surfPoints.size())
fgThrow("Point index value larger than availables points");
surf.surfPoints[ii].label = syn.next();
saveFgmesh(meshFname,mesh);
}
void
spsToVerts(CLArgs const & args)
{
Syntax syn(args,
"<in>.tri <out>.tri\n"
" <out>.tri will be appended with the new marked vertices."
);
Mesh in = loadTri(syn.next());
Mesh out = loadTri(syn.next());
surfPointsToMarkedVerts_(in,out);
saveTri(syn.curr(),out);
}
void
surf(CLArgs const & args)
{
Cmds ops;
ops.push_back(Cmd(surfAdd,"add","Add an empty surface to a mesh"));
ops.push_back(Cmd(surfCopy,"copy","Copy surface structure between aligned meshes"));
ops.push_back(Cmd(surfDel,"del","Delete a surface in a mesh (leaves verts unchanged)"));
ops.push_back(Cmd(surfList,"list","List surfaces in mesh"));
ops.push_back(Cmd(mergenamedsurfs,"mergeNamed","Merge surfaces with identical names"));
ops.push_back(Cmd(mergesurfs,"merge","Merge all surfaces in a mesh into one"));
ops.push_back(Cmd(surfRen,"ren","Rename a surface in a mesh"));
ops.push_back(Cmd(spCopy,"spCopy","Copy surf points between meshes with identical surface topology"));
ops.push_back(Cmd(spDel,"spDel","Delete a surface point"));
ops.push_back(Cmd(spList,"spList","List surface points in each surface"));
ops.push_back(Cmd(spRen,"spRen","Rename a surface point"));
ops.push_back(Cmd(spsToVerts,"spVert","Convert surface points to marked vertices"));
doMenu(args,ops);
}
void
toTris(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
mesh.convertToTris();
saveMesh(mesh,syn.next());
}
void
unifyuvs(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
mesh = unifyIdenticalUvs(mesh);
saveMesh(mesh,syn.next());
}
void
unifyverts(CLArgs const & args)
{
Syntax syn(args,
"<in>.<extIn> <out>.<extOut>\n"
" <extIn> = " + meshLoadFormatsCLDescription() + "\n"
" <extOut> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
mesh = unifyIdenticalVerts(mesh);
saveMesh(mesh,syn.next());
}
void
uvclamp(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext0> [<out>.<ext1>]\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + meshSaveFormatsCLDescription()
);
Mesh in = loadMesh(syn.next());
Mat22F cb(0,1,0,1);
for (size_t ii=0; ii<in.uvs.size(); ++ii)
in.uvs[ii] = clampBounds(in.uvs[ii],cb);
if (syn.more())
saveMesh(in,syn.next());
else
saveMesh(in,syn.curr());
return;
}
void
uvSolidImage(CLArgs const & args)
{
Syntax syn(args,
"<mesh>.<extM> <size> <image>.<extI>\n"
" <mesh> - The mesh must contains UVs for anything to be done.\n"
" <extM> - " + meshLoadFormatsCLDescription() + "\n"
" <size> - Output image size (will be square).\n"
" <image> - Output image.\n"
" <extI> - " + imgFileExtensionsDescription()
);
Mesh mesh = loadMesh(syn.next());
uint sz = syn.nextAs<uint>();
if (sz > (1 << 12))
syn.error("<size> is too large",syn.curr());
ImgUC img = getUvCover(mesh,Vec2UI(sz*4));
img = fgShrink2(img);
img = fgShrink2(img);
saveImage(syn.next(),img);
}
void
uvWireframeImage(CLArgs const & args)
{
Syntax syn(args,
"<mesh>.<extM> <image>.<extI>\n"
" <mesh> - The mesh must contains UVs for anything to be done.\n"
" <extM> - " + meshLoadFormatsCLDescription() + "\n"
" <image> - If this file already exists it will be used as the background.\n"
" <extI> - " + imgFileExtensionsDescription()
);
Mesh mesh = loadMesh(syn.next());
ImgC4UC img;
if (pathExists(syn.peekNext()))
loadImage_(syn.peekNext(),img);
saveImage(syn.next(),cUvWireframeImage(mesh,RgbaUC{0,255,0,255},img));
}
void
uvmask(CLArgs const & args)
{
Syntax syn(args,
"<meshIn>.<ext0> <imageIn>.<ext1> <meshOut>.<ext2>\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + imgFileExtensionsDescription() + "\n"
" <ext2> = " + meshSaveFormatsCLDescription()
);
Mesh mesh = loadMesh(syn.next());
ImgC4UC img = loadImage(syn.next());
Img<FgBool> mask = Img<FgBool>(img.dims());
for (Iter2UI it(img.dims()); it.valid(); it.next()) {
Vec4UC px = img[it()].m_c;
mask[it()] = (px[0] > 0) || (px[1] > 0) || (px[2] > 0); }
mask = mapAnd(mask,flipHoriz(mask));
mesh = fg3dMaskFromUvs(mesh,mask);
saveMesh(mesh,syn.next());
}
void
uvunwrap(CLArgs const & args)
{
Syntax syn(args,
"<in>.<ext0> [<out>.<ext1>]\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + meshSaveFormatsCLDescription()
);
Mesh in = loadMesh(syn.next());
for (size_t ii=0; ii<in.uvs.size(); ++ii) {
Vec2F uv = in.uvs[ii];
in.uvs[ii][0] = cMod(uv[0],1.0f);
in.uvs[ii][1] = cMod(uv[1],1.0f);
}
if (syn.more())
saveMesh(in,syn.next());
else
saveMesh(in,syn.curr());
return;
}
void
xformApply(CLArgs const & args)
{
Syntax syn(args,
"<similarity>.xml <in>.<ext0> <out>.<ext1>\n"
" <ext0> = " + meshLoadFormatsCLDescription() + "\n"
" <ext1> = " + meshSaveFormatsCLDescription()
);
SimilarityD xform;
loadBsaXml(syn.next(),xform);
Mesh in = loadMesh(syn.next());
Mesh out(in);
out.transform(Affine3F(xform.asAffine()));
saveMesh(out,syn.next());
}
void
xformCreateIdentity(CLArgs const & args)
{
Syntax syn(args,
"<output>.xml \n"
" Edit the values in this file or apply subsequent transforms with other commands"
);
string simFname = syn.next();
saveBsaXml(simFname,SimilarityD::identity());
}
void
xformCreateMeshes(CLArgs const & args)
{
Syntax syn(args,
"<similarity>.xml <base>.<ex> <transformed>.<ex>\n"
" <ex> = " + meshLoadFormatsCLDescription()
);
string simFname = syn.next();
Mesh base = loadMesh(syn.next());
Mesh targ = loadMesh(syn.next());
if (base.verts.size() != targ.verts.size())
fgThrow("Base and target mesh vertex counts are different");
Vec3Ds bv = scast<double>(base.verts),
tv = scast<double>(targ.verts);
SimilarityD sim = similarityApprox(bv,tv);
double ssd = cSsd(mapMul(sim.asAffine(),bv),tv),
sz = cMaxElem(cDims(tv));
fgout << fgnl << "Transformed base to target relative RMS delta: " << sqrt(ssd / tv.size()) / sz;
saveBsaXml(simFname,sim);
}
void
xformCreateRotate(CLArgs const & args)
{
Syntax syn(args,
"<output>.xml <axis> <degrees> <point> [<input>.xml]\n"
" <output> - Save here\n"
" <axis> - (x | y | z) Right-hand-rule axis of rotation\n"
" <point> - <x> <y> <z> Point around which rotation is applied\n"
" <input> - Compose rotation after this transform, if specified"
);
string outName = syn.next();
string axisStr = syn.next();
if (axisStr.size() != 1)
syn.error("<axis> must be one character");
char axisName = tolower(axisStr[0]);
int axisNum = int(axisName) - int('x');
if ((axisNum < 0) || (axisNum > 2))
syn.error("Invalid value for <axis>",axisStr);
double degs = syn.nextAs<double>(),
rads = degToRad(degs);
QuaternionD rot(rads,uint(axisNum));
Vec3D point {0};
point[0] = syn.nextAs<double>();
point[1] = syn.nextAs<double>();
point[2] = syn.nextAs<double>();
SimilarityD xf = SimilarityD{point} * SimilarityD{rot} * SimilarityD{-point};
if (syn.more())
xf = xf * loadBsaXml<SimilarityD>(syn.next());
saveBsaXml(outName,xf);
}
void
xformCreateScale(CLArgs const & args)
{
Syntax syn(args,
"<similarity>.xml <scale>"
);
string simFname = syn.next();
SimilarityD sim;
if (pathExists(simFname))
loadBsaXml(simFname,sim);
double scale = syn.nextAs<double>();
saveBsaXml(simFname,SimilarityD(scale)*sim);
}
void
xformCreateTrans(CLArgs const & args)
{
Syntax syn(args,
"<similarity>.xml <X> <Y> <Z>"
);
string simFname = syn.next();
SimilarityD sim;
if (pathExists(simFname))
loadBsaXml(simFname,sim);
Vec3D trans;
trans[0] = syn.nextAs<double>();
trans[1] = syn.nextAs<double>();
trans[2] = syn.nextAs<double>();
saveBsaXml(simFname,SimilarityD(trans)*sim);
}
void
xformCreate(CLArgs const & args)
{
Cmds cmds {
{xformCreateIdentity,"identity","Create identity similarity transform XML file for editing"},
{xformCreateMeshes,"meshes","Create similarity transform from base and transformed meshes with matching vertex lists"},
{xformCreateRotate,"rotate","Combine a rotation with a similarity transform XML file"},
{xformCreateScale,"scale","Combine a scaling with a similarity transform XML file"},
{xformCreateTrans,"translate","Combine a translation with a similarity transform XML file"}
};
doMenu(args,cmds);
}
void
xformMirror(CLArgs const & args)
{
Syntax syn(args,
"<axis> <meshIn>.<ext1> [<meshOut>.<ext2>]\n"
" <axis> - (x | y | z)\n"
" <ext1> - " + meshLoadFormatsCLDescription() + "\n"
" <ext2> - " + meshSaveFormatsCLDescription()
);
uint axis = 0;
string axisStr = syn.nextLower().as_ascii();
if (axisStr == "x")
axis = 0;
else if (axisStr == "y")
axis = 1;
else if (axisStr == "z")
axis = 3;
else
syn.error("Invalid value of <axis>",axisStr);
Mesh mesh = loadMesh(syn.next());
Mat33F xf = Mat33F::identity();
xf.rc(axis,axis) = -1.0f;
mesh.transform(xf);
Ustring fname = (syn.more() ? syn.next() : syn.curr());
saveMesh(mesh,fname);
}
void
xform(CLArgs const & args)
{
Cmds cmds;
cmds.push_back(Cmd(xformApply,"apply","Apply a simiarlity transform (from XML file) to a mesh"));
cmds.push_back(Cmd(xformCreate,"create","Create a similarity transform XML file"));
cmds.push_back(Cmd(xformMirror,"mirror","Mirror a mesh"));
doMenu(args,cmds);
}
void
meshops(CLArgs const & args)
{
Cmds ops {
{combinesurfs,"combinesurfs","Combine surfaces from meshes with identical vertex lists"},
{convert,"convert","Convert the mesh between different formats"},
{copyUvList,"copyUvList","Copy UV list from one mesh to another with same UV count"},
{copyUvs,"copyUvs","Copy UVs from one mesh to another with identical facet structure"},
{copyverts,"copyverts","Copy verts from one mesh to another with same vertex count"},
{emboss,"emboss","Emboss a mesh based on greyscale values of a UV image"},
{invWind,"invWind","Invert facet winding of a mesh"},
{markVerts,"markVerts","Mark vertices in a .TRI file from a given list"},
{mmerge,"merge","Merge multiple meshes into one. No optimization is done"},
{rdf,"rdf","Remove Duplicate Facets within each surface"},
{retopo,"retopo","Rebase a mesh topology with an exactly aligned mesh"},
{rt,"rt","Remove specific tris from a mesh"},
{ruv,"ruv","Remove vertices and uvs not referenced by a surface or marked vertex"},
{seams,"seams","Extract each seam of a mesh as a file with seam verts marked"},
{sortFacets,"sortFacets","Sort facets for optimal transparency viewing"},
{splitObjByMtl,"splitObjByMtl","Split up an OBJ mesh by 'usemtl' name"},
{splitCont,"splitCont","Split up surface by contiguous vertex indices"},
{splitsurfsbyuvs,"splitSurfsByUvs","Split up surfaces with discontiguous UV mappings"},
{surf,"surf","Operations on mesh surface structure"},
{toTris,"toTris","Convert all facets to tris"},
{unifyuvs,"unifyUVs","Unify identical UV coordinates"},
{unifyverts,"unifyVerts","Unify identical vertices"},
{uvclamp,"uvclamp","Clamp UV coords to the range [0,1]"},
{uvWireframeImage,"uvImgW","Wireframe image of mesh UV map"},
{uvSolidImage,"uvImgS","Solid white inside UV facets, black outside, 4xFSAA"},
{uvmask,"uvmask","Mask out geometry for any black areas of a texture image {auto symmetrized)"},
{uvunwrap,"uvunwrap","Unwrap wrap-around UV coords to the range [0,1]"},
{xform,"xform","Create or apply similarity transforms from/to meshes"},
};
doMenu(args,ops);
}
}
Cmd
getMeshopsCmd()
{return Cmd(meshops,"mesh","3D Mesh tools"); }
}
// */
| 35.51378 | 128 | 0.539438 | MikhailGorobets |
86a8b695a80adb549baeea0066c73d6c83c73651 | 11,899 | cpp | C++ | code/src/Core/Math/Matrix.cpp | Arzana/Plutonium | 5a17c93e5072ac291b96347a4df196e1609fabe2 | [
"MIT"
] | 4 | 2019-03-21T16:02:03.000Z | 2020-04-09T08:53:29.000Z | code/src/Core/Math/Matrix.cpp | Arzana/Plutonium | 5a17c93e5072ac291b96347a4df196e1609fabe2 | [
"MIT"
] | 24 | 2018-04-06T08:25:17.000Z | 2020-10-19T11:01:09.000Z | code/src/Core/Math/Matrix.cpp | Arzana/Plutonium | 5a17c93e5072ac291b96347a4df196e1609fabe2 | [
"MIT"
] | null | null | null | #include "Core\Math\Matrix.h"
inline float det33(float a, float b, float c, float d, float e, float f, float g, float h, float i)
{
return a * e * i + b * f * g + c * d * h - c * e * g - b * d * i - a * f * h;
}
Pu::Matrix Pu::Matrix::CreateFrom3x3(const Matrix3 & matrix, Vector3 translation)
{
return Matrix(
matrix.f[0], matrix.f[3], matrix.f[6], translation.X,
matrix.f[1], matrix.f[4], matrix.f[7], translation.Y,
matrix.f[2], matrix.f[5], matrix.f[8], translation.Z,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateScaledTranslation(Vector3 translation, float scalar)
{
return Matrix(
scalar, 0.0f, 0.0f, translation.X,
0.0f, scalar, 0.0f, translation.Y,
0.0f, 0.0f, scalar, translation.Z,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateScaledTranslation(Vector3 translation, Vector3 scalar)
{
return Matrix(
scalar.X, 0.0f, 0.0f, translation.X,
0.0f, scalar.Y, 0.0f, translation.Y,
0.0f, 0.0f, scalar.Z, translation.Z,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateRotation(float theta, Vector3 axis)
{
const float cc = cosf(theta);
const float ss = sinf(theta);
const float xx = axis.X * axis.X;
const float xy = axis.X * axis.Y;
const float xz = axis.X * axis.Z;
const float yy = axis.Y * axis.Y;
const float yz = axis.Y * axis.Z;
const float zz = axis.Z * axis.Z;
const float omc = 1.0f - cc;
float a = xx * omc + cc;
float b = xy * omc - axis.Z * ss;
float c = xz * omc + axis.Y * ss;
float e = xy * omc + axis.Z * ss;
float f = yy * omc + cc;
float g = yz * omc - axis.X * ss;
float i = xz * omc - axis.Y * ss;
float j = yz * omc + axis.X * ss;
float k = zz * omc + cc;
return Matrix(a, b, c, 0.0f, e, f, g, 0.0f, i, j, k, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateRotation(Quaternion quaternion)
{
const float ii = sqr(quaternion.I);
const float jj = sqr(quaternion.J);
const float kk = sqr(quaternion.K);
const float ir = quaternion.I * quaternion.R;
const float ij = quaternion.I * quaternion.J;
const float kr = quaternion.K * quaternion.R;
const float ki = quaternion.K * quaternion.I;
const float jr = quaternion.J * quaternion.R;
const float jk = quaternion.J * quaternion.K;
const float a = 1.0f - 2.0f * (jj + kk);
const float b = 2.0f * (ij - kr);
const float c = 2.0f * (ki + jr);
const float e = 2.0f * (ij + kr);
const float f = 1.0f - 2.0f * (kk + ii);
const float g = 2.0f * (jk - ir);
const float i = 2.0f * (ki - jr);
const float j = 2.0f * (jk + ir);
const float k = 1.0f - 2.0f * (jj + ii);
return Matrix(a, b, c, 0.0f, e, f, g, 0.0f, i, j, k, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateWorld(Vector2 pos, float theta, Vector2 scale)
{
/*
Translation * Rotation (Roll) * Scale
For 2D any rotation is on the Z-axis, we inline the creating of this matrix.
We can use the order of matrix multiplication to eleminate the other multiplications.
*/
const float s = sinf(theta);
const float c = cosf(theta);
return Matrix(
c * scale.X, -s * scale.Y, 0.0f, pos.X,
s * scale.X, c * scale.Y, 0.0f, pos.Y,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateWorld(Vector3 pos, Quaternion orientation, Vector3 scale)
{
const Matrix3 rot = Matrix3::CreateRotation(orientation);
/*
Translation * Rotation * Scale
Can be done without matrix multiplication because the order of multiplication is known.
*/
return Matrix(
scale.X * rot.c1.X, scale.Y * rot.c2.X, scale.Z * rot.c3.X, pos.X,
scale.X * rot.c1.Y, scale.Y * rot.c2.Y, scale.Z * rot.c3.Y, pos.Y,
scale.X * rot.c1.Z, scale.Y * rot.c2.Z, scale.Z * rot.c3.Z, pos.Z,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateOrtho(float width, float height, float near, float far)
{
const float a = 2.0f / width;
const float f = 2.0f / height;
const float k = 2.0f / (far - near);
return Matrix(
a, 0.0f, 0.0f, -1.0f,
0.0f, f, 0.0f, -1.0f,
0.0f, 0.0f, k, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateOrtho(float left, float right, float bottom, float top, float near, float far)
{
const float a = 2.0f / (right - left);
const float f = 2.0f / (top - bottom);
const float k = 2.0f / (far - near);
const float d = -(right + left) / (right - left);
const float h = -(top + bottom) / (top - bottom);
const float l = -(far + near) / (far - near);
return Matrix(
a, 0.0f, 0.0f, d,
0.0f, f, 0.0f, h,
0.0f, 0.0f, k, l,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Matrix Pu::Matrix::CreateFrustum(float left, float right, float bottom, float top, float near, float far)
{
const float a = (2.0f * near) / (right - left);
const float c = -((right + left) / (right - left));
const float f = -(2.0f * near) / (top - bottom);
const float g = -((bottom + top) / (top - bottom));
const float k = (far + near) / (far - near);
const float l = -(2.0f * far * near) / (far - near);
return Matrix(
a, 0.0f, c, 0.0f,
0.0f, f, g, 0.0f,
0.0f, 0.0f, k, l,
0.0f, 0.0f, 1.0f, 0.0f);
}
Pu::Matrix Pu::Matrix::CreatePerspective(float fovY, float aspr, float near, float far)
{
/*
This simpification can be made over the frustum function because the frustum is generic.
If the frustum is symetric (like with a perspective camera) we can use the formula.
Then we can solve a bit further so we don't have to multiply and divide with near for a and b.
*/
const float f = -1.0f / tanf(fovY * 0.5f);
const float a = -f / aspr;
const float k = (far + near) / (far - near);
const float l = -(2.0f * far * near) / (far - near);
return Matrix(
a, 0.0f, 0.0f, 0.0f,
0.0f, f, 0.0f, 0.0f,
0.0f, 0.0f, k, l,
0.0f, 0.0f, 1.0f, 0.0f);
}
Pu::Matrix Pu::Matrix::CreateLookIn(Vector3 pos, Vector3 direction, Vector3 up)
{
const Vector3 axisX = normalize(cross(up, direction));
const Vector3 axisY = cross(direction, axisX);
const float d = -dot(axisX, pos);
const float h = -dot(axisY, pos);
const float l = -dot(direction, pos);
return Matrix(
axisX.X, axisX.Y, axisX.Z, d,
axisY.X, axisY.Y, axisY.Z, h,
direction.X, direction.Y, direction.Z, l,
0.0f, 0.0f, 0.0f, 1.0f);
}
Pu::Quaternion Pu::Matrix::GetOrientation(void) const
{
return Quaternion::Create(normalize(GetForward()), normalize(GetUp()));
}
Pu::Vector3 Pu::Matrix::GetScale(void) const
{
return Vector3(GetRight().Length(), GetUp().Length(), GetForward().Length());
}
Pu::Vector3 Pu::Matrix::GetSquaredScale(void) const
{
return Vector3(GetRight().LengthSquared(), GetUp().LengthSquared(), GetForward().LengthSquared());
}
Pu::Matrix Pu::Matrix::GetStatic(void) const
{
/* Simply remove the translation. */
const Vector3 r = GetRight();
const Vector3 u = GetUp();
const Vector3 b = GetForward();
return Matrix(
r.X, u.X, b.X, 0.0f,
r.Y, u.Y, b.Y, 0.0f,
r.Z, u.Z, b.Z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
float Pu::Matrix::GetDeterminant(void) const
{
return
f[0] * det33(f[5], f[9], f[13], f[6], f[10], f[14], f[7], f[11], f[15]) -
f[1] * det33(f[1], f[9], f[13], f[2], f[10], f[14], f[3], f[11], f[15]) +
f[2] * det33(f[1], f[5], f[13], f[2], f[6], f[14], f[3], f[7], f[15]) -
f[3] * det33(f[1], f[5], f[9], f[2], f[6], f[10], f[3], f[7], f[11]);
}
/* Warning cause is checked and code is working as intended. */
#pragma warning (push)
#pragma warning (disable:4458)
Pu::Matrix Pu::Matrix::GetInverse(void) const
{
/* Inline calculate the matrix of minors needed for the determinant to save performance. */
const float a = det33(this->f[5], this->f[9], this->f[13], this->f[6], this->f[10], this->f[14], this->f[7], this->f[11], this->f[15]);
const float e = det33(this->f[1], this->f[9], this->f[13], this->f[2], this->f[10], this->f[14], this->f[3], this->f[11], this->f[15]);
const float i = det33(this->f[1], this->f[5], this->f[13], this->f[2], this->f[6], this->f[14], this->f[3], this->f[7], this->f[15]);
const float m = det33(this->f[1], this->f[5], this->f[9], this->f[2], this->f[6], this->f[10], this->f[3], this->f[7], this->f[11]);
/* Calculate determinant and if it's zero early out with an identity matrix. */
const float det = f[0] * a - f[4] * e + f[8] * i - f[12] * m;
if (det == 0.0f) return Matrix();
/* Calculate matrix of minors for the full matrix (inline transposed). */
const float b = det33(this->f[4], this->f[8], this->f[12], this->f[6], this->f[10], this->f[14], this->f[7], this->f[11], this->f[15]);
const float c = det33(this->f[4], this->f[8], this->f[12], this->f[5], this->f[9], this->f[13], this->f[7], this->f[11], this->f[15]);
const float d = det33(this->f[4], this->f[8], this->f[12], this->f[5], this->f[9], this->f[13], this->f[6], this->f[10], this->f[14]);
const float f = det33(this->f[0], this->f[8], this->f[12], this->f[2], this->f[10], this->f[14], this->f[3], this->f[11], this->f[15]);
const float g = det33(this->f[0], this->f[8], this->f[12], this->f[1], this->f[9], this->f[13], this->f[3], this->f[11], this->f[15]);
const float h = det33(this->f[0], this->f[8], this->f[12], this->f[1], this->f[9], this->f[13], this->f[2], this->f[10], this->f[14]);
const float j = det33(this->f[0], this->f[4], this->f[12], this->f[2], this->f[6], this->f[14], this->f[3], this->f[7], this->f[15]);
const float k = det33(this->f[0], this->f[4], this->f[12], this->f[1], this->f[5], this->f[13], this->f[3], this->f[7], this->f[15]);
const float l = det33(this->f[0], this->f[4], this->f[12], this->f[1], this->f[5], this->f[13], this->f[2], this->f[6], this->f[14]);
const float n = det33(this->f[0], this->f[4], this->f[8], this->f[2], this->f[6], this->f[10], this->f[3], this->f[7], this->f[11]);
const float o = det33(this->f[0], this->f[4], this->f[8], this->f[1], this->f[5], this->f[9], this->f[3], this->f[7], this->f[11]);
const float p = det33(this->f[0], this->f[4], this->f[8], this->f[1], this->f[5], this->f[9], this->f[2], this->f[6], this->f[10]);
/* Construct the adjugate matrix by checkboarding the determinants. */
const Matrix adj = Matrix(
+a, -b, +c, -d,
-e, +f, -g, +h,
+i, -j, +k, -l,
-m, +n, -o, +p);
/* Return the adjugate matrix multiplied by the inverse determinant. */
return adj * recip(det);
}
#pragma warning(pop)
Pu::Matrix Pu::Matrix::GetTranspose(void) const
{
return Matrix(c1.X, c1.Y, c1.Z, c1.W,
c2.X, c2.Y, c2.Z, c2.W,
c3.X, c3.Y, c3.Z, c3.W,
c4.X, c4.Y, c4.Z, c4.W);
}
Pu::string Pu::Matrix::ToString(void) const
{
if (nrlyeql(GetDeterminant(), 1.0f)) return "[Identity]";
string result;
for (size_t c = 0; c < 4; c++)
{
for (size_t r = 0; r < 3; r++)
{
result += std::_Floating_to_string("%.2f", f[c * 4 + r]);
result += ", ";
}
result += std::_Floating_to_string("%.2f", f[c * 4 + 3]);
result += '\n';
}
return result;
}
/* Warning cause is checked and code is working as intended. */
#pragma warning (push)
#pragma warning (disable:4458)
void Pu::Matrix::SetOrientation(float pitch, float yaw, float roll)
{
const float cz = cosf(pitch);
const float sz = sinf(pitch);
const float cy = cosf(yaw);
const float sy = sinf(yaw);
const float cx = cosf(roll);
const float sx = sinf(roll);
const float a = cx * cy;
const float b = cx * sy * sz - sx * cz;
const float c = cx * sy * cz + sx * sz;
const float e = sx * cy;
const float f = sx * sy * sz + cx * cz;
const float g = sx * sy * cz - cx * sz;
const float i = -sy;
const float j = cy * sz;
const float k = cy * cz;
c1 = Vector4(a, e, i, 0.0f) * GetRight().Length();
c2 = Vector4(b, f, j, 0.0f) * GetUp().Length();
c3 = Vector4(c, g, k, 0.0f) * GetForward().Length();
}
#pragma warning(pop)
void Pu::Matrix::SetScale(float v)
{
c1 = normalize(c1) * v;
c2 = normalize(c2) * v;
c3 = normalize(c3) * v;
}
void Pu::Matrix::SetScale(float x, float y, float z)
{
c1 = normalize(c1) * x;
c2 = normalize(c2) * y;
c3 = normalize(c3) * z;
}
void Pu::Matrix::SetScale(Vector3 v)
{
c1 = normalize(c1) * v.X;
c2 = normalize(c2) * v.Y;
c3 = normalize(c3) * v.Z;
} | 33.900285 | 136 | 0.604336 | Arzana |
86aecf99aebdb82c77a9d3e0a7f7cccb94bc0d27 | 831 | cpp | C++ | src/PyZPK/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/run_r1cs_gg_ppzksnark.cpp | gargarchit/PyZPK | 682c20efc6ae5d7bf705f9fcbcbf003d9e382412 | [
"Apache-2.0"
] | 4 | 2020-05-21T13:55:33.000Z | 2020-08-17T00:59:29.000Z | src/PyZPK/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/run_r1cs_gg_ppzksnark.cpp | gargarchit/PyZPK | 682c20efc6ae5d7bf705f9fcbcbf003d9e382412 | [
"Apache-2.0"
] | 1 | 2020-07-21T07:37:59.000Z | 2020-07-21T07:39:14.000Z | src/PyZPK/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/run_r1cs_gg_ppzksnark.cpp | gargarchit/PyZPK | 682c20efc6ae5d7bf705f9fcbcbf003d9e382412 | [
"Apache-2.0"
] | null | null | null | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>
#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/examples/run_r1cs_gg_ppzksnark.hpp>
namespace py = pybind11;
using namespace libsnark;
using namespace libff;
// Declaration of functionality that runs the R1CS GG ppzkSNARK for
// a given R1CS example.
void init_zk_proof_systems_ppzksnark_r1cs_gg_ppzksnark_run_r1cs_gg_ppzksnark(py::module &m)
{
// Runs the GG ppzkSNARK(generator, prover, and verifier) for a given
// R1CS example(specified by a constraint system, input, and witness).
using ppT = default_r1cs_gg_ppzksnark_pp;
m.def("run_r1cs_gg_ppzksnark", &run_r1cs_gg_ppzksnark<ppT>, py::arg("example"), py::arg("test_serialization"));
} | 39.571429 | 115 | 0.78941 | gargarchit |
86b392ea56b62ae052a3e7750b6054c5690e36cd | 10,612 | hpp | C++ | include/GlobalNamespace/WaypointData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/WaypointData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/WaypointData.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: BeatmapObjectData
#include "GlobalNamespace/BeatmapObjectData.hpp"
// Including type: OffsetDirection
#include "GlobalNamespace/OffsetDirection.hpp"
// Including type: NoteLineLayer
#include "GlobalNamespace/NoteLineLayer.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Skipping declaration: BeatmapDataItem because it is already included!
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: WaypointData
class WaypointData;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::WaypointData);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::WaypointData*, "", "WaypointData");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x2C
#pragma pack(push, 1)
// Autogenerated type: WaypointData
// [TokenAttribute] Offset: FFFFFFFF
class WaypointData : public ::GlobalNamespace::BeatmapObjectData {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private OffsetDirection <offsetDirection>k__BackingField
// Size: 0x4
// Offset: 0x20
::GlobalNamespace::OffsetDirection offsetDirection;
// Field size check
static_assert(sizeof(::GlobalNamespace::OffsetDirection) == 0x4);
// private System.Int32 <lineIndex>k__BackingField
// Size: 0x4
// Offset: 0x24
int lineIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
// private NoteLineLayer <lineLayer>k__BackingField
// Size: 0x4
// Offset: 0x28
::GlobalNamespace::NoteLineLayer lineLayer;
// Field size check
static_assert(sizeof(::GlobalNamespace::NoteLineLayer) == 0x4);
public:
// Get instance field reference: private OffsetDirection <offsetDirection>k__BackingField
::GlobalNamespace::OffsetDirection& dyn_$offsetDirection$k__BackingField();
// Get instance field reference: private System.Int32 <lineIndex>k__BackingField
int& dyn_$lineIndex$k__BackingField();
// Get instance field reference: private NoteLineLayer <lineLayer>k__BackingField
::GlobalNamespace::NoteLineLayer& dyn_$lineLayer$k__BackingField();
// public OffsetDirection get_offsetDirection()
// Offset: 0x281E37C
::GlobalNamespace::OffsetDirection get_offsetDirection();
// private System.Void set_offsetDirection(OffsetDirection value)
// Offset: 0x281E384
void set_offsetDirection(::GlobalNamespace::OffsetDirection value);
// public System.Int32 get_lineIndex()
// Offset: 0x281E38C
int get_lineIndex();
// private System.Void set_lineIndex(System.Int32 value)
// Offset: 0x281E394
void set_lineIndex(int value);
// public NoteLineLayer get_lineLayer()
// Offset: 0x281E39C
::GlobalNamespace::NoteLineLayer get_lineLayer();
// protected System.Void set_lineLayer(NoteLineLayer value)
// Offset: 0x281E3A4
void set_lineLayer(::GlobalNamespace::NoteLineLayer value);
// public System.Void .ctor(System.Single time, System.Int32 lineIndex, NoteLineLayer lineLayer, OffsetDirection offsetDirection)
// Offset: 0x281E43C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static WaypointData* New_ctor(float time, int lineIndex, ::GlobalNamespace::NoteLineLayer lineLayer, ::GlobalNamespace::OffsetDirection offsetDirection) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::WaypointData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<WaypointData*, creationType>(time, lineIndex, lineLayer, offsetDirection)));
}
// private System.Void MirrorTransformOffsetDirection()
// Offset: 0x281E4AC
void MirrorTransformOffsetDirection();
// public override BeatmapDataItem GetCopy()
// Offset: 0x281E3AC
// Implemented from: BeatmapDataItem
// Base method: BeatmapDataItem BeatmapDataItem::GetCopy()
::GlobalNamespace::BeatmapDataItem* GetCopy();
// public override System.Void Mirror(System.Int32 lineCount)
// Offset: 0x281E498
// Implemented from: BeatmapObjectData
// Base method: System.Void BeatmapObjectData::Mirror(System.Int32 lineCount)
void Mirror(int lineCount);
}; // WaypointData
#pragma pack(pop)
static check_size<sizeof(WaypointData), 40 + sizeof(::GlobalNamespace::NoteLineLayer)> __GlobalNamespace_WaypointDataSizeCheck;
static_assert(sizeof(WaypointData) == 0x2C);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::get_offsetDirection
// Il2CppName: get_offsetDirection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::OffsetDirection (GlobalNamespace::WaypointData::*)()>(&GlobalNamespace::WaypointData::get_offsetDirection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "get_offsetDirection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::set_offsetDirection
// Il2CppName: set_offsetDirection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::WaypointData::*)(::GlobalNamespace::OffsetDirection)>(&GlobalNamespace::WaypointData::set_offsetDirection)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("", "OffsetDirection")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "set_offsetDirection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::get_lineIndex
// Il2CppName: get_lineIndex
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::WaypointData::*)()>(&GlobalNamespace::WaypointData::get_lineIndex)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "get_lineIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::set_lineIndex
// Il2CppName: set_lineIndex
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::WaypointData::*)(int)>(&GlobalNamespace::WaypointData::set_lineIndex)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "set_lineIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::get_lineLayer
// Il2CppName: get_lineLayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::NoteLineLayer (GlobalNamespace::WaypointData::*)()>(&GlobalNamespace::WaypointData::get_lineLayer)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "get_lineLayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::set_lineLayer
// Il2CppName: set_lineLayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::WaypointData::*)(::GlobalNamespace::NoteLineLayer)>(&GlobalNamespace::WaypointData::set_lineLayer)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("", "NoteLineLayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "set_lineLayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::MirrorTransformOffsetDirection
// Il2CppName: MirrorTransformOffsetDirection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::WaypointData::*)()>(&GlobalNamespace::WaypointData::MirrorTransformOffsetDirection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "MirrorTransformOffsetDirection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::GetCopy
// Il2CppName: GetCopy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::BeatmapDataItem* (GlobalNamespace::WaypointData::*)()>(&GlobalNamespace::WaypointData::GetCopy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "GetCopy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::WaypointData::Mirror
// Il2CppName: Mirror
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::WaypointData::*)(int)>(&GlobalNamespace::WaypointData::Mirror)> {
static const MethodInfo* get() {
static auto* lineCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::WaypointData*), "Mirror", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{lineCount});
}
};
| 53.326633 | 202 | 0.74199 | RedBrumbler |
86b507e1b770148c9724552ec70a16a269e859a1 | 15,471 | cpp | C++ | SpatialGDK/Source/SpatialGDK/Private/LoadBalancing/LayeredLBStrategy.cpp | cyberbibby/UnrealGDK | 9502a1ba11d21b3cb64978ba7ea178c63371cdd0 | [
"MIT"
] | null | null | null | SpatialGDK/Source/SpatialGDK/Private/LoadBalancing/LayeredLBStrategy.cpp | cyberbibby/UnrealGDK | 9502a1ba11d21b3cb64978ba7ea178c63371cdd0 | [
"MIT"
] | null | null | null | SpatialGDK/Source/SpatialGDK/Private/LoadBalancing/LayeredLBStrategy.cpp | cyberbibby/UnrealGDK | 9502a1ba11d21b3cb64978ba7ea178c63371cdd0 | [
"MIT"
] | null | null | null | // Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "LoadBalancing/LayeredLBStrategy.h"
#include "EngineClasses/SpatialNetDriver.h"
#include "EngineClasses/SpatialWorldSettings.h"
#include "LoadBalancing/GridBasedLBStrategy.h"
#include "Schema/ActorGroupMember.h"
#include "Utils/LayerInfo.h"
#include "Utils/SpatialActorUtils.h"
#include "Templates/Tuple.h"
DEFINE_LOG_CATEGORY(LogLayeredLBStrategy);
DEFINE_VTABLE_PTR_HELPER_CTOR(ULayeredLBStrategy);
ULayeredLBStrategy::ULayeredLBStrategy()
: Super()
{
}
ULayeredLBStrategy::~ULayeredLBStrategy() = default;
FString ULayeredLBStrategy::ToString() const
{
const FName LocalLayerName = GetLocalLayerName();
const UAbstractLBStrategy* const* LBStrategy = LayerNameToLBStrategy.Find(LocalLayerName);
FString Description =
FString::Printf(TEXT("Layered, LocalLayerName = %s, LocalVirtualWorkerId = %d, LayerStrategy = %s"), *LocalLayerName.ToString(),
LocalVirtualWorkerId, *LBStrategy ? *(*LBStrategy)->ToString() : TEXT("NoStrategy"));
if (VirtualWorkerIdToLayerName.Num() > 0)
{
Description += TEXT(", LayerNamesPerVirtualWorkerId = {");
for (const auto& Entry : VirtualWorkerIdToLayerName)
{
Description += FString::Printf(TEXT("%d = %s, "), Entry.Key, *Entry.Value.ToString());
}
if (ensureAlwaysMsgf(Description.Len() > 1, TEXT("Load balancing strategy description should be more than 1 character in length")))
{
Description.LeftChopInline(2);
Description += TEXT("}");
}
}
return Description;
}
void ULayeredLBStrategy::SetLayers(TArray<FLayerInfo>& WorkerLayers)
{
check(WorkerLayers.Num() != 0);
// For each Layer, add a LB Strategy for that layer.
for (int32 LayerIndex = 0; LayerIndex < WorkerLayers.Num(); ++LayerIndex)
{
FLayerInfo& LayerInfo = WorkerLayers[LayerIndex];
if (*LayerInfo.LoadBalanceStrategy == nullptr)
{
UE_LOG(LogLayeredLBStrategy, Error,
TEXT("WorkerLayer %s does not specify a load balancing strategy (or it cannot be resolved). Using default layer."),
*LayerInfo.Name.ToString());
LayerInfo.LoadBalanceStrategy = UAbstractSpatialMultiWorkerSettings::GetDefaultLayerInfo().LoadBalanceStrategy;
}
checkf(*LayerInfo.LoadBalanceStrategy != nullptr,
TEXT("WorkerLayer %s does not specify a load balancing strategy (or it cannot be resolved)"), *LayerInfo.Name.ToString());
UE_LOG(LogLayeredLBStrategy, Log, TEXT("Creating LBStrategy for Layer %s."), *LayerInfo.Name.ToString());
AddStrategyForLayer(LayerInfo.Name, NewObject<UAbstractLBStrategy>(this, LayerInfo.LoadBalanceStrategy));
for (const TSoftClassPtr<AActor>& ClassPtr : LayerInfo.ActorClasses)
{
UE_LOG(LogLayeredLBStrategy, Log, TEXT(" - Adding class %s."), *ClassPtr.GetAssetName());
ClassPathToLayerName.Emplace(ClassPtr, LayerInfo.Name);
}
LayerData.Emplace(LayerInfo.Name, FLayerData{ LayerInfo.Name, LayerIndex });
}
}
void ULayeredLBStrategy::SetLocalVirtualWorkerId(VirtualWorkerId InLocalVirtualWorkerId)
{
if (LocalVirtualWorkerId != SpatialConstants::INVALID_VIRTUAL_WORKER_ID)
{
UE_LOG(LogLayeredLBStrategy, Error,
TEXT("The Local Virtual Worker Id cannot be set twice. Current value: %d Requested new value: %d"), LocalVirtualWorkerId,
InLocalVirtualWorkerId);
return;
}
LocalVirtualWorkerId = InLocalVirtualWorkerId;
for (const auto& Elem : LayerNameToLBStrategy)
{
Elem.Value->SetLocalVirtualWorkerId(InLocalVirtualWorkerId);
}
}
TSet<VirtualWorkerId> ULayeredLBStrategy::GetVirtualWorkerIds() const
{
return TSet<VirtualWorkerId>(VirtualWorkerIds);
}
bool ULayeredLBStrategy::ShouldHaveAuthority(const AActor& Actor) const
{
if (!IsReady())
{
UE_LOG(LogLayeredLBStrategy, Warning, TEXT("LayeredLBStrategy not ready to relinquish authority for Actor %s."),
*AActor::GetDebugName(&Actor));
return false;
}
const AActor* RootOwner = &Actor;
while (RootOwner->GetOwner() != nullptr && RootOwner->GetOwner()->GetIsReplicated())
{
RootOwner = RootOwner->GetOwner();
}
const FName& LayerName = GetLayerNameForActor(*RootOwner);
if (!LayerNameToLBStrategy.Contains(LayerName))
{
UE_LOG(LogLayeredLBStrategy, Error, TEXT("LayeredLBStrategy doesn't have a LBStrategy for Actor %s which is in Layer %s."),
*AActor::GetDebugName(RootOwner), *LayerName.ToString());
return false;
}
// If this worker is not responsible for the Actor's layer, just return false.
if (VirtualWorkerIdToLayerName.Contains(LocalVirtualWorkerId) && VirtualWorkerIdToLayerName[LocalVirtualWorkerId] != LayerName)
{
return false;
}
return LayerNameToLBStrategy[LayerName]->ShouldHaveAuthority(Actor);
}
VirtualWorkerId ULayeredLBStrategy::WhoShouldHaveAuthority(const AActor& Actor) const
{
if (!IsReady())
{
UE_LOG(LogLayeredLBStrategy, Warning, TEXT("LayeredLBStrategy not ready to decide on authority for Actor %s."),
*AActor::GetDebugName(&Actor));
return SpatialConstants::INVALID_VIRTUAL_WORKER_ID;
}
const AActor* RootOwner = &Actor;
while (RootOwner->GetOwner() != nullptr && RootOwner->GetOwner()->GetIsReplicated())
{
RootOwner = RootOwner->GetOwner();
}
const FName& LayerName = GetLayerNameForActor(*RootOwner);
if (!LayerNameToLBStrategy.Contains(LayerName))
{
UE_LOG(LogLayeredLBStrategy, Error, TEXT("LayeredLBStrategy doesn't have a LBStrategy for Actor %s which is in Layer %s."),
*AActor::GetDebugName(RootOwner), *LayerName.ToString());
return SpatialConstants::INVALID_VIRTUAL_WORKER_ID;
}
const VirtualWorkerId ReturnedWorkerId = LayerNameToLBStrategy[LayerName]->WhoShouldHaveAuthority(*RootOwner);
if (ReturnedWorkerId != SpatialConstants::INVALID_VIRTUAL_WORKER_ID)
{
UE_LOG(LogLayeredLBStrategy, Log, TEXT("LayeredLBStrategy returning virtual worker id %d for Actor %s."), ReturnedWorkerId,
*AActor::GetDebugName(RootOwner));
}
return ReturnedWorkerId;
}
SpatialGDK::FActorLoadBalancingGroupId ULayeredLBStrategy::GetActorGroupId(const AActor& Actor) const
{
const FName ActorLayerName = GetLayerNameForActor(Actor);
const int32 ActorLayerIndex = LayerData.FindChecked(ActorLayerName).LayerIndex + 1;
// We're not going deeper inside nested strategies intentionally; LBStrategy, or nesting thereof,
// won't exist when the Strategy Worker is finished, and GroupIDs are only necessary for it to work.
return ActorLayerIndex;
}
SpatialGDK::QueryConstraint ULayeredLBStrategy::GetWorkerInterestQueryConstraint(const VirtualWorkerId VirtualWorker) const
{
if (!VirtualWorkerIdToLayerName.Contains(VirtualWorker))
{
UE_LOG(LogLayeredLBStrategy, Error, TEXT("LayeredLBStrategy doesn't have a LBStrategy for worker %d."), VirtualWorker);
SpatialGDK::QueryConstraint Constraint;
Constraint.ComponentConstraint = 0;
return Constraint;
}
const FName& LayerName = VirtualWorkerIdToLayerName[VirtualWorker];
check(LayerNameToLBStrategy.Contains(LayerName));
return LayerNameToLBStrategy[LayerName]->GetWorkerInterestQueryConstraint(VirtualWorker);
}
bool ULayeredLBStrategy::RequiresHandoverData() const
{
for (const auto& Elem : LayerNameToLBStrategy)
{
if (Elem.Value->RequiresHandoverData())
{
return true;
}
}
return false;
}
FVector ULayeredLBStrategy::GetWorkerEntityPosition() const
{
if (!ensureAlwaysMsgf(IsReady(), TEXT("Called GetWorkerEntityPosition before load balancing strategy was ready")))
{
return FVector::ZeroVector;
}
if (!VirtualWorkerIdToLayerName.Contains(LocalVirtualWorkerId))
{
UE_LOG(LogLayeredLBStrategy, Error, TEXT("LayeredLBStrategy doesn't have a LBStrategy for worker %d."), LocalVirtualWorkerId);
return FVector::ZeroVector;
}
const FName& LayerName = VirtualWorkerIdToLayerName[LocalVirtualWorkerId];
if (!ensureAlwaysMsgf(LayerNameToLBStrategy.Contains(LayerName),
TEXT("Called GetWorkerEntityPosition but couldn't find layer %s in local map"), *LayerName.ToString()))
{
return FVector::ZeroVector;
}
return LayerNameToLBStrategy[LayerName]->GetWorkerEntityPosition();
}
uint32 ULayeredLBStrategy::GetMinimumRequiredWorkers() const
{
// The MinimumRequiredWorkers for this strategy is a sum of the required workers for each of the wrapped strategies.
uint32 MinimumRequiredWorkers = 0;
for (const auto& Elem : LayerNameToLBStrategy)
{
MinimumRequiredWorkers += Elem.Value->GetMinimumRequiredWorkers();
}
UE_LOG(LogLayeredLBStrategy, Verbose, TEXT("LayeredLBStrategy needs %d workers to support all layer strategies."),
MinimumRequiredWorkers);
return MinimumRequiredWorkers;
}
void ULayeredLBStrategy::SetVirtualWorkerIds(const VirtualWorkerId& FirstVirtualWorkerId, const VirtualWorkerId& LastVirtualWorkerId)
{
// If the LayeredLBStrategy wraps { SingletonStrategy, 2x2 grid, Singleton } and is given IDs 1 through 6 it will assign:
// Singleton : 1
// Grid : 2 - 5
// Singleton: 6
VirtualWorkerId NextWorkerIdToAssign = FirstVirtualWorkerId;
for (const auto& Elem : LayerNameToLBStrategy)
{
UAbstractLBStrategy* LBStrategy = Elem.Value;
VirtualWorkerId MinimumRequiredWorkers = LBStrategy->GetMinimumRequiredWorkers();
VirtualWorkerId LastVirtualWorkerIdToAssign = NextWorkerIdToAssign + MinimumRequiredWorkers - 1;
if (LastVirtualWorkerIdToAssign > LastVirtualWorkerId)
{
UE_LOG(LogLayeredLBStrategy, Error,
TEXT("LayeredLBStrategy was not given enough VirtualWorkerIds to meet the demands of the layer strategies."));
return;
}
UE_LOG(LogLayeredLBStrategy, Log, TEXT("LayeredLBStrategy assigning VirtualWorkerIds %d to %d to Layer %s"), NextWorkerIdToAssign,
LastVirtualWorkerIdToAssign, *Elem.Key.ToString());
LBStrategy->SetVirtualWorkerIds(NextWorkerIdToAssign, LastVirtualWorkerIdToAssign);
for (VirtualWorkerId id = NextWorkerIdToAssign; id <= LastVirtualWorkerIdToAssign; id++)
{
VirtualWorkerIdToLayerName.Add(id, Elem.Key);
}
NextWorkerIdToAssign += MinimumRequiredWorkers;
}
// Keep a copy of the VirtualWorkerIds. This is temporary and will be removed in the next PR.
for (VirtualWorkerId CurrentVirtualWorkerId = FirstVirtualWorkerId; CurrentVirtualWorkerId <= LastVirtualWorkerId;
CurrentVirtualWorkerId++)
{
VirtualWorkerIds.Add(CurrentVirtualWorkerId);
}
}
// DEPRECATED
// This is only included because Scavengers uses the function in SpatialStatics that calls this.
// Once they are pick up this code, they should be able to switch to another method and we can remove this.
bool ULayeredLBStrategy::CouldHaveAuthority(const TSubclassOf<AActor> Class) const
{
if (!ensureAlwaysMsgf(IsReady(), TEXT("Called CouldHaveAuthority before load balancing strategy was ready")))
{
return false;
}
return *VirtualWorkerIdToLayerName.Find(LocalVirtualWorkerId) == GetLayerNameForClass(Class);
}
UAbstractLBStrategy* ULayeredLBStrategy::GetDefaultStrategy() const
{
return GetLBStrategyForLayer(SpatialConstants::DefaultLayer);
}
UAbstractLBStrategy* ULayeredLBStrategy::GetLBStrategyForVisualRendering() const
{
// The default strategy is guaranteed to exist as long as the strategy is ready.
if (!ensureAlwaysMsgf(
LayerNameToLBStrategy.Contains(SpatialConstants::DefaultLayer),
TEXT("Load balancing strategy does not contain default layer which is needed to render worker debug visualization. "
"Default layer presence should be enforced by MultiWorkerSettings edit validation. Class: %s"),
*GetNameSafe(this)))
{
return nullptr;
}
return GetLBStrategyForLayer(SpatialConstants::DefaultLayer);
}
UAbstractLBStrategy* ULayeredLBStrategy::GetLBStrategyForLayer(FName Layer) const
{
// Editor has the option to display the load balanced zones and could query the strategy anytime.
#ifndef WITH_EDITOR
if (!ensureAlwaysMsgf(IsReady(), TEXT("Called GetLBStrategyForLayer before load balancing strategy was ready")))
{
return nullptr;
}
#endif
if (UAbstractLBStrategy* const* Entry = LayerNameToLBStrategy.Find(Layer))
{
return *Entry;
}
UE_LOG(LogLayeredLBStrategy, Warning, TEXT("No strategy exists for layer %s"), *Layer.ToString());
return nullptr;
}
FName ULayeredLBStrategy::GetLocalLayerName() const
{
if (!IsReady())
{
UE_LOG(LogLayeredLBStrategy, Error, TEXT("Tried to get worker layer name before the load balancing strategy was ready."));
return NAME_None;
}
const FName* LocalLayerName = VirtualWorkerIdToLayerName.Find(LocalVirtualWorkerId);
if (LocalLayerName == nullptr)
{
UE_LOG(LogLayeredLBStrategy, Error, TEXT("Load balancing strategy didn't contain mapping between virtual worker ID to layer name."),
LocalVirtualWorkerId);
return NAME_None;
}
return *LocalLayerName;
}
FName ULayeredLBStrategy::GetLayerNameForClass(const TSubclassOf<AActor> Class) const
{
if (Class == nullptr)
{
return NAME_None;
}
UClass* FoundClass = Class;
TSoftClassPtr<AActor> ClassPtr = TSoftClassPtr<AActor>(FoundClass);
while (FoundClass != nullptr && FoundClass->IsChildOf(AActor::StaticClass()))
{
if (const FName* Layer = ClassPathToLayerName.Find(ClassPtr))
{
const FName LayerHolder = *Layer;
if (FoundClass != Class)
{
ClassPathToLayerName.Add(TSoftClassPtr<AActor>(Class), LayerHolder);
}
return LayerHolder;
}
FoundClass = FoundClass->GetSuperClass();
ClassPtr = TSoftClassPtr<AActor>(FoundClass);
}
// No mapping found so set and return default actor group.
ClassPathToLayerName.Emplace(TSoftClassPtr<AActor>(Class), SpatialConstants::DefaultLayer);
return SpatialConstants::DefaultLayer;
}
bool ULayeredLBStrategy::IsSameWorkerType(const AActor* ActorA, const AActor* ActorB) const
{
if (ActorA == nullptr || ActorB == nullptr)
{
return false;
}
return GetLayerNameForClass(ActorA->GetClass()) == GetLayerNameForClass(ActorB->GetClass());
}
FName ULayeredLBStrategy::GetLayerNameForActor(const AActor& Actor) const
{
return GetLayerNameForClass(Actor.GetClass());
}
void ULayeredLBStrategy::AddStrategyForLayer(const FName& LayerName, UAbstractLBStrategy* LBStrategy)
{
LayerNameToLBStrategy.Add(LayerName, LBStrategy);
LayerNameToLBStrategy[LayerName]->Init();
}
void ULayeredLBStrategy::GetLegacyLBInformation(FLegacyLBContext& Ctx) const
{
if (!IsStrategyWorkerAware())
{
return;
}
TArray<FName> LayerNames;
LayerNames.SetNum(LayerNameToLBStrategy.Num());
for (const auto& Data : LayerData)
{
LayerNames[Data.Value.LayerIndex] = Data.Key;
}
for (FName& LayerName : LayerNames)
{
Ctx.Layers.AddDefaulted();
Ctx.Layers.Last().Name = LayerName;
const UAbstractLBStrategy* Strategy = LayerNameToLBStrategy.FindChecked(LayerName);
Strategy->GetLegacyLBInformation(Ctx);
}
}
bool ULayeredLBStrategy::IsStrategyWorkerAware() const
{
for (auto Entry : LayerNameToLBStrategy)
{
if (!Entry.Value->IsA<UGridBasedLBStrategy>() || !Entry.Value->IsStrategyWorkerAware())
{
return false;
}
}
return true;
}
TArray<SpatialGDK::ComponentData> ULayeredLBStrategy::CreateStaticLoadBalancingData(const AActor& Actor) const
{
TArray<SpatialGDK::ComponentData> ComponentData;
if (IsStrategyWorkerAware())
{
FName LayerName = GetLayerNameForActor(Actor);
uint32 LayerIndex = LayerData.FindChecked(LayerName).LayerIndex;
// Force all unique actor class actors to run on worker auth over snapshot entities
if (FUnrealObjectRef::IsUniqueActorClass(Actor.GetClass()))
{
LayerIndex = SpatialConstants::LAYER_TO_RUN_ON_WORKER_AUTH_OVER_SNAPSHOT_PARTITION;
}
SpatialGDK::ActorGroupMember MembershipComponent(LayerIndex);
ComponentData.Add(MembershipComponent.CreateComponentData());
}
return ComponentData;
}
| 33.487013 | 134 | 0.772348 | cyberbibby |
86bfb1f48e1281c8f0419c41566e0bbb4a7e6b19 | 1,660 | cpp | C++ | LeetCodeCPP/_1177. Can Make Palindrome from Substring/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | 1 | 2019-03-29T03:33:56.000Z | 2019-03-29T03:33:56.000Z | LeetCodeCPP/_1177. Can Make Palindrome from Substring/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | LeetCodeCPP/_1177. Can Make Palindrome from Substring/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// _1177. Can Make Palindrome from Substring
//
// Created by admin on 2019/9/5.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <bitset>
#include <vector>
using namespace std;
class Solution {
public:
vector<bool> canMakePaliQueries1(string s, vector<vector<int>>& queries) {
int m=s.size();
int n=queries.size();
vector<vector<bool>> helper(m+1,vector<bool>(26,false));
for(int i=0;i<m;i++){
helper[i+1].assign(helper[i].begin(),helper[i].end());
helper[i+1][s[i]-'a']=helper[i+1][s[i]-'a']^true;
}
vector<bool> ret;
for(auto q:queries){
int sum=0;
for(int i=0;i<26;i++){
sum+=(helper[q[1]+1][i]^helper[q[0]][i]);
}
ret.push_back(sum/2<=q[2]);
}
return ret;
}
vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) {
int mask = 0;
vector<int> ps(1,0);
for (char c : s)
ps.push_back(mask ^= 1 << (c - 'a'));
vector<bool> r;
for (auto &q : queries) {
int odds =bitset<32>(ps[q[1] + 1] ^ ps[q[0]]).count();
r.push_back(q[2]>= odds/2);
}
return r;
}
};
int main(int argc, const char * argv[]) {
string input1="abcda";
vector<vector<int>> input2={{3,3,0},{1,2,0},{0,3,1},{0,3,2},{0,4,1}};
Solution so=Solution();
vector<bool> ret=so.canMakePaliQueries(input1, input2);
for(auto r:ret){
cout<<r<<" ";
}
cout<<endl;
return 0;
}
| 25.151515 | 78 | 0.496988 | 18600130137 |
86c44bd72de8914c743ad3106ff5cc9d4a4d7a83 | 8,390 | hpp | C++ | src/polynomials/include/boost_polynomials.hpp | dkavolis/polynomials | 10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0 | [
"MIT"
] | null | null | null | src/polynomials/include/boost_polynomials.hpp | dkavolis/polynomials | 10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0 | [
"MIT"
] | null | null | null | src/polynomials/include/boost_polynomials.hpp | dkavolis/polynomials | 10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2022 <Daumantas Kavolis>
*
* 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 "config.hpp"
MSVC_WARNING_DISABLE(4619)
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/chebyshev.hpp>
#include <boost/math/special_functions/hermite.hpp>
#include <boost/math/special_functions/laguerre.hpp>
#include <boost/math/special_functions/legendre.hpp>
#include <boost/math/special_functions/legendre_stieltjes.hpp>
MSVC_WARNING_POP()
#include "quadrature.hpp"
namespace poly {
namespace detail {
template <typename Integral>
struct BasicImpl {
using OrderType = Integral;
using Storage = Integral;
constexpr static inline bool is_trivial = true;
static auto make_storage(OrderType order = 0) noexcept -> Storage { return order; }
static auto get_order(Storage const& item) noexcept -> OrderType { return item; }
static void set_order(Storage& item, OrderType const& value) noexcept { item = value; }
};
} // namespace detail
template <typename Real_, unsigned N = QuadraturePoints>
struct LegendreImpl : detail::BasicImpl<std::int16_t> {
using Real = Real_;
constexpr static inline bool is_orthonormal = true;
static auto eval(Storage const& item, Real x) -> Real { return boost::math::legendre_p(item, x); }
static auto prime(Storage const& item, Real x) -> Real {
return boost::math::legendre_p_prime(item, x);
}
static auto zeros(Storage const& item) -> std::vector<Real> {
using std::abs;
auto z = boost::math::legendre_p_zeros<Real>(item);
detail::reflect_in_place<detail::Reflection::Odd>(
z, abs(z[0]) < 2 * std::numeric_limits<Real>::epsilon());
return z;
}
static auto next(Storage const& item, Real x, Real Pl, Real Plm1) -> Real {
return boost::math::legendre_next(item, x, Pl, Plm1);
}
template <bool check = false>
static auto weights(Storage const& item, bounds_check<check> c = no_bounds_check)
-> view<Real const> {
return GaussQuadrature<Real, N>::weights(item + 1, c);
}
template <bool check = false>
static auto abscissa(Storage const& item, bounds_check<check> c = no_bounds_check)
-> view<Real const> {
return GaussQuadrature<Real, N>::abscissa(item + 1, c);
}
static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }
};
template <typename Real_>
struct LaguerreImpl : detail::BasicImpl<std::int16_t> {
using Real = Real_;
constexpr static inline bool is_orthonormal = true;
static auto eval(Storage const& item, Real x) -> Real { return boost::math::laguerre(item, x); }
static auto next(Storage const& item, Real x, Real Pl, Real Plm1) -> Real {
return boost::math::laguerre_next(item, x, Pl, Plm1);
}
static auto domain() -> std::pair<Real, Real> { return {0, 1}; }
};
template <typename Real_>
struct HermiteImpl : detail::BasicImpl<std::uint16_t> {
using Real = Real_;
constexpr static inline bool is_orthonormal = true;
static auto eval(Storage const& item, Real x) -> Real { return boost::math::hermite(item, x); }
static auto next(Storage const& item, Real x, Real Pl, Real Plm1) -> Real {
return boost::math::hermite_next(item, x, Pl, Plm1);
}
static auto domain() -> std::pair<Real, Real> {
return {-std::numeric_limits<Real>::infinity(), std::numeric_limits<Real>::infinity()};
}
};
template <typename, unsigned>
struct ChebyshevImpl;
namespace detail {
template <typename Real, unsigned N = QuadraturePoints>
struct ChebyshevQuadrature {
static auto abscissa() -> view<Real const> {
static std::vector<Real> v = ChebyshevImpl<Real, N>::zeros({N});
return {v.data(), v.size()};
}
static auto weights() -> view<Real const> {
static std::vector<Real> v(std::size_t(N), boost::math::constants::pi<Real>() / N);
return {v.data(), v.size()};
}
};
} // namespace detail
template <typename Real, unsigned N = QuadraturePoints>
using ChebyshevQuadrature = detail::Quadrature<Real, detail::ChebyshevQuadrature, N, false>;
template <typename Real_, unsigned N = QuadraturePoints>
struct ChebyshevImpl : detail::BasicImpl<std::int16_t> {
using Real = Real_;
constexpr static inline bool is_orthonormal = true;
static auto eval(Storage const& item, Real x) -> Real {
return boost::math::chebyshev_t(item, x);
}
static auto prime(Storage const& item, Real x) -> Real {
return boost::math::chebyshev_t_prime(item, x);
}
static auto next(Storage const& /* unused */, Real x, Real Pl, Real Plm1) -> Real {
return boost::math::chebyshev_next(x, Pl, Plm1);
}
static auto zeros(Storage const& item) -> std::vector<Real> {
using std::cos;
std::vector<Real> values(item, 0);
Real factor{boost::math::constants::pi<Real>() / 2.0 / item};
auto half = item / 2;
auto start = (item + 1) / 2;
for (OrderType i = 0; i < half; ++i) {
Real x = cos((2 * (start + i) + 1) * factor);
values[start + i] = -x;
values[half - i - 1] = x;
}
return values;
}
template <bool check = false>
static auto weights(Storage const& item, bounds_check<check> c = no_bounds_check)
-> view<Real const> {
return ChebyshevQuadrature<Real, N>::weights(item + 1, c);
}
template <bool check = false>
static auto abscissa(Storage const& item, bounds_check<check> c = no_bounds_check)
-> view<Real const> {
return ChebyshevQuadrature<Real, N>::abscissa(item + 1, c);
}
static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }
};
template <typename Real_>
struct LegendreStieltjesImpl {
using Real = Real_;
using OrderType = std::int16_t;
constexpr static inline bool is_orthonormal = true;
class Storage {
public:
explicit Storage(OrderType m) : polynomial{m}, order{m} {};
private:
boost::math::legendre_stieltjes<Real> polynomial;
OrderType order;
template <class>
friend struct LegendreStieltjesImpl;
};
static auto make_storage(OrderType order = 0) noexcept -> Storage { return Storage{order}; }
static auto get_order(Storage const& item) noexcept -> OrderType { return item.order; }
static void set_order(Storage& item, OrderType const& value) noexcept { item = Storage{value}; }
static auto eval(Storage const& item, Real x) -> Real { return item.polynomial(x); }
static auto prime(Storage const& item, Real x) -> Real { return item.polynomial.prime(x); }
static auto zeros(Storage const& item) -> std::vector<Real> {
auto vector = item.polynomial.zeros();
detail::reflect_in_place<detail::Reflection::Odd>(vector, vector[0] == 0);
return vector;
}
static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }
};
template <typename Real_, unsigned N = QuadraturePoints>
struct GaussKronrodImpl : detail::BasicImpl<std::int16_t> {
using Real = Real_;
constexpr static inline bool is_orthonormal = true;
template <bool check = false>
static auto weights(Storage const& item, bounds_check<check> c = no_bounds_check)
-> view<Real const> {
return GaussKronrodQuadrature<Real, N>::weights(item, c);
}
template <bool check = false>
static auto abscissa(Storage const& item, bounds_check<check> c = no_bounds_check)
-> view<Real const> {
return GaussKronrodQuadrature<Real, N>::abscissa(item, c);
}
static auto domain() -> std::pair<Real, Real> { return {-1, 1}; }
};
} // namespace poly
| 36.960352 | 100 | 0.695948 | dkavolis |
86c5310383f15976dd3059284daa756cf30d7cc0 | 3,919 | hpp | C++ | odeint/border/element_border.hpp | hmito/hmLib | 0f2515ba9c99c06d02e2fa633eeae73bcd793983 | [
"MIT"
] | null | null | null | odeint/border/element_border.hpp | hmito/hmLib | 0f2515ba9c99c06d02e2fa633eeae73bcd793983 | [
"MIT"
] | null | null | null | odeint/border/element_border.hpp | hmito/hmLib | 0f2515ba9c99c06d02e2fa633eeae73bcd793983 | [
"MIT"
] | 1 | 2015-09-22T03:32:11.000Z | 2015-09-22T03:32:11.000Z | #ifndef HMLIB_ODEINT_BORDER_ELEMENTBORDER_INC
#define HMLIB_ODEINT_BORDER_ELEMENTBORDER_INC 100
#
#include <functional>
#include <boost/range.hpp>
namespace hmLib {
namespace odeint {
template<typename value_type>
struct lower_border {
public:
lower_border() = default;
lower_border(size_t pos_, value_type value_) :pos(pos_), value(value_) {}
void set(size_t pos_, value_type value_) {
pos = pos_;
value = value_;
}
public:
template<typename state_type>
void force_zero_deriv(state_type& dx, bool ap)const {
if (ap) {
*std::next(boost::begin(dx), pos) = 0;
}
}
template<typename state_type, typename time_type>
bool operator()(const state_type& x, state_type& dx, time_type t, bool ap)const {
if (ap && *std::next(boost::begin(dx), pos) < 0) {
*std::next(boost::begin(dx), pos) = 0;
return true;
}
return false;
}
template<typename state_type, typename time_type>
bool is_invalid_step(const state_type& x, const state_type& dx, time_type t, bool ap)const {
if (ap) {
return *std::next(boost::begin(dx), pos) > 0;
}
else {
return *std::next(boost::begin(x), pos) < value;
}
}
template<typename state_type, typename time_type>
bool will_validate(const state_type& x, time_type t, bool ap)const {
return (*std::next(boost::begin(x), pos) < value);
}
template<typename state_type, typename time_type>
bool validate(state_type& x, const state_type& dx, time_type t, bool& ap)const {
bool ans = false;
if (ap) {
if (*std::next(boost::begin(x), pos) < value) {
ans = true;
*std::next(boost::begin(x), pos) = value;
}
ap = (*std::next(boost::begin(dx), pos) <= 0);
}
else {
if (*std::next(boost::begin(x), pos) < value) {
ans = true;
*std::next(boost::begin(x), pos) = value;
ap = (*std::next(boost::begin(dx), pos) <= 0);
}
else {
ap = false;
}
}
return ans;
}
private:
size_t pos;
value_type value;
};
template<typename value_type>
struct upper_border {
public:
upper_border() = default;
upper_border(size_t pos_, value_type value_) :pos(pos_), value(value_) {}
void set(size_t pos_, value_type value_) {
pos = pos_;
value = value_;
}
public:
template<typename state_type>
void force_zero_deriv(state_type& dx, bool ap)const {
if (ap) {
*std::next(boost::begin(dx), pos) = 0;
}
}
template<typename state_type, typename time_type>
bool operator()(const state_type& x, state_type& dx, time_type t, bool ap)const {
if (ap && *std::next(boost::begin(dx), pos) > 0) {
*std::next(boost::begin(dx), pos) = 0;
return true;
}
return false;
}
template<typename state_type, typename time_type>
bool is_invalid_step(const state_type& x, const state_type& dx, time_type t, bool ap)const {
if (ap) {
return *std::next(boost::begin(dx), pos) < 0;
}
else {
return *std::next(boost::begin(x), pos) > value;
}
}
template<typename state_type, typename time_type>
bool will_validate(const state_type& x, time_type t, bool ap)const {
return (*std::next(boost::begin(x), pos) > value);
}
template<typename state_type, typename time_type>
bool validate(state_type& x, const state_type& dx, time_type t, bool& ap)const {
bool ans = false;
if (ap) {
if (*std::next(boost::begin(x), pos) > value) {
ans = true;
*std::next(boost::begin(x), pos) = value;
}
ap = (*std::next(boost::begin(dx), pos) >= 0);
}
else {
if (*std::next(boost::begin(x), pos) > value) {
ans = true;
*std::next(boost::begin(x), pos) = value;
ap = (*std::next(boost::begin(dx), pos) >= 0);
}
else {
ap = false;
}
}
return ans;
}
private:
size_t pos;
value_type value;
};
}
}
#
#endif
| 26.842466 | 95 | 0.609339 | hmito |
86c6206360f2ecc6fd716d82985a42d8bf85b37a | 1,176 | cpp | C++ | cpp/441-450/Number of Boomerangs.cpp | KaiyuWei/leetcode | fd61f5df60cfc7086f7e85774704bacacb4aaa5c | [
"MIT"
] | 150 | 2015-04-04T06:53:49.000Z | 2022-03-21T13:32:08.000Z | cpp/441-450/Number of Boomerangs.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 1 | 2015-04-13T15:15:40.000Z | 2015-04-21T20:23:16.000Z | cpp/441-450/Number of Boomerangs.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 64 | 2015-06-30T08:00:07.000Z | 2022-01-01T16:44:14.000Z | class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int res = 0;
// iterate over all the points
for (int i = 0; i < points.size(); ++i) {
unordered_map<long, int> group;
// iterate over all points other than points[i]
for (int j = 0; j < points.size(); ++j) {
if (j == i) continue;
int dy = points[i].second - points[j].second;
int dx = points[i].first - points[j].first;
// compute squared euclidean distance from points[i]
int key = dy * dy + dx * dx;
// accumulate # of such "j"s that are "key" distance from "i"
++group[key];
}
for (auto& p : group) {
if (p.second > 1) {
/*
* for all the groups of points,
* number of ways to select 2 from n =
* nP2 = n!/(n - 2)! = n * (n - 1)
*/
res += p.second * (p.second - 1);
}
}
}
return res;
}
};
| 28.682927 | 77 | 0.406463 | KaiyuWei |
86c721c5736573b18c65b31aeff87d68007eefab | 1,397 | cpp | C++ | ComplitaionLinux/OC_stage2.cpp | Picrik/GameDevC- | ddc46b60605da490e9bfaf838ef7ef3ee0757eb1 | [
"MIT"
] | null | null | null | ComplitaionLinux/OC_stage2.cpp | Picrik/GameDevC- | ddc46b60605da490e9bfaf838ef7ef3ee0757eb1 | [
"MIT"
] | null | null | null | ComplitaionLinux/OC_stage2.cpp | Picrik/GameDevC- | ddc46b60605da490e9bfaf838ef7ef3ee0757eb1 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int ajouteDeux(int nombreRecu)
{
int valeur(nombreRecu +2);
return valeur;
}
void direBonjour()
{
cout << "dire bonjour" << endl;
}
int main()
{
int a(4), b(5);
cout << "a vaut : " << a << " et be vaut :" << b << endl;
cout << "affectaton" << endl;
a = b;
cout << "a vaut : " << a << " et be vaut" << b << endl;
//changement de valeur;
a = 6;
cout << "a vaut : " << a << " et b vaut : " << b << endl;
cout << "Quel age avez-vous ?" << endl;
int ageUtilisateur(0); // préparation de la place mémoire
cin >> ageUtilisateur; // Reception de la valeur
cout << "Vous avez " << ageUtilisateur << " ans !" << endl; // Et on affiche la réponse
int nombreEnfant(0);
cout << "Combien d'enfants avez vous ?" << endl;
cin >> nombreEnfant;
if (nombreEnfant == 1)
{
cout << "vous avez " << nombreEnfant << " enfant" << endl;
}
else if (nombreEnfant > 1)
{
cout << "vous avez " << nombreEnfant << " enfants" << endl;
}
else
{
cout << "vous n'avez pas d'enfants" <<endl;
}
// cout<< "vous avez " << nombreEnfant << " enfant";
int compteur(0);
for (compteur = 0; compteur < 10; ++compteur)
{
cout << compteur << endl;
}
cout << ajouteDeux(3) << endl;
direBonjour();
return 0;
} | 18.878378 | 91 | 0.518969 | Picrik |
f866f21894d93c951f0a51d201a1c9291bb5afbf | 88 | cpp | C++ | engine/source/PADO/PADO_Component.cpp | Goldenbough44/PADO | a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6 | [
"MIT"
] | 1 | 2021-08-13T04:39:53.000Z | 2021-08-13T04:39:53.000Z | engine/source/PADO/PADO_Component.cpp | Goldenbough44/PADO | a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6 | [
"MIT"
] | 2 | 2021-08-13T04:49:02.000Z | 2022-03-25T19:20:56.000Z | engine/source/PADO/PADO_Component.cpp | Goldenbough44/PADO | a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6 | [
"MIT"
] | null | null | null | //
// (c) 2019 Highwater Games Co. All Rights Reserved.
//
#include "PADO_Component.h"
| 14.666667 | 52 | 0.681818 | Goldenbough44 |
f8698d0b28282e76ad0465d9a04f96f3150c0baa | 1,861 | cpp | C++ | src/bin/exrmaketiled/Image.cpp | remia/openexr | 566087f13259f4429d55125d1001b2696ac2bfc3 | [
"BSD-3-Clause"
] | 587 | 2015-01-04T09:56:19.000Z | 2019-11-21T13:23:33.000Z | third_party/openexr-672c77d7c923402f549371e08b39ece4552cbb85/src/bin/exrmaketiled/Image.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | 360 | 2015-01-04T10:55:17.000Z | 2019-11-21T16:37:22.000Z | third_party/openexr-672c77d7c923402f549371e08b39ece4552cbb85/src/bin/exrmaketiled/Image.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | 297 | 2015-01-11T12:06:42.000Z | 2019-11-19T21:59:57.000Z | //
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
//----------------------------------------------------------------------------
//
// Classes for storing OpenEXR images in memory.
//
//----------------------------------------------------------------------------
#include "Image.h"
#include "namespaceAlias.h"
#include <Iex.h>
using namespace IMF;
using namespace IMATH_NAMESPACE;
using namespace std;
ImageChannel::ImageChannel (Image& image) : _image (image)
{
// empty
}
ImageChannel::~ImageChannel ()
{
// empty
}
Image::Image () : _dataWindow (Box2i (V2i (0, 0), V2i (0, 0)))
{
// empty
}
Image::Image (const Box2i& dataWindow) : _dataWindow (dataWindow)
{
// empty
}
Image::~Image ()
{
for (ChannelMap::iterator i = _channels.begin (); i != _channels.end ();
++i)
delete i->second;
}
void
Image::resize (const IMATH_NAMESPACE::Box2i& dataWindow)
{
_dataWindow = dataWindow;
for (ChannelMap::iterator i = _channels.begin (); i != _channels.end ();
++i)
i->second->resize (width (), height ());
}
void
Image::addChannel (const string& name, PixelType type)
{
switch (type)
{
case IMF::HALF:
_channels[name] = new HalfChannel (*this, width (), height ());
break;
case IMF::FLOAT:
_channels[name] = new FloatChannel (*this, width (), height ());
break;
case IMF::UINT:
_channels[name] = new UIntChannel (*this, width (), height ());
break;
default: throw IEX_NAMESPACE::ArgExc ("Unknown channel type.");
}
}
ImageChannel&
Image::channel (const string& name)
{
return *_channels.find (name)->second;
}
const ImageChannel&
Image::channel (const string& name) const
{
return *_channels.find (name)->second;
}
| 20.910112 | 78 | 0.559377 | remia |
f86f7649896ed418d789bcfd4687a381c569e846 | 24,608 | cpp | C++ | src/EvtGenModels/EvtISGW2.cpp | qdcampagna/BTODSTARLNUNP_EVTGEN_Model | 9623a0ffe2625450a1228a80d6baae74ed6c0965 | [
"CC0-1.0"
] | null | null | null | src/EvtGenModels/EvtISGW2.cpp | qdcampagna/BTODSTARLNUNP_EVTGEN_Model | 9623a0ffe2625450a1228a80d6baae74ed6c0965 | [
"CC0-1.0"
] | null | null | null | src/EvtGenModels/EvtISGW2.cpp | qdcampagna/BTODSTARLNUNP_EVTGEN_Model | 9623a0ffe2625450a1228a80d6baae74ed6c0965 | [
"CC0-1.0"
] | null | null | null |
/***********************************************************************
* Copyright 1998-2020 CERN for the benefit of the EvtGen authors *
* *
* This file is part of EvtGen. *
* *
* EvtGen is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* EvtGen 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 EvtGen. If not, see <https://www.gnu.org/licenses/>. *
***********************************************************************/
#include "EvtGenModels/EvtISGW2.hh"
#include "EvtGenBase/EvtConst.hh"
#include "EvtGenBase/EvtGenKine.hh"
#include "EvtGenBase/EvtIdSet.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtParticle.hh"
#include "EvtGenBase/EvtPatches.hh"
#include "EvtGenBase/EvtReport.hh"
#include "EvtGenBase/EvtSemiLeptonicScalarAmp.hh"
#include "EvtGenBase/EvtSemiLeptonicTensorAmp.hh"
#include "EvtGenBase/EvtSemiLeptonicVectorAmp.hh"
#include "EvtGenModels/EvtISGW2FF.hh"
#include <stdlib.h>
#include <string>
std::string EvtISGW2::getName()
{
return "ISGW2";
}
EvtDecayBase* EvtISGW2::clone()
{
return new EvtISGW2;
}
void EvtISGW2::decay( EvtParticle* p )
{
p->initializePhaseSpace( getNDaug(), getDaugs() );
calcamp->CalcAmp( p, _amp2, isgw2ffmodel.get() );
}
void EvtISGW2::initProbMax()
{
//added by Lange Jan4,2000
static EvtId EM = EvtPDL::getId( "e-" );
static EvtId EP = EvtPDL::getId( "e+" );
static EvtId MUM = EvtPDL::getId( "mu-" );
static EvtId MUP = EvtPDL::getId( "mu+" );
static EvtId TAUM = EvtPDL::getId( "tau-" );
static EvtId TAUP = EvtPDL::getId( "tau+" );
static EvtId BP = EvtPDL::getId( "B+" );
static EvtId BM = EvtPDL::getId( "B-" );
static EvtId B0 = EvtPDL::getId( "B0" );
static EvtId B0B = EvtPDL::getId( "anti-B0" );
static EvtId BS0 = EvtPDL::getId( "B_s0" );
static EvtId BSB = EvtPDL::getId( "anti-B_s0" );
static EvtId BCP = EvtPDL::getId( "B_c+" );
static EvtId BCM = EvtPDL::getId( "B_c-" );
static EvtId DST0 = EvtPDL::getId( "D*0" );
static EvtId DSTB = EvtPDL::getId( "anti-D*0" );
static EvtId DSTP = EvtPDL::getId( "D*+" );
static EvtId DSTM = EvtPDL::getId( "D*-" );
static EvtId D0 = EvtPDL::getId( "D0" );
static EvtId D0B = EvtPDL::getId( "anti-D0" );
static EvtId DP = EvtPDL::getId( "D+" );
static EvtId DM = EvtPDL::getId( "D-" );
static EvtId D1P1P = EvtPDL::getId( "D_1+" );
static EvtId D1P1N = EvtPDL::getId( "D_1-" );
static EvtId D1P10 = EvtPDL::getId( "D_10" );
static EvtId D1P1B = EvtPDL::getId( "anti-D_10" );
static EvtId D3P2P = EvtPDL::getId( "D_2*+" );
static EvtId D3P2N = EvtPDL::getId( "D_2*-" );
static EvtId D3P20 = EvtPDL::getId( "D_2*0" );
static EvtId D3P2B = EvtPDL::getId( "anti-D_2*0" );
static EvtId D3P1P = EvtPDL::getId( "D'_1+" );
static EvtId D3P1N = EvtPDL::getId( "D'_1-" );
static EvtId D3P10 = EvtPDL::getId( "D'_10" );
static EvtId D3P1B = EvtPDL::getId( "anti-D'_10" );
static EvtId D3P0P = EvtPDL::getId( "D_0*+" );
static EvtId D3P0N = EvtPDL::getId( "D_0*-" );
static EvtId D3P00 = EvtPDL::getId( "D_0*0" );
static EvtId D3P0B = EvtPDL::getId( "anti-D_0*0" );
static EvtId D21S0P = EvtPDL::getId( "D(2S)+" );
static EvtId D21S0N = EvtPDL::getId( "D(2S)-" );
static EvtId D21S00 = EvtPDL::getId( "D(2S)0" );
static EvtId D21S0B = EvtPDL::getId( "anti-D(2S)0" );
static EvtId D23S1P = EvtPDL::getId( "D*(2S)+" );
static EvtId D23S1N = EvtPDL::getId( "D*(2S)-" );
static EvtId D23S10 = EvtPDL::getId( "D*(2S)0" );
static EvtId D23S1B = EvtPDL::getId( "anti-D*(2S)0" );
static EvtId RHO2S0 = EvtPDL::getId( "rho(2S)0" );
static EvtId RHO2SP = EvtPDL::getId( "rho(2S)+" );
static EvtId RHO2SM = EvtPDL::getId( "rho(2S)-" );
static EvtId OMEG2S = EvtPDL::getId( "omega(2S)" );
static EvtId ETA2S = EvtPDL::getId( "eta(2S)" );
static EvtId PI2S0 = EvtPDL::getId( "pi(2S)0" );
static EvtId PI2SP = EvtPDL::getId( "pi(2S)+" );
static EvtId PI2SM = EvtPDL::getId( "pi(2S)-" );
static EvtId PIP = EvtPDL::getId( "pi+" );
static EvtId PIM = EvtPDL::getId( "pi-" );
static EvtId PI0 = EvtPDL::getId( "pi0" );
static EvtId RHOP = EvtPDL::getId( "rho+" );
static EvtId RHOM = EvtPDL::getId( "rho-" );
static EvtId RHO0 = EvtPDL::getId( "rho0" );
static EvtId A2P = EvtPDL::getId( "a_2+" );
static EvtId A2M = EvtPDL::getId( "a_2-" );
static EvtId A20 = EvtPDL::getId( "a_20" );
static EvtId A1P = EvtPDL::getId( "a_1+" );
static EvtId A1M = EvtPDL::getId( "a_1-" );
static EvtId A10 = EvtPDL::getId( "a_10" );
static EvtId A0P = EvtPDL::getId( "a_0+" );
static EvtId A0M = EvtPDL::getId( "a_0-" );
static EvtId A00 = EvtPDL::getId( "a_00" );
static EvtId B1P = EvtPDL::getId( "b_1+" );
static EvtId B1M = EvtPDL::getId( "b_1-" );
static EvtId B10 = EvtPDL::getId( "b_10" );
static EvtId H1 = EvtPDL::getId( "h_1" );
static EvtId H1PR = EvtPDL::getId( "h'_1" );
static EvtId F1 = EvtPDL::getId( "f_1" );
static EvtId F1PR = EvtPDL::getId( "f'_1" );
static EvtId F0 = EvtPDL::getId( "f_0" );
static EvtId F0PR = EvtPDL::getId( "f'_0" );
static EvtId F2 = EvtPDL::getId( "f_2" );
static EvtId F2PR = EvtPDL::getId( "f'_2" );
static EvtId ETA = EvtPDL::getId( "eta" );
static EvtId ETAPR = EvtPDL::getId( "eta'" );
static EvtId OMEG = EvtPDL::getId( "omega" );
static EvtId KP = EvtPDL::getId( "K+" );
static EvtId KM = EvtPDL::getId( "K-" );
static EvtId K0 = EvtPDL::getId( "K0" );
static EvtId KB = EvtPDL::getId( "anti-K0" );
static EvtId K0S = EvtPDL::getId( "K_S0" );
static EvtId K0L = EvtPDL::getId( "K_L0" );
static EvtId KSTP = EvtPDL::getId( "K*+" );
static EvtId KSTM = EvtPDL::getId( "K*-" );
static EvtId KST0 = EvtPDL::getId( "K*0" );
static EvtId KSTB = EvtPDL::getId( "anti-K*0" );
static EvtId K1P = EvtPDL::getId( "K_1+" );
static EvtId K1M = EvtPDL::getId( "K_1-" );
static EvtId K10 = EvtPDL::getId( "K_10" );
static EvtId K1B = EvtPDL::getId( "anti-K_10" );
static EvtId K1STP = EvtPDL::getId( "K'_1+" );
static EvtId K1STM = EvtPDL::getId( "K'_1-" );
static EvtId K1ST0 = EvtPDL::getId( "K'_10" );
static EvtId K1STB = EvtPDL::getId( "anti-K'_10" );
static EvtId K2STP = EvtPDL::getId( "K_2*+" );
static EvtId K2STM = EvtPDL::getId( "K_2*-" );
static EvtId K2ST0 = EvtPDL::getId( "K_2*0" );
static EvtId K2STB = EvtPDL::getId( "anti-K_2*0" );
static EvtId PHI = EvtPDL::getId( "phi" );
static EvtId DSP = EvtPDL::getId( "D_s+" );
static EvtId DSM = EvtPDL::getId( "D_s-" );
static EvtId DSSTP = EvtPDL::getId( "D_s*+" );
static EvtId DSSTM = EvtPDL::getId( "D_s*-" );
static EvtId DS1P = EvtPDL::getId( "D_s1+" );
static EvtId DS1M = EvtPDL::getId( "D_s1-" );
static EvtId DS0STP = EvtPDL::getId( "D_s0*+" );
static EvtId DS0STM = EvtPDL::getId( "D_s0*-" );
static EvtId DPS1P = EvtPDL::getId( "D'_s1+" );
static EvtId DPS1M = EvtPDL::getId( "D'_s1-" );
static EvtId DS2STP = EvtPDL::getId( "D_s2*+" );
static EvtId DS2STM = EvtPDL::getId( "D_s2*-" );
EvtId parnum, mesnum, lnum;
parnum = getParentId();
mesnum = getDaug( 0 );
lnum = getDaug( 1 );
if ( parnum == BP || parnum == BM || parnum == B0 || parnum == B0B ||
parnum == BS0 || parnum == BSB ) {
if ( mesnum == DST0 || mesnum == DSTP || mesnum == DSTB ||
mesnum == DSTM || mesnum == DSSTP || mesnum == DSSTM ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 10000.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 7000.0 );
return;
}
}
if ( mesnum == D0 || mesnum == DP || mesnum == D0B || mesnum == DM ||
mesnum == DSP || mesnum == DSM ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 4000.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 3500.0 );
return;
}
}
if ( mesnum == D1P1P || mesnum == D1P1N || mesnum == D1P10 ||
mesnum == D1P1B || mesnum == DS1P || mesnum == DS1M ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1300.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 480.0 );
return;
}
}
if ( mesnum == D3P1P || mesnum == D3P1N || mesnum == D3P10 ||
mesnum == D3P1B || mesnum == DS0STP || mesnum == DS0STM ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 450.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 73.0 ); //???
return;
}
}
if ( mesnum == D3P0P || mesnum == D3P0N || mesnum == D3P00 ||
mesnum == D3P0B || mesnum == DPS1P || mesnum == DPS1M ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 200.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 90.0 );
return;
}
}
if ( mesnum == D3P2P || mesnum == D3P2N || mesnum == D3P20 ||
mesnum == D3P2B || mesnum == DS2STP || mesnum == DS2STM ) {
if ( mesnum == DS2STP || mesnum == DS2STM ) {
setProbMax( 550.0 );
return;
}
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 400.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 220.0 );
return;
}
}
if ( mesnum == D21S0P || mesnum == D21S0N || mesnum == D21S00 ||
mesnum == D21S0B ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 16.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 3.0 );
return;
}
}
if ( mesnum == D23S1P || mesnum == D23S1N || mesnum == D23S10 ||
mesnum == D23S1B ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 500.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 250.0 );
return;
}
}
if ( mesnum == RHOP || mesnum == RHOM || mesnum == RHO0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 6500.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 6000.0 );
return;
}
}
if ( mesnum == OMEG ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 6800.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 6000.0 );
return;
}
}
if ( mesnum == PIP || mesnum == PIM || mesnum == PI0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1200.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1150.0 );
return;
}
}
if ( mesnum == ETA ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1800.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1900.0 );
return;
}
}
if ( mesnum == ETAPR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 3000.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 3000.0 );
return;
}
}
if ( mesnum == B1P || mesnum == B1M || mesnum == B10 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 2500.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1700.0 );
return;
}
}
if ( mesnum == A0P || mesnum == A0M || mesnum == A00 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 80.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 62.0 );
return;
}
}
if ( mesnum == A1P || mesnum == A1M || mesnum == A10 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 4500.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 3500.0 );
return;
}
}
if ( mesnum == A2P || mesnum == A2M || mesnum == A20 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1200.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1000.0 );
return;
}
}
if ( mesnum == H1 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 2600.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 2900.0 );
return;
}
}
if ( mesnum == H1PR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1400.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1500.0 );
return;
}
}
if ( mesnum == F2 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1100.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1100.0 );
return;
}
}
if ( mesnum == F2PR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 804.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 600.0 );
return;
}
}
if ( mesnum == F1 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 2500.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 2000.0 );
return;
}
}
if ( mesnum == F1PR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 2400.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1700.0 );
return;
}
}
if ( mesnum == F0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 80.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 63.0 );
return;
}
}
if ( mesnum == F0PR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 120.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 120.0 );
return;
}
}
if ( mesnum == RHO2SP || mesnum == RHO2SM || mesnum == RHO2S0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 2400.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 2000.0 );
return;
}
}
if ( mesnum == OMEG2S ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1600.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1400.0 );
return;
}
}
if ( mesnum == PI2SP || mesnum == PI2SM || mesnum == PI2S0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 500.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 300.0 );
return;
}
}
if ( mesnum == ETA2S ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 344.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 300.0 );
return;
}
}
if ( mesnum == KP || mesnum == KM || mesnum == K1P || mesnum == K1M ||
mesnum == K1STP || mesnum == K1STM ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 2000.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 1000.0 );
return;
}
}
if ( mesnum == KSTP || mesnum == KSTM ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 10000.0 );
return;
}
if ( lnum == TAUP || lnum == TAUM ) {
setProbMax( 7000.0 );
return;
}
}
}
if ( parnum == D0 || parnum == DP || parnum == DM || parnum == D0B ) {
if ( mesnum == RHOP || mesnum == RHOM || mesnum == RHO0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 110.0 );
return;
}
}
if ( mesnum == OMEG ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 75.0 );
return;
}
}
if ( mesnum == PIP || mesnum == PIM || mesnum == PI0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 40.0 );
return;
}
}
if ( mesnum == ETA ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 65.0 );
return;
}
}
if ( mesnum == ETAPR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 60.0 );
return;
}
}
if ( mesnum == KP || mesnum == KM || mesnum == K0 || mesnum == K0S ||
mesnum == K0L || mesnum == KB ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 70.0 );
return;
}
}
if ( mesnum == K1STP || mesnum == K1STM || mesnum == K1ST0 ||
mesnum == K1STB ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 3.3 );
return;
}
}
if ( mesnum == K1P || mesnum == K1M || mesnum == K10 || mesnum == K1B ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 100.0 );
return;
}
}
if ( mesnum == KSTP || mesnum == KSTM || mesnum == KST0 ||
mesnum == KSTB ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 135.0 );
return;
}
}
if ( mesnum == K2STP || mesnum == K2STM || mesnum == K2ST0 ||
mesnum == K2STB ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
//Lange - Oct 26,2001 - increasing from 0.75 to
//accomodate
setProbMax( 9.0 );
// setProbMax( 0.75);
return;
}
}
if ( mesnum == F0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1.0 );
return;
}
}
}
if ( parnum == DSP || parnum == DSM ) {
if ( mesnum == PHI ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 90.0 );
return;
}
}
if ( mesnum == ETA ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 75.0 );
return;
}
}
if ( mesnum == ETAPR ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 80.0 );
return;
}
}
if ( mesnum == KST0 || mesnum == KSTB ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 100.0 );
return;
}
}
if ( mesnum == K0 || mesnum == KB || mesnum == K0S || mesnum == K0L ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 45.0 );
return;
}
}
if ( mesnum == F0 ) {
if ( lnum == EP || lnum == EM || lnum == MUP || lnum == MUM ) {
setProbMax( 1.0 );
return;
}
}
}
if ( parnum == BCP || parnum == BCM ) {
setProbMax( 1000.0 );
return;
}
//This is a real cludge.. (ryd)
setProbMax( 0.0 );
}
void EvtISGW2::init()
{
checkNArg( 0 );
checkNDaug( 3 );
//We expect the parent to be a scalar
//and the daughters to be X lepton neutrino
checkSpinParent( EvtSpinType::SCALAR );
checkSpinDaughter( 1, EvtSpinType::DIRAC );
checkSpinDaughter( 2, EvtSpinType::NEUTRINO );
EvtSpinType::spintype mesontype = EvtPDL::getSpinType( getDaug( 0 ) );
isgw2ffmodel = std::make_unique<EvtISGW2FF>();
switch ( mesontype ) {
case EvtSpinType::SCALAR:
calcamp = std::make_unique<EvtSemiLeptonicScalarAmp>();
break;
case EvtSpinType::VECTOR:
calcamp = std::make_unique<EvtSemiLeptonicVectorAmp>();
break;
case EvtSpinType::TENSOR:
calcamp = std::make_unique<EvtSemiLeptonicTensorAmp>();
;
break;
default:;
}
}
| 33.480272 | 81 | 0.42474 | qdcampagna |
f8754b22c2c9ad302c1dae607a9a6d960f7b98e4 | 4,812 | hpp | C++ | src/image_processing/grid.hpp | Gusgo99/Fourier_drawing | 24048863ae9faabcf5db928e09cdc258f5017b2c | [
"MIT"
] | null | null | null | src/image_processing/grid.hpp | Gusgo99/Fourier_drawing | 24048863ae9faabcf5db928e09cdc258f5017b2c | [
"MIT"
] | null | null | null | src/image_processing/grid.hpp | Gusgo99/Fourier_drawing | 24048863ae9faabcf5db928e09cdc258f5017b2c | [
"MIT"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
MIT License
Copyright (c) 2020 Gustavo Pacola Gonçalves
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 GRID_HPP
#define GRID_HPP
#pragma once
#include <iostream>
#include <array>
#include <utility>
#include <vector>
class grid {
public:
using position = std::pair<size_t, size_t>;
using offset = std::pair<int, int>;
using iterator = std::vector<int>::iterator;
using const_iterator = std::vector<int>::const_iterator;
enum data {NOTHING, EDGE};
grid(
const size_t _numLines,
const size_t _numColumns,
const std::vector<int> &_gridData = {});
grid(
const position _size = {0, 0},
const std::vector<int> &_gridData = {});
void fill(const int _value);
size_t num_lines() const;
size_t num_columns() const;
position get_size() const;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
int& operator()(const size_t _line, const size_t _column);
int& operator()(const position _position);
int operator()(const size_t _line, const size_t _column) const;
int operator()(const position _position) const;
position max_neighbour(const position _targetPosition) const;
position min_neighbour(const position _targetPosition) const;
std::vector<int> positions_data(const std::vector<position> _positions) const;
std::array<int, 8> neighbours_data(const position _targetPosition) const;
std::array<int, 4> diagonal_neighbours_data(const position _targetPosition) const;
std::array<int, 4> non_diagonal_neighbours_data(const position _targetPosition) const;
template<typename inputIt>
static int count_regions(const inputIt _begin, const inputIt _end);
grid distance_heightmap(const position _targetPosition) const;
std::vector<position> descend_heightmap(const position _start) const;
std::vector<position> find_every_value(const int _value) const;
position find_value(const int _value) const;
std::vector<position> get_contour() const;
void remove_unconnected_cells(const position _targetPosition);
bool remove_non_connecting_cells(const std::vector<position> &_positions);
void skeletonize();
std::vector<position> solve_chinese_postman();
class cellNeighbourhood {
public:
cellNeighbourhood();
cellNeighbourhood(const grid &_grid, const grid::position _position);
int& operator[](const size_t _position);
int operator[](const size_t _position) const;
std::array<int, 4> diagonal_cells() const;
std::array<int, 4> non_diagonal_cells() const;
using iterator = std::array<int, 8>::iterator;
using const_iterator = std::array<int, 8>::const_iterator;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
size_t size() const;
bool does_cell_causes_connection() const;
bool has_even_connection_count() const;
bool has_odd_connection_count() const;
static constexpr std::array<grid::offset, 8> NEIGHBOUROFFSET{
grid::offset(-1, -1), grid::offset(0, -1), grid::offset(1, -1),
grid::offset(1, 0),
grid::offset(1, 1), grid::offset(0, 1), grid::offset(-1, 1),
grid::offset(-1, 0)
};
private:
size_t count_connected_cells(const size_t _startIndex) const;
std::array<int, 8> neighbourData;
std::array<position, 8> neighbourPositions;
};
cellNeighbourhood get_cell_neighbourhood(const position _position) const;
private:
position size;
std::vector<int> gridData;
static constexpr std::array<grid::offset, 8> NEIGHBOUROFFSET{
grid::offset(-1, -1), grid::offset(0, -1), grid::offset(1, -1),
grid::offset(1, 0),
grid::offset(1, 1), grid::offset(0, 1), grid::offset(-1, 1),
grid::offset(-1, 0)
};
};
#endif | 35.382353 | 110 | 0.718204 | Gusgo99 |
f8761ee0cd720565e27b13990b4641d03efd4515 | 4,014 | hpp | C++ | include/Hord/IO/PropTypeIterator.hpp | komiga/hord | 32be8ffb11bd74959c5cd5254e36d87f224b6f60 | [
"MIT"
] | null | null | null | include/Hord/IO/PropTypeIterator.hpp | komiga/hord | 32be8ffb11bd74959c5cd5254e36d87f224b6f60 | [
"MIT"
] | null | null | null | include/Hord/IO/PropTypeIterator.hpp | komiga/hord | 32be8ffb11bd74959c5cd5254e36d87f224b6f60 | [
"MIT"
] | null | null | null | /**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief PropType iterator.
@ingroup prop
*/
#pragma once
#include <Hord/config.hpp>
#include <Hord/utility.hpp>
#include <Hord/IO/Defs.hpp>
#include <duct/utility.hpp>
#include <type_traits>
namespace Hord {
namespace IO {
// Forward declarations
class PropTypeIterator;
/**
@addtogroup prop
@{
*/
/** @cond INTERNAL */
namespace {
static constexpr unsigned
s_bit_position[]{
enum_cast(IO::PropType::LAST), // none
enum_cast(IO::PropType::identity),
enum_cast(IO::PropType::metadata),
0u,
enum_cast(IO::PropType::scratch),
0u,0u,0u,
enum_cast(IO::PropType::primary),
0u,0u,0u,0u, 0u,0u,0u,
enum_cast(IO::PropType::auxiliary)
};
static_assert(
17u == std::extent<decltype(s_bit_position)>::value,
"s_bit_position needs to be updated"
);
#define assert_bit(t_) \
static_assert( \
s_bit_position[enum_cast(IO::PropTypeBit:: t_)] \
== enum_cast(IO::PropType:: t_), \
"bit is not in the correct location" \
)
assert_bit(identity);
assert_bit(metadata);
assert_bit(scratch);
assert_bit(primary);
assert_bit(auxiliary);
#undef assert_bit
} // anonymous namespace
/** @endcond */ // INTERNAL
/**
PropType iterator.
*/
class PropTypeIterator {
private:
enum : unsigned {
end_position = enum_cast(IO::PropType::LAST),
mask_value = enum_cast(IO::PropTypeBit::all),
};
static constexpr unsigned
lsb(
unsigned const value
) {
return value & unsigned(-signed(value));
}
unsigned m_value;
unsigned m_position;
PropTypeIterator() = delete;
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~PropTypeIterator() = default;
/** Copy constructor. */
PropTypeIterator(PropTypeIterator const&) = default;
/** Move constructor. */
PropTypeIterator(PropTypeIterator&&) = default;
/** Copy assignment operator. */
PropTypeIterator& operator=(PropTypeIterator const&) = default;
/** Move assignment operator. */
PropTypeIterator& operator=(PropTypeIterator&&) = default;
/**
Constructor with types.
*/
constexpr
PropTypeIterator(
IO::PropTypeBit const types
) noexcept
: m_value(enum_cast(types) & mask_value)
, m_position(
// Woo paranoia
s_bit_position[mask_value & lsb(m_value)]
)
{}
/// @}
/** @name Properties */ /// @{
/**
Get value.
*/
constexpr IO::PropTypeBit
value() const noexcept {
return static_cast<IO::PropTypeBit>(m_value);
}
/**
Get position.
*/
constexpr unsigned
position() const noexcept {
return m_position;
}
/**
Check if iterator has a type at its position.
*/
constexpr bool
has() const noexcept {
return m_value & (1u << m_position);
}
/**
Get type at current position.
*/
constexpr IO::PropType
type() const noexcept {
return has()
? static_cast<IO::PropType>(m_position)
: static_cast<IO::PropType>(-1)
;
}
/// @}
/** @name Operators */ /// @{
/**
Indirection operator.
*/
IO::PropType
operator*() const noexcept {
return type();
}
/**
Post-increment operator.
*/
PropTypeIterator
operator++(int) noexcept {
PropTypeIterator copy{*this};
++(*this);
return copy;
}
/**
Pre-increment operator.
*/
PropTypeIterator&
operator++() noexcept {
m_position = s_bit_position[
lsb(m_value & (mask_value << (1u + m_position)))
];
return *this;
}
/**
Equal-to operator.
*/
bool
operator==(
PropTypeIterator const& other
) const noexcept {
return m_position == other.m_position;
}
/**
Not-equal-to operator.
*/
bool
operator!=(
PropTypeIterator const& other
) const noexcept {
return m_position != other.m_position;
}
/// @}
};
/**
Get beginning iterator for types.
*/
constexpr PropTypeIterator
begin(
IO::PropTypeBit const types
) noexcept {
return {types};
}
/**
Get ending iterator for types.
*/
constexpr PropTypeIterator
end(
IO::PropTypeBit const /*types*/
) noexcept {
return {PropTypeBit::none};
}
/** @} */ // end of doc-group prop
} // namespace IO
} // namespace Hord
| 17.376623 | 72 | 0.673144 | komiga |
f878e48779a25bfad72d49a2b0b3ac46baafd08e | 4,404 | hpp | C++ | SDK/ARKSurvivalEvolved_IsFlying_DK_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_IsFlying_DK_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_IsFlying_DK_classes.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_IsFlying_DK_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass IsFlying_DK.IsFlying_DK_C
// 0x0063 (0x00F3 - 0x0090)
class UIsFlying_DK_C : public UBTDecorator_BlueprintBase
{
public:
class AActor* K2Node_Event_OwnerActor2; // 0x0090(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AActor* K2Node_Event_OwnerActor; // 0x0098(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<EBTNodeResult> K2Node_Event_NodeResult; // 0x00A0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x00A1(0x0007) MISSED OFFSET
class APrimalDinoAIController* K2Node_DynamicCast_AsPrimalDinoAIController; // 0x00A8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast_CastSuccess; // 0x00B0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData01[0x7]; // 0x00B1(0x0007) MISSED OFFSET
class APrimalDinoAIController* K2Node_DynamicCast_AsPrimalDinoAIController2; // 0x00B8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast2_CastSuccess; // 0x00C0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData02[0x7]; // 0x00C1(0x0007) MISSED OFFSET
class AActor* K2Node_Event_OwnerActor3; // 0x00C8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APrimalDinoAIController* K2Node_DynamicCast_AsPrimalDinoAIController3; // 0x00D0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast3_CastSuccess; // 0x00D8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData03[0x7]; // 0x00D9(0x0007) MISSED OFFSET
class APawn* CallFunc_K2_GetPawn_ReturnValue; // 0x00E0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APrimalDinoCharacter* K2Node_DynamicCast_AsPrimalDinoCharacter; // 0x00E8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast4_CastSuccess; // 0x00F0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasBuffPreventingFlight_ReturnValue; // 0x00F1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue; // 0x00F2(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass IsFlying_DK.IsFlying_DK_C");
return ptr;
}
void ReceiveConditionCheck(class AActor** OwnerActor);
void ReceiveExecutionStart(class AActor** OwnerActor);
void ReceiveExecutionFinish(class AActor** OwnerActor, TEnumAsByte<EBTNodeResult>* NodeResult);
void ExecuteUbergraph_IsFlying_DK(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 72.196721 | 192 | 0.576067 | 2bite |
f87a8571bd3a0a6c949b9ea1bd0da477907e674b | 894 | hpp | C++ | engine/src/TransitionManager.hpp | skryabiin/core | 13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7 | [
"MIT"
] | null | null | null | engine/src/TransitionManager.hpp | skryabiin/core | 13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7 | [
"MIT"
] | null | null | null | engine/src/TransitionManager.hpp | skryabiin/core | 13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7 | [
"MIT"
] | null | null | null | #ifndef CORE_TRANSITION_MANAGER_HPP
#define CORE_TRANSITION_MANAGER_HPP
#include "Templates.hpp"
#include "RuntimeContext.hpp"
#include "LuaState.hpp"
#include "Transition.hpp"
namespace core {
class TransitionManager : public initializable<TransitionManager, void, void, void, void>, public singleton<TransitionManager>, public updateable<TransitionManager, void, RuntimeContext>, public pausable<TransitionManager> {
public:
void addTransition(TransitionBase* transition);
//lua bindings
static int createTransition_bind(LuaState& lua);
static int deleteTransition_bind(LuaState& lua);
bool createImpl();
bool initializeImpl();
bool resetImpl();
bool destroyImpl();
void updateImpl(float dt, RuntimeContext& context);
void pauseImpl();
void resumeImpl();
private:
std::vector<TransitionBase*> _transitions;
};
} //end namespace core
#endif | 19.021277 | 225 | 0.760626 | skryabiin |
f87c02bce0df83d52dde121d9a4cbdd6f4fce4ff | 1,230 | cpp | C++ | 72_edit-distance.cpp | yzhhome/leetcode_cpp | 69404b039848e9e43ace80c43243f04b037a1fa1 | [
"MIT"
] | null | null | null | 72_edit-distance.cpp | yzhhome/leetcode_cpp | 69404b039848e9e43ace80c43243f04b037a1fa1 | [
"MIT"
] | null | null | null | 72_edit-distance.cpp | yzhhome/leetcode_cpp | 69404b039848e9e43ace80c43243f04b037a1fa1 | [
"MIT"
] | null | null | null | /*
72. 编辑距离
https://leetcode-cn.com/problems/edit-distance/
*/
#include <iostream>
#include <vector>
using namespace std;
// 最小编辑距离动态规划解法
int minDistance(string word1, string word2) {
int l1 = word1.size();
int l2 = word2.size();
// dp初始化为全0的l1 * l2容器
vector<vector<int>> dp(l1 + 1, vector<int>(l2 + 1, 0));
// 第0列初始化为[0, l1]
for (int i = 0; i <= l1; i++)
dp[i][0] = i;
// 第0行初始化为[0, l2]
for (int j = 0; j <= l2; j++)
dp[0][j] = j;
for (int i = 1; i <= l1; i++){
for (int j = 1; j <= l2; j++){
// 两个字符相同,各自向前移动一个字符
if (word1[i - 1] == word2[j - 1]){
dp[i][j] = dp[i - 1][j - 1];
}
else{
// 插入: dp[i][j - 1] 插入word2中的一个字符,j前移1
// 删除: dp[i - 1][j] 删除word1中的一个字符,i前移1
// 替换: dp[i - 1][j - 1] word1和word2中的字符进替换,i和j都前移1
// 每次前移操作次数加1
int minValue = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1]));
dp[i][j] = minValue + 1;
}
}
}
return dp[l1][l2];
}
int main(){
cout << minDistance("horse", "ros") << endl;
system("pause");
return 0;
} | 24.6 | 86 | 0.437398 | yzhhome |
f87c59038dbdc3525019a60281da59ac0cc4b014 | 3,176 | hh | C++ | commands/function-cmd.hh | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 10 | 2016-12-28T22:06:31.000Z | 2021-05-24T13:42:30.000Z | commands/function-cmd.hh | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 4 | 2015-10-09T23:55:10.000Z | 2020-04-04T08:09:22.000Z | commands/function-cmd.hh | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | null | null | null | // -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#ifndef FAINT_FUNCTION_CMD_HH
#define FAINT_FUNCTION_CMD_HH
#include <functional>
#include "commands/bitmap-cmd.hh"
namespace faint{
class Bitmap;
class utf8_string;
BitmapCommandPtr function_command(const utf8_string& name,
const std::function<void(Bitmap&)>&);
BitmapCommandPtr function_command(const utf8_string& name,
std::function<void(Bitmap&)>&&);
template<typename... Args, typename... Rest>
BitmapCommandPtr in_place_function_command(const utf8_string& name,
Bitmap(*func)(const Bitmap&, Args...),
Rest&&... rest)
{
return function_command(name,
[=](Bitmap& bmp){
bmp = func(bmp, rest...);
});
}
template<typename... Rest, typename...Args>
BitmapCommandPtr function_command(const utf8_string& name,
void(*func)(Bitmap&, Args...),
Rest&&... rest)
{
// Bind all arguments of the function, except the bitmap parameter (the first
// argument) which is provided as the only parameter when the
// function is run as a command.
return function_command(name,
[=](Bitmap& bmp){
return func(bmp, rest...);
});
}
template<typename ArgHere, typename ArgThere>
BitmapCommandPtr function_command(const utf8_string& name,
void(*func)(Bitmap&, ArgThere),
ArgHere&& a)
{
// This function_command variant helps resolving the correct
// bitmap-taking function in the face of overloads by requiring
// matching arguments, instead of the compile failing on ambiguity.
//
// For example, with these overloads:
//
// 1. ColRGB blend_alpha(const Color&, const ColRGB&)
// 2. void blend_alpha(Bitmap&, const ColRGB&)
// 3. void blend_alpha(Bitmap&, const SpaceShip&)
//
// function_command(blend_alpha, ColRGB(255, 0, 0)) will correctly
// resolve to #2.
return function_command(name,
[=](Bitmap& bmp){
return func(bmp, a);
});
}
template<typename Arg>
BitmapCommandPtr function_command(const utf8_string& name,
void(*func)(Bitmap&, Arg),
Arg&& a)
{
// This function_command variant helps resolving the correct
// bitmap-taking function in the face of overloads by requiring
// matching arguments, instead of the compile failing on ambiguity.
//
// For example, with these overloads:
//
// 1. ColRGB blend_alpha(const Color&, const ColRGB&)
// 2. void blend_alpha(Bitmap&, const ColRGB&)
// 3. void blend_alpha(Bitmap&, const SpaceShip&)
//
// function_command(blend_alpha, ColRGB(255, 0, 0)) will correctly
// resolve to #2.
return function_command(name,
[=](Bitmap& bmp){
return func(bmp, a);
});
}
} // namespace
#endif
| 29.407407 | 79 | 0.707179 | lukas-ke |
f885832ffdb632c4dec78a43ac799bfe3ebd64e1 | 502 | cpp | C++ | GameDevelop/Source/Physics/Physics2D.cpp | Andapeng/GameEngineDevelop | c868dc453ca8e4191ff5180eb90aafbf71112f68 | [
"MIT"
] | null | null | null | GameDevelop/Source/Physics/Physics2D.cpp | Andapeng/GameEngineDevelop | c868dc453ca8e4191ff5180eb90aafbf71112f68 | [
"MIT"
] | null | null | null | GameDevelop/Source/Physics/Physics2D.cpp | Andapeng/GameEngineDevelop | c868dc453ca8e4191ff5180eb90aafbf71112f68 | [
"MIT"
] | null | null | null | #include "Physics2D.h"
int CheckCollision(int One_x1, int One_y1, int One_x2, int One_y2, int Two_x1, int Two_y1, int Two_x2, int Two_y2)
{
bool xIsCollide = (One_x1 < Two_x1) && (One_x2 > Two_x2);
bool yIsCollide = (One_y1 < Two_y1) && (One_y2 > Two_y2);
return xIsCollide && yIsCollide;
}
int CheckCollision(Collider2D& collider1, Collider2D& collider2)
{
return CheckCollision(collider1.x1, collider1.y1, collider1.x2, collider1.y2, collider2.x1, collider2.y1, collider2.x2, collider2.y2);
}
| 33.466667 | 135 | 0.739044 | Andapeng |
f887c3054c69e0ff42cbd0abdd24dc783099b433 | 782 | cpp | C++ | code/test8/2.cpp | Bc-Gg/Algorithms | 0c35fd4e002ff4b0ad6ebb243df3df278e366595 | [
"MIT"
] | 8 | 2022-03-13T10:25:33.000Z | 2022-03-30T08:26:00.000Z | code/test8/2.cpp | Bc-Gg/Algorithms | 0c35fd4e002ff4b0ad6ebb243df3df278e366595 | [
"MIT"
] | null | null | null | code/test8/2.cpp | Bc-Gg/Algorithms | 0c35fd4e002ff4b0ad6ebb243df3df278e366595 | [
"MIT"
] | 2 | 2022-03-20T12:09:52.000Z | 2022-03-21T03:43:01.000Z | # include<iostream>
# include<algorithm>
using namespace std;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
const int N =105;
int vis[N][N], g[N][N];
int col, row;
void dfs(int i , int j){
if(i <= col && j <= row && i >0 && j>0)
vis[i][j] = 1;
for(int k = 0 ;k < 4 ;k++){
if(!vis[i+dx[k]][j+dy[k]] && g[i+dx[k]][j+dy[k]])
dfs(i+dx[k], j+dy[k]);
}
}
int main(){
int ans = 0;
cin >> col >> row;
for(int i = 1 ; i <= col; i ++)
for(int j = 1 ; j <= row; j++)
scanf("%1d", &g[i][j]);
for(int i = 1 ; i <= col ;i++)
for(int j = 1 ; j <= row; j++){
if(!vis[i][j] && g[i][j]){
dfs(i,j);
ans++;
}
}
cout << ans;
return 0;
}
| 21.722222 | 57 | 0.378517 | Bc-Gg |
f8893dd9392e81ec9f2ed81473be878268a30ab5 | 2,747 | hpp | C++ | include/chemfiles/selections/parser.hpp | sguionni/chemfiles | 99486730d4849656308516c6f7ed60b74fd575bc | [
"BSD-3-Clause"
] | null | null | null | include/chemfiles/selections/parser.hpp | sguionni/chemfiles | 99486730d4849656308516c6f7ed60b74fd575bc | [
"BSD-3-Clause"
] | null | null | null | include/chemfiles/selections/parser.hpp | sguionni/chemfiles | 99486730d4849656308516c6f7ed60b74fd575bc | [
"BSD-3-Clause"
] | null | null | null | // Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#ifndef CHEMFILES_SELECTION_PARSER_HPP
#define CHEMFILES_SELECTION_PARSER_HPP
#include <string>
#include <vector>
#include <cassert>
#include "chemfiles/selections/lexer.hpp"
#include "chemfiles/selections/expr.hpp"
namespace chemfiles {
namespace selections {
/// A recursive descent parser for chemfiles selection language. This parser
/// does not handle selection context (`pairs: ...`) that should be striped
/// before using it.
class Parser {
public:
/// Create a new parser for the given list of `tokens`
Parser(std::vector<Token> tokens): tokens_(std::move(tokens)) {}
~Parser() = default;
Parser(const Parser&) = default;
Parser& operator=(const Parser&) = default;
Parser(Parser&&) noexcept = default;
Parser& operator=(Parser&&) = default;
/// Parse the list of tokens and get the corresponding Ast.
Ast parse();
private:
Ast expression();
Ast selector();
Ast bool_selector();
Ast string_selector();
Ast math_selector();
/// Parse Boolean and string properties, returning nullptr if none of these
/// can not be parsed, so that they can be parsed as a mathematical
/// expression later
Ast bool_or_string_property();
MathAst math_sum();
MathAst math_product();
MathAst math_power();
MathAst math_value();
// mathematical functions (cos, sin, ...)
MathAst math_function(const std::string& name);
// functions of atomic variables (distance(#1, #2), ...)
MathAst math_var_function(const std::string& name);
// Match multiple variables and the surrounding parenthesis
std::vector<Variable> variables();
// Match multiple variables or sub-selections
std::vector<SubSelection> sub_selection();
// Match an optional single variable and the surrounding parenthesis
Variable variable();
bool match(Token::Type type) {
if (check(type)) {
advance();
return true;
}
return false;
}
bool finished() const {
return peek().type() == Token::END;
}
Token peek() const {
return tokens_[current_];
}
Token previous() const {
assert(current_ > 0);
return tokens_[current_ - 1];
}
bool check(Token::Type type) const {
if (finished()) {
return false;
}
return peek().type() == type;
}
Token advance() {
if (!finished()) {
current_++;
}
return previous();
}
std::vector<Token> tokens_;
size_t current_ = 0;
};
}} // namespace chemfiles && namespace selections
#endif
| 26.413462 | 79 | 0.643611 | sguionni |
f88c9d57f3830dad0466c233cdb3b6db27f0215e | 2,770 | hpp | C++ | Server/includes/Systems/BonusSystem.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | 1 | 2019-08-14T12:31:50.000Z | 2019-08-14T12:31:50.000Z | Server/includes/Systems/BonusSystem.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | null | null | null | Server/includes/Systems/BonusSystem.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** Epitech scolarship project (4 years remaining)
** File description:
** Made on 2018/11 by ebernard
*/
#pragma once
#include "../../../libs/ECS/Manager.hpp"
#include "../../../libs/EventManager/EventManager.hpp"
#include "GameComponents.hpp"
#include "GameEvents.hpp"
class BonusSystem : public ecs::System {
public:
explicit BonusSystem(ecs::Manager &ecsMgr, EventManager &evtMgr) : System(ecsMgr), _evtMgr(evtMgr) {
setNeededComponent({Player::m_type, MovableHitBox::m_type});
setNeededComponent({PowerUpSpeed::m_type, MovableHitBox::m_type});
setNeededComponent({PowerUpShield::m_type, MovableHitBox::m_type});
}
/**
* @brief Gives player some speed
* @param it [int] bonus entity
*/
void handlePowerUpSpeed(ecs::Entity it) {
const auto &elemS { m_manager.getComponentManager<PowerUpSpeed>().getComponent(it) };
for (auto &elem : m_entities) {
if (m_manager.getComponentManager<Player>().hasEntity(elem)) {
auto &player { m_manager.getComponentManager<Player>().getComponent(elem) };
auto &sHitBox { m_manager.getComponentManager<MovableHitBox>().getComponent(it) };
auto &pHitBox { m_manager.getComponentManager<MovableHitBox>().getComponent(elem) };
if (pHitBox.checkCollide(sHitBox)) {
player += elemS;
m_manager.removeEntity(it);
_evtMgr.emit<Game::RemoveEvent>(it);
break;
}
}
}
};
/**
* @brief Gives a shield to the player
* @param it [int] bonus entity
*/
void handlePowerUpShield(ecs::Entity it) {
for (auto &elem : m_entities) {
if (m_manager.getComponentManager<Player>().hasEntity(elem)) {
auto &player { m_manager.getComponentManager<Player>().getComponent(elem) };
auto &sHitBox { m_manager.getComponentManager<MovableHitBox>().getComponent(it) };
auto &pHitBox { m_manager.getComponentManager<MovableHitBox>().getComponent(elem) };
if (pHitBox.checkCollide(sHitBox)) {
player._shield += 1;
m_manager.removeEntity(it);
_evtMgr.emit<Game::RemoveEvent>(it);
break;
}
}
}
}
void updateEntity(float timeSinceLastFrame, ecs::Entity it) override {
if (m_manager.getComponentManager<PowerUpSpeed>().hasEntity(it))
handlePowerUpSpeed(it);
else if (m_manager.getComponentManager<PowerUpShield>().hasEntity(it))
handlePowerUpShield(it);
}
private:
EventManager &_evtMgr;
}; | 36.447368 | 104 | 0.60361 | KillianG |
f88cf1e0093ec3289eaf3254e290d4a1dfafab9a | 793 | inl | C++ | rGWB/csmassert.inl | mfernba/rGWB | 346de75519b1752c1ac9bea8ad7e5526096506ca | [
"MIT"
] | 10 | 2017-11-23T14:14:04.000Z | 2022-03-14T20:22:30.000Z | rGWB/csmassert.inl | mfernba/rGWB | 346de75519b1752c1ac9bea8ad7e5526096506ca | [
"MIT"
] | null | null | null | rGWB/csmassert.inl | mfernba/rGWB | 346de75519b1752c1ac9bea8ad7e5526096506ca | [
"MIT"
] | 1 | 2020-11-30T14:35:09.000Z | 2020-11-30T14:35:09.000Z | //
// sm4dblist.h
// solidmodeling4
//
// Created by Manuel Fernandez on 1/2/15.
// Copyright (c) 2015 manueru. All rights reserved.
//
// An implementation of Martti Mäntylä Geometric Workbench
//
// Assertion management module.
//
#ifdef RGWB_STANDALONE_DISTRIBUTABLE
#undef assert
#include "csmfwddecl.hxx"
void csmassert_dontuse_assertion_failed(const char *file, int line, const char *assertion);
#define assert(condition) ( (condition)? (void)0 : csmassert_dontuse_assertion_failed(__FILE__, __LINE__, #condition))
#define assert_no_null(condition) assert(condition != NULL)
void csmassert_dontuse_default_error(const char *file, int line) __attribute__ ((noreturn));
#define default_error() csmassert_dontuse_default_error(__FILE__, __LINE__)
#endif
| 30.5 | 119 | 0.751576 | mfernba |
f88de24b9c5196b7686062cea0cea3c0bda05f90 | 2,526 | cpp | C++ | test/DigraphDot.cpp | cestlascorpion/Scorpion | c7175a0279f8d1eba2be7ba1758ddcd8fec25073 | [
"MIT"
] | null | null | null | test/DigraphDot.cpp | cestlascorpion/Scorpion | c7175a0279f8d1eba2be7ba1758ddcd8fec25073 | [
"MIT"
] | null | null | null | test/DigraphDot.cpp | cestlascorpion/Scorpion | c7175a0279f8d1eba2be7ba1758ddcd8fec25073 | [
"MIT"
] | null | null | null | #include "DigraphDot.h"
using namespace std;
using namespace Scorpion;
struct MySQLNode {
void operator()(DotNode *node) {
node->_label = "mysql\n" + node->_name;
node->_attr["shape"] = "ellipse";
node->_attr["style"] = "solid";
node->_attr["fontsize"] = "14";
}
};
struct RedisNode {
void operator()(DotNode *node) {
node->_label = "redis\n" + node->_name;
node->_attr["shape"] = "ellipse";
node->_attr["style"] = "solid";
node->_attr["fontsize"] = "14";
}
};
struct KafkaNode {
void operator()(DotNode *node) {
node->_label = "kafka\n" + node->_name;
node->_attr["shape"] = "ellipse";
node->_attr["style"] = "solid";
node->_attr["fontsize"] = "14";
}
};
struct MongoNode {
void operator()(DotNode *node) {
node->_label = "mongo\n" + node->_name;
node->_attr["shape"] = "ellipse";
node->_attr["style"] = "solid";
node->_attr["fontsize"] = "14";
}
};
struct TiDBNode {
void operator()(DotNode *node) {
node->_label = "tidb\n" + node->_name;
node->_attr["shape"] = "ellipse";
node->_attr["style"] = "solid";
node->_attr["fontsize"] = "14";
}
};
struct SpecialLine {
string operator()(DotNode *, DotNode *to) {
if (to->_label.find("mysql") != string::npos) {
return R"(["color"="green","style"="dashed","len"="3"])";
}
if (to->_label.find("redis") != string::npos) {
return R"(["color"="blue","style"="dashed","len"="3"])";
}
if (to->_label.find("kafka") != string::npos) {
return R"(["color"="red","style"="dashed","len"="3"])";
}
if (to->_label.find("mongo") != string::npos) {
return R"(["color"="brown","style"="dashed","len"="3"])";
}
if (to->_label.find("tidb") != string::npos) {
return R"(["color"="purple","style"="dashed","len"="3"])";
}
return R"(["color"="black","style"="bold","splines"="line","len"="3"])";
}
};
int main() {
DigraphDot dot(vector<string>{"dot", "fdp"}, "svg");
dot.ReadFile("relation.txt", DefaultNode());
dot.ReadFile("cppmysql.txt", MySQLNode());
dot.ReadFile("cppredis.txt", RedisNode());
dot.ReadFile("cppkafka.txt", KafkaNode());
dot.ReadFile("cppmongo.txt", MongoNode());
dot.ReadFile("cpptidb.txt", TiDBNode());
// dot.WriteSVC("accountlogic", SpecialLine());
dot.WriteALL(SpecialLine());
} | 30.804878 | 80 | 0.529691 | cestlascorpion |
f8925dee374fa25dc2b24c2f168137a77b03016b | 4,235 | cpp | C++ | common/type_system/state.cpp | doctashay/jak-project | bc0d2b0105518dd260144719cb6ac1f97e5624ad | [
"0BSD"
] | null | null | null | common/type_system/state.cpp | doctashay/jak-project | bc0d2b0105518dd260144719cb6ac1f97e5624ad | [
"0BSD"
] | 6 | 2021-02-08T06:11:47.000Z | 2022-03-14T06:02:18.000Z | common/type_system/state.cpp | doctashay/jak-project | bc0d2b0105518dd260144719cb6ac1f97e5624ad | [
"0BSD"
] | null | null | null | #include "state.h"
#include "common/type_system/TypeSystem.h"
/*!
* Convert a (state <blah> ...) to the function required to go. Must be state.
*/
TypeSpec state_to_go_function(const TypeSpec& state_type, const TypeSpec& return_type) {
assert(state_type.base_type() == "state");
std::vector<TypeSpec> arg_types;
for (int i = 0; i < (int)state_type.arg_count() - 1; i++) {
arg_types.push_back(state_type.get_arg(i));
}
arg_types.push_back(return_type); // for the return.
auto result = TypeSpec("function", arg_types);
result.add_new_tag("behavior", state_type.last_arg().base_type());
return result;
}
StateHandler handler_name_to_kind(const std::string& name) {
if (name == "enter") {
return StateHandler::ENTER;
} else if (name == "exit") {
return StateHandler::EXIT;
} else if (name == "code") {
return StateHandler::CODE;
} else if (name == "event") {
return StateHandler::EVENT;
} else if (name == "trans") {
return StateHandler::TRANS;
} else if (name == "post") {
return StateHandler::POST;
} else {
assert(false);
}
}
std::string handler_kind_to_name(StateHandler kind) {
switch (kind) {
case StateHandler::ENTER:
return "enter";
case StateHandler::EXIT:
return "exit";
case StateHandler::CODE:
return "code";
case StateHandler::EVENT:
return "event";
case StateHandler::TRANS:
return "trans";
case StateHandler::POST:
return "post";
default:
assert(false);
}
}
TypeSpec get_state_handler_type(const std::string& handler_name, const TypeSpec& state_type) {
return get_state_handler_type(handler_name_to_kind(handler_name), state_type);
}
TypeSpec get_state_handler_type(StateHandler kind, const TypeSpec& state_type) {
TypeSpec result;
switch (kind) {
case StateHandler::CODE:
result = state_to_go_function(state_type, TypeSpec("none"));
break;
case StateHandler::ENTER:
result = state_to_go_function(state_type, TypeSpec("none"));
break;
case StateHandler::TRANS:
case StateHandler::POST:
case StateHandler::EXIT:
result = TypeSpec("function", {TypeSpec("none")});
break;
case StateHandler::EVENT:
result = TypeSpec("function", {TypeSpec("process"), TypeSpec("int"), TypeSpec("symbol"),
TypeSpec("event-message-block"), TypeSpec("object")});
break;
default:
assert(false);
}
result.add_or_modify_tag("behavior", state_type.last_arg().base_type());
return result;
}
namespace {
TypeSpec func_to_state_type(const TypeSpec& func_type, const TypeSpec& proc_type) {
TypeSpec result("state");
for (int i = 0; i < ((int)func_type.arg_count()) - 1; i++) {
result.add_arg(func_type.get_arg(i));
}
result.add_arg(proc_type);
return result;
}
} // namespace
std::optional<TypeSpec> get_state_type_from_enter_and_code(const TypeSpec& enter_func_type,
const TypeSpec& code_func_type,
const TypeSpec& proc_type,
const TypeSystem& ts) {
bool enter_real_func =
enter_func_type.base_type() == "function" && enter_func_type.arg_count() > 0;
bool code_real_func = code_func_type.base_type() == "function" && code_func_type.arg_count() > 0;
if (enter_real_func && code_real_func) {
int i = 0;
TypeSpec result("state");
for (; i < std::min((int)enter_func_type.arg_count(), (int)code_func_type.arg_count()) - 1;
i++) {
result.add_arg(
ts.lowest_common_ancestor(enter_func_type.get_arg(i), code_func_type.get_arg(i)));
}
for (; i < ((int)enter_func_type.arg_count()) - 1; i++) {
result.add_arg(enter_func_type.get_arg(i));
}
for (; i < ((int)code_func_type.arg_count()) - 1; i++) {
result.add_arg(code_func_type.get_arg(i));
}
result.add_arg(proc_type);
return result;
} else if (enter_real_func) {
return func_to_state_type(enter_func_type, proc_type);
} else if (code_real_func) {
return func_to_state_type(code_func_type, proc_type);
} else {
return {};
}
} | 31.604478 | 99 | 0.638489 | doctashay |
f892fe7fe9e41c7f902a7e9cd70f3c0619dc0dd1 | 1,241 | cpp | C++ | LeetCode/Problems/Algorithms/#236_LowestCommonAncestorOfABinaryTree_sol3_common_path_from_root_with_parents_and_levels_O(N)_time_O(N)_extra_space_32ms_21.1MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#236_LowestCommonAncestorOfABinaryTree_sol3_common_path_from_root_with_parents_and_levels_O(N)_time_O(N)_extra_space_32ms_21.1MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#236_LowestCommonAncestorOfABinaryTree_sol3_common_path_from_root_with_parents_and_levels_O(N)_time_O(N)_extra_space_32ms_21.1MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
void dfs(TreeNode* node, unordered_map<TreeNode*, TreeNode*>& parent, unordered_map<TreeNode*, int>& level){
if(node != NULL){
for(TreeNode* child: {node->left, node->right}){
parent[child] = node;
level[child] = 1 + level[node];
dfs(child, parent, level);
}
}
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
unordered_map<TreeNode*, TreeNode*> parent;
unordered_map<TreeNode*, int> level;
parent[root] = NULL;
level[root] = 0;
dfs(root, parent, level);
while(level[p] != level[q]){
if(level[p] < level[q]){
q = parent[q];
}else{
p = parent[p];
}
}
while(p != q){
p = parent[p];
q = parent[q];
}
return p;
}
}; | 26.404255 | 113 | 0.448832 | Tudor67 |
f894c96f2088b599a7581d9c09e1c48a88bdcad6 | 2,987 | cpp | C++ | src/pcapng/sorter_pcapng.cpp | nprint/pcapML | a9be4f2b98053e105d042507aa0821a67ce2dd4d | [
"Apache-2.0"
] | 18 | 2021-06-02T21:05:43.000Z | 2022-03-12T15:21:14.000Z | src/pcapng/sorter_pcapng.cpp | nprint/pcapML | a9be4f2b98053e105d042507aa0821a67ce2dd4d | [
"Apache-2.0"
] | 3 | 2021-06-02T18:07:06.000Z | 2021-06-02T18:12:30.000Z | src/pcapng/sorter_pcapng.cpp | nprint/pcapml | 6a2189500caa51065a1b3387954ad08ebbfe5e3a | [
"Apache-2.0"
] | 1 | 2021-06-03T12:46:02.000Z | 2021-06-03T12:46:02.000Z | /*
* Copyright 2020 nPrint
* 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
*/
#include "sorter_pcapng.hpp"
bool Sorter::process_block(Block *b, void *p) {
uint32_t block_type;
block_type = b->get_block_type();
if (block_type == SECTION_HEADER) {
section_headers.push_back(b->get_file_window());
} else if (block_type == INTERFACE_HEADER) {
idbs.push_back(b->get_file_window());
} else if (block_type == ENHANCED_PKT_HEADER) {
process_packet_block(b);
}
return true;
}
bool Sorter::process_packet_block(Block *b) {
PacketSortInfo *psi;
std::string comment;
uint64_t ts;
std::vector<std::string> tokens;
EnhancedPacketBlock *epb;
comment = get_pkt_comment(b);
if (comment.compare("") == 0) {
return false;
}
tokenize_string(comment, tokens, ',');
psi = new PacketSortInfo;
/* set SID */
sscanf(tokens[COMMENT_SID_LOC].c_str(), "%zu", &psi->sid);
/* format and set timestamp */
epb = (EnhancedPacketBlock *) b->get_block_buf();
ts = transform_ts(epb->ts_low, epb->ts_high);
psi->ts = ts;
/* set file window */
psi->fw = b->get_file_window();
pkt_blocks.push_back(*psi);
return true;
}
int Sorter::sort_pcapng(char *infile, char *outfile) {
uint32_t rv;
Block *b;
rv = open_pcapng(infile);
if (rv != 0) {
return 1;
}
while (1) {
b = read_block();
if (b == NULL) {
break;
}
process_block(b, NULL);
delete b;
}
std::sort(pkt_blocks.begin(), pkt_blocks.end());
copy_output(infile, outfile);
return 0;
}
int Sorter::copy_output(char *infile, char *outfile) {
FILE *in, *out;
uint32_t i;
printf("Copying file in sorted order\n");
printf(" Number of sections: %ld\n", section_headers.size());
printf(" Number of idbs: %ld\n", idbs.size());
printf(" Number of pkt blocks: %ld\n", pkt_blocks.size());
in = fopen(infile, "r");
out = fopen(outfile, "wb");
for (i = 0; i < section_headers.size(); i++) {
copy_range(section_headers[i], in, out);
}
for (i = 0; i < idbs.size(); i++) {
copy_range(idbs[i], in , out);
}
for (i = 0; i < pkt_blocks.size(); i++) {
copy_range(pkt_blocks[i].fw, in, out);
}
return 0;
}
int Sorter::copy_range(FileWindow fw, FILE *in, FILE *out) {
uint32_t rv;
uint8_t buf[8192];
uint64_t n_bytes;
n_bytes = fw.f_end - fw.f_start;
rv = fseek(in, fw.f_start, SEEK_SET);
if (rv != 0) {
return 1;
}
rv = fread((void *) &buf, 1, n_bytes, in);
if (rv != n_bytes) {
return 1;
}
rv = fwrite((void *) &buf, 1, n_bytes, out);
if (rv!= n_bytes) {
return 1;
}
return 0;
}
| 23.706349 | 78 | 0.58152 | nprint |
f89830920ae7a452a7d2543989319b027212a580 | 590 | cpp | C++ | system/Dragon.cpp | arulagrawal/cos214_project | 1ea65ac7e46b97107c0ec2a75359514bc6c98c15 | [
"BSD-2-Clause"
] | null | null | null | system/Dragon.cpp | arulagrawal/cos214_project | 1ea65ac7e46b97107c0ec2a75359514bc6c98c15 | [
"BSD-2-Clause"
] | null | null | null | system/Dragon.cpp | arulagrawal/cos214_project | 1ea65ac7e46b97107c0ec2a75359514bc6c98c15 | [
"BSD-2-Clause"
] | null | null | null | #include "Dragon.h"
///The dragon spacecraft can move in all its normal directions and can clone itself.
Dragon::Dragon(string cargo[], int cargoSize) : Spacecraft(cargo, cargoSize)
{
}
void Dragon::boost()
{
stage->boost();
}
void Dragon::slow()
{
stage->slow();
}
void Dragon::left()
{
stage->left();
}
void Dragon::right()
{
stage->right();
}
Spacecraft *Dragon::clone()
{
int arrCargoSize = sizeof(cargo) / sizeof(cargo[0]);
return new Dragon(this->cargo, arrCargoSize);
}
vector<string> Dragon::getPeople() {
vector<string> empty;
return empty;
} | 15.945946 | 84 | 0.654237 | arulagrawal |
f8987424e3a72587ecd8396faafcee56ab68ffa0 | 739 | cpp | C++ | Before Summer 2017/SummerTrain Archieve/COWCAR.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Before Summer 2017/SummerTrain Archieve/COWCAR.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Before Summer 2017/SummerTrain Archieve/COWCAR.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | //============================================================================
// Name : COWCAR.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
int i, j = 0, cnt = 0, n, m, d, l, cows[50001], way[50001];
cin >> n >> m >> d >> l;
for (i = 0; i < n && cin >> cows[i]; ++i)
;
sort(cows, cows + n);
memset(way, 0, sizeof way);
for (i = 0; i < n; ++i, ++j) {
if (j == m)
j = 0;
if (cows[i] - (d * way[j]) >= l)
way[j]++, cnt++;
}
cout << cnt << endl;
return 0;
}
| 24.633333 | 78 | 0.399188 | mohamedGamalAbuGalala |
f8996596c88869df11abb3a72578a83a1979a2d9 | 601 | cpp | C++ | tests/replay/minimal_packed.cpp | alexbatashev/pi_reproduce | 7129111ff80b9d76e4dfad26f1f2b67ef3826e52 | [
"Apache-2.0"
] | null | null | null | tests/replay/minimal_packed.cpp | alexbatashev/pi_reproduce | 7129111ff80b9d76e4dfad26f1f2b67ef3826e52 | [
"Apache-2.0"
] | 4 | 2021-07-05T12:14:37.000Z | 2021-07-29T18:39:42.000Z | tests/replay/minimal_packed.cpp | alexbatashev/pi_reproduce | 7129111ff80b9d76e4dfad26f1f2b67ef3826e52 | [
"Apache-2.0"
] | null | null | null | // REQUIRES: linux
// RUN: echo "1" > %t.txt
// RUN: %clangxx %s --std=c++17 -o %t.exe
// RUN: %dpcpp_trace record --override -o %t_trace %t.exe -- %t.txt
// RUN: rm %t.txt
// RUN: %dpcpp_trace pack %t_trace
// RUN: %dpcpp_trace replay %t_trace
#include <cstdlib>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char *argv[]) {
if (argc != 2)
return EXIT_FAILURE;
if (!fs::exists(argv[1]))
return EXIT_FAILURE;
std::ifstream is{argv[1]};
int test;
is >> test;
if (test != 1) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 19.387097 | 67 | 0.62396 | alexbatashev |
f89d1b3b2cd7a12f8303d3d78823af4c73182a9c | 2,643 | cpp | C++ | Love Babber OnGoing Placement/Binary Trees/Construct Tree from Inorder & Preorder.cpp | work-mohit/Placement-Practice | 396e61f7980991b2d6392589f26f917981c135ab | [
"MIT"
] | null | null | null | Love Babber OnGoing Placement/Binary Trees/Construct Tree from Inorder & Preorder.cpp | work-mohit/Placement-Practice | 396e61f7980991b2d6392589f26f917981c135ab | [
"MIT"
] | null | null | null | Love Babber OnGoing Placement/Binary Trees/Construct Tree from Inorder & Preorder.cpp | work-mohit/Placement-Practice | 396e61f7980991b2d6392589f26f917981c135ab | [
"MIT"
] | null | null | null | class Solution{
public:
int findPosition(int in[] , int n, int ele){
for(int i = 0 ; i < n; i++){
if(ele == in[i]){
return i;
}
}
return -1;
}
Node* solve(int in[],int pre[], int n, int &index, int inorderStart, int inorderEnd){
if(index >= n || inorderStart > inorderEnd)
return NULL;
int ele = pre[index++];
Node* root = new Node(ele);
int pos = findPosition(in,n,ele);
root->left = solve(in, pre, n,index, inorderStart, pos-1);
root->right = solve(in, pre, n ,index , pos +1, inorderEnd);
return root;
}
Node* buildTree(int in[],int pre[], int n)
{
int preIndex = 0;
return solve(in, pre , n, preIndex ,0 , n-1);
}
};
/////////
// with making maping of the positions
// inorder and preorder
class Solution{
public:
void makeMapping(int in[] , int n, map<int, int> &m){
for(int i = 0 ; i < n; i++){
m[in[i]] = i;
}
}
Node* solve(int in[],int pre[], int n, int &index, int inorderStart, int inorderEnd, map<int,int> &m){
if(index >= n || inorderStart > inorderEnd)
return NULL;
int ele = pre[index++];
Node* root = new Node(ele);
int pos = m[ele];
root->left = solve(in, pre, n,index, inorderStart, pos-1, m);
root->right = solve(in, pre, n ,index , pos +1, inorderEnd, m);
return root;
}
Node* buildTree(int in[],int pre[], int n)
{
int preIndex = 0;
map<int,int> m;
makeMapping(in, n , m);
return solve(in, pre , n, preIndex ,0 , n-1,m);
}
};
// inorder and postorder
void makeMapping(int in[] , int n, map<int, int> &m){
for(int i = 0 ; i < n; i++){
m[in[i]] = i;
}
}
Node* solve(int in[],int post[], int n, int &index, int inorderStart, int inorderEnd, map<int,int> &m){
if(index < 0 || inorderStart > inorderEnd)
return NULL;
int ele = post[index--];
Node* root = new Node(ele);
if(inorderStart == inorderEnd)
return root;
int pos = m[ele];
root->right = solve(in, post, n ,index , pos+1, inorderEnd, m);
root->left = solve(in, post, n,index, inorderStart, pos-1, m);
return root;
}
Node* buildTree(int in[],int post[], int n)
{
int postIndex = n-1;
map<int,int> m;
makeMapping(in, n , m);
return solve(in, post , n, postIndex ,0,n-1,m);
} | 26.168317 | 106 | 0.491109 | work-mohit |
f89eeea439b1f3db71fab797a27d3a9cbaf39406 | 1,591 | cpp | C++ | src/sdm/utils/value_function/action_selection/registry.cpp | SDMStudio/sdms | 43a86973081ffd86c091aed69b332f0087f59361 | [
"MIT"
] | null | null | null | src/sdm/utils/value_function/action_selection/registry.cpp | SDMStudio/sdms | 43a86973081ffd86c091aed69b332f0087f59361 | [
"MIT"
] | null | null | null | src/sdm/utils/value_function/action_selection/registry.cpp | SDMStudio/sdms | 43a86973081ffd86c091aed69b332f0087f59361 | [
"MIT"
] | null | null | null | #include <sdm/macros.hpp>
#include <sdm/utils/value_function/action_selection/registry.hpp>
#include <sdm/utils/value_function/action_selection.hpp>
SDMS_REGISTRY(action_selection)
SDMS_REGISTER("Exhaustive", ExhaustiveActionSelection)
SDMS_REGISTER("MaxplanSerial", ActionSelectionMaxplanSerial)
SDMS_REGISTER("MaxplanWCSP", ActionSelectionMaxplanWCSP)
#ifdef WITH_CPLEX
SDMS_REGISTER("MaxplanLP", ActionSelectionMaxplanLP)
SDMS_REGISTER("SawtoothLP", ActionSelectionSawtoothLP)
SDMS_REGISTER("SawtoothLPSerial", ActionSelectionSawtoothLPSerial)
#endif
SDMS_END_REGISTRY()
namespace sdm
{
namespace action_selection
{
std::vector<std::string> registry::available()
{
std::vector<std::string> available_init;
for (auto const &pair_init : container)
available_init.push_back(pair_init.first);
return available_init;
}
std::shared_ptr<ActionSelectionInterface> registry::make(std::string name, std::shared_ptr<SolvableByDP> world, Config config)
{
typename map_type::iterator it = registry::container.find(name);
if (it == registry::container.end())
{
std::string init_names = "{";
for (auto &v : registry::available())
{
init_names = init_names + "\"" + v + "\" ";
}
throw sdm::exception::Exception(name + " not registered. Available initializers are : " + init_names + "}");
}
return it->second(world, config);
}
}
} | 37 | 134 | 0.648649 | SDMStudio |
f89f8f663be1499b577dbf2c1723dd7d0575f515 | 2,961 | cpp | C++ | test/modulo_256-bit.cpp | kimwalisch/primesum | c73b8afba311413454a25d45482efaea025ae3a0 | [
"BSD-2-Clause"
] | 31 | 2016-05-16T10:43:48.000Z | 2021-12-31T23:20:46.000Z | test/modulo_256-bit.cpp | kimwalisch/primesum | c73b8afba311413454a25d45482efaea025ae3a0 | [
"BSD-2-Clause"
] | 2 | 2016-06-07T08:41:55.000Z | 2017-11-17T13:22:20.000Z | test/modulo_256-bit.cpp | kimwalisch/primesum | c73b8afba311413454a25d45482efaea025ae3a0 | [
"BSD-2-Clause"
] | 2 | 2019-10-31T02:11:39.000Z | 2021-06-29T16:37:56.000Z | #include <iostream>
#include <random>
#include <limits>
#include <int256_t.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using namespace primesum;
using namespace std;
typedef boost::multiprecision::int256_t boost_int256_t;
int main(int argc, char** argv)
{
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int64_t> dist(1, std::numeric_limits<int64_t>::max());
random_device rd2;
mt19937 gen2(rd2());
uniform_int_distribution<int64_t> dist2(1, std::numeric_limits<int16_t>::max());
int iters = 10000;
if (argc > 1)
iters = atoi(argv[1]);
// Test random dividends and small quotients
for (int i = 0; i < iters; i++)
{
int256_t x1 = 1;
boost_int256_t y1 = 1;
for (int i = 0; i < 4; i++)
{
int64_t a = dist(gen);
int256_t x2 = 1;
boost_int256_t y2 = 1;
x1 *= a; x1 += 1;
y1 *= a; y1 += 1;
for (int j = 1; j < 17; j++)
{
x2 = j;
y2 = j;
auto res1 = x1 % x2;
auto res2 = y1 % y2;
// std::cout << y1 << " % " << y2 << " == " << res2 << "\n";
if ((uint64_t) res1 != (uint64_t) res2)
{
std::cerr << x1 << std::endl;
std::cerr << x2 << std::endl;
std::cerr << y1 << std::endl;
std::cerr << y2 << std::endl;
std::cerr << (x1 % x2) << " != " << (y1 % y2) << std::endl;
return 1;
}
}
}
}
// Test random dividends and quotients
for (int i = 0; i < iters; i++)
{
int256_t x1 = 1;
boost_int256_t y1 = 1;
for (int i = 0; i < 4; i++)
{
int64_t a = dist(gen);
int256_t x2 = 1;
boost_int256_t y2 = 1;
x1 *= a; x1 += 1;
y1 *= a; y1 += 1;
for (int j = 0; j < 17; j++)
{
int64_t b = dist2(gen);
x2 *= b; x2 += 1;
y2 *= b; y2 += 1;
auto res1 = x1 % x2;
auto res2 = y1 % y2;
// std::cout << y1 << " % " << y2 << " == " << res2 << "\n";
do
{
if ((uint64_t) res1 != (uint64_t) res2)
{
std::cerr << x1 << std::endl;
std::cerr << x2 << std::endl;
std::cerr << y1 << std::endl;
std::cerr << y2 << std::endl;
std::cerr << (x1 % x2) << " != " << (y1 % y2) << std::endl;
return 1;
}
res1 >>= 64;
res2 >>= 64;
}
while (res2 != 0);
}
}
}
return 0;
}
| 25.747826 | 84 | 0.376224 | kimwalisch |
f8a0352f4587c4da4d218326156beffdeb413691 | 5,260 | cpp | C++ | src/appleseed/renderer/modeling/environmentshader/backgroundenvironmentshader.cpp | KarthikRIyer/appleseed | d66189620e06bc1be8122ad6e22c6e15514ebb49 | [
"MIT"
] | 1 | 2019-03-18T09:23:10.000Z | 2019-03-18T09:23:10.000Z | src/appleseed/renderer/modeling/environmentshader/backgroundenvironmentshader.cpp | anikket786/appleseed | e44f2ed2c867014c30195f067a91d0280c404c70 | [
"MIT"
] | null | null | null | src/appleseed/renderer/modeling/environmentshader/backgroundenvironmentshader.cpp | anikket786/appleseed | e44f2ed2c867014c30195f067a91d0280c404c70 | [
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "backgroundenvironmentshader.h"
// appleseed.renderer headers.
#include "renderer/kernel/rendering/pixelcontext.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/modeling/environmentshader/environmentshader.h"
#include "renderer/modeling/input/sourceinputs.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
#include "foundation/math/vector.h"
#include "foundation/utility/api/specializedapiarrays.h"
#include "foundation/utility/containers/dictionary.h"
using namespace foundation;
namespace renderer
{
namespace
{
//
// Background environment shader.
//
const char* Model = "background_environment_shader";
class BackgroundEnvironmentShader
: public EnvironmentShader
{
public:
BackgroundEnvironmentShader(
const char* name,
const ParamArray& params)
: EnvironmentShader(name, params)
{
m_inputs.declare("color", InputFormatSpectralIlluminance);
m_inputs.declare("alpha", InputFormatFloat, "1.0");
}
void release() override
{
delete this;
}
const char* get_model() const override
{
return Model;
}
void evaluate(
const ShadingContext& shading_context,
const PixelContext& pixel_context,
const Vector3d& direction,
Spectrum& value,
Alpha& alpha) const override
{
const Vector2f s(pixel_context.get_sample_position());
InputValues values;
m_inputs.evaluate(
shading_context.get_texture_cache(),
SourceInputs(Vector2f(s[0], 1.0f - s[1])),
&values);
value = values.m_color;
alpha = Alpha(values.m_alpha);
}
private:
APPLESEED_DECLARE_INPUT_VALUES(InputValues)
{
Spectrum m_color;
float m_alpha;
};
};
}
//
// BackgroundEnvironmentShaderFactory class implementation.
//
void BackgroundEnvironmentShaderFactory::release()
{
delete this;
}
const char* BackgroundEnvironmentShaderFactory::get_model() const
{
return Model;
}
Dictionary BackgroundEnvironmentShaderFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Background Environment Shader");
}
DictionaryArray BackgroundEnvironmentShaderFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "color")
.insert("label", "Color")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Texture Instances"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "alpha")
.insert("label", "Alpha")
.insert("type", "numeric")
.insert("min",
Dictionary()
.insert("value", "0.0")
.insert("type", "hard"))
.insert("max",
Dictionary()
.insert("value", "1.0")
.insert("type", "hard"))
.insert("use", "optional")
.insert("default", "1.0"));
return metadata;
}
auto_release_ptr<EnvironmentShader> BackgroundEnvironmentShaderFactory::create(
const char* name,
const ParamArray& params) const
{
return
auto_release_ptr<EnvironmentShader>(
new BackgroundEnvironmentShader(name, params));
}
} // namespace renderer
| 29.886364 | 80 | 0.626426 | KarthikRIyer |
f8a41d8f035097a9f8e4ecb31f96d6bc51b1d12b | 2,494 | cpp | C++ | examples/custom.cpp | vlazzarini/aurora | 4990d81a6873beace4a39d6584cc77afbda82cf4 | [
"BSD-3-Clause"
] | 11 | 2021-11-26T16:23:40.000Z | 2022-01-19T21:36:35.000Z | examples/custom.cpp | vlazzarini/aurora | 4990d81a6873beace4a39d6584cc77afbda82cf4 | [
"BSD-3-Clause"
] | null | null | null | examples/custom.cpp | vlazzarini/aurora | 4990d81a6873beace4a39d6584cc77afbda82cf4 | [
"BSD-3-Clause"
] | null | null | null | // custom.cpp:
// Custom bandlimited waveform generation example
//
// (c) V Lazzarini, 2021
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE
#include "BlOsc.h"
#include "Env.h"
#include "flute.h"
#include <cstdlib>
#include <iostream>
int main(int argc, const char *argv[]) {
if (argc > 3) {
auto dur = std::atof(argv[1]);
auto a = std::atof(argv[2]);
auto f = std::atof(argv[3]) * flute::ratio;
Aurora::TableSet<float> wave(flute::wave, flute::base, flute::fs);
Aurora::BlOsc<float> osc(&wave, flute::fs);
std::vector<float> brkpts({0.1f, 1.f, 0.5f, 0.1f, 1.f, 0.7f});
Aurora::Env<float> env(Aurora::env_gen<float>(brkpts), 0.1f,
flute::fs / Aurora::def_vsize, 1);
bool gate = 1;
for (int n = 0; n < osc.fs() * (dur + 0.1f); n += osc.vsize()) {
if (n > osc.fs() * dur)
gate = 0;
for (auto s : osc(env(0, a, gate)[0], f))
std::cout << s << std::endl;
}
} else
std::cout << "usage: " << argv[0] << " dur(s) amp freq(Hz)" << std::endl;
return 0;
}
| 45.345455 | 80 | 0.689254 | vlazzarini |
f8a79faaad893b5c41a06af5149f8af12cd8c9f9 | 17,240 | cpp | C++ | IntelShaderAnalyzer.cpp | GameTechDev/IntelShaderAnalyzer | 2fcb0c3e2a4d025fd89d8f417646dda015473738 | [
"MIT"
] | 117 | 2019-03-19T19:28:21.000Z | 2022-01-11T20:27:17.000Z | IntelShaderAnalyzer.cpp | GameTechDev/IntelShaderAnalyzer | 2fcb0c3e2a4d025fd89d8f417646dda015473738 | [
"MIT"
] | 2 | 2019-06-30T04:42:33.000Z | 2021-11-15T17:40:43.000Z | IntelShaderAnalyzer.cpp | GameTechDev/IntelShaderAnalyzer | 2fcb0c3e2a4d025fd89d8f417646dda015473738 | [
"MIT"
] | 6 | 2019-03-20T10:14:11.000Z | 2021-08-06T10:58:42.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Intel Corporation
// 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 _CRT_SECURE_NO_WARNINGS
#include "IntelShaderAnalyzer.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <d3dcompiler.h>
#ifdef _WIN64
#define DLL_NAME "IntelGpuCompiler64.dll"
#else
#define DLL_NAME "IntelGpuCompiler32.dll"
#endif
using namespace IntelGPUCompiler;
int sizeOfFile(const char* filename) {
struct stat st;
if (stat(filename, &st) == -1)
return -1;
return st.st_size;
}
bool readAllBytes( std::vector<uint8_t>& bytes, const char * filename )
{
size_t length = sizeOfFile( filename );
if ( length == -1 )
return false;
std::ifstream is(filename, std::ifstream::binary);
bytes.resize( length );
is.read((char*)bytes.data(), length);
return true;
}
bool readAllText( std::string& text,const char * filename )
{
std::ifstream file( filename );
if ( !file.good() )
return false;
std::stringstream buffer;
buffer << file.rdbuf();
text = std::move( buffer.str() );
return true;
}
class API
{
public:
virtual bool CanRun( ToolInputs& opts ) = 0;
virtual bool CreateCompiler( Platform platformID,SFunctionTable& functionTable,OpaqueCompiler& compiler ) = 0;
virtual bool CreateShader( SFunctionTable& functionTable,OpaqueCompiler& compiler,OpaqueShader& output,ToolInputs& opts ) = 0;
virtual void DeleteShader( SFunctionTable& functionTable,OpaqueShader& shader ) = 0;
virtual void DeleteCompiler( SFunctionTable& functionTable,OpaqueCompiler& compiler ) = 0;
};
class API_DX11 : public API
{
public:
virtual bool CanRun( ToolInputs& opts ) override
{
if ( opts.bytecode.empty() )
{
printf( "Missing shader bytecode\n" );
return false;
}
return true;
}
virtual bool CreateCompiler( Platform platformID, SFunctionTable& functionTable,OpaqueCompiler& compiler ) override
{
return functionTable.interface1.pfnDX11.pfnCreateCompiler( platformID,compiler );
}
virtual bool CreateShader( SFunctionTable& functionTable, OpaqueCompiler& compiler, OpaqueShader& output,ToolInputs& opts ) override
{
ShaderInput_DX11_V1 input;
input.DXBCBin = (void*)opts.bytecode.data();
return functionTable.interface1.pfnDX11.pfnCreateShader( compiler,input,output );
}
virtual void DeleteCompiler( SFunctionTable& functionTable, OpaqueCompiler& compiler ) override
{
functionTable.interface1.pfnDX11.pfnDeleteShaderCompiler( compiler );
}
virtual void DeleteShader( SFunctionTable& functionTable,OpaqueShader& shader ) override
{
functionTable.interface1.pfnDX11.pfnDeleteShader( shader );
}
};
class API_DX12 : public API
{
public:
virtual bool CanRun( ToolInputs& opts ) override
{
if ( opts.bytecode.empty() )
{
printf( "Missing shader bytecode\n" );
return false;
}
if ( opts.rootsig.empty() )
{
printf( "Missing root signature\n" );
return false;
}
return true;
}
virtual bool CreateCompiler( Platform platformID,SFunctionTable& functionTable,OpaqueCompiler& compiler ) override
{
return functionTable.interface1.pfnDX12.pfnCreateCompiler( platformID,compiler );
}
virtual bool CreateShader( SFunctionTable& functionTable,OpaqueCompiler& compiler,OpaqueShader& output,ToolInputs& opts ) override
{
ShaderInput_DX12_V1 input;
input.DXBCBin = (void*)opts.bytecode.data();
input.rootSignature = (void*)opts.rootsig.data();
input.rootSignatureSize = opts.rootsig.size();
return functionTable.interface1.pfnDX12.pfnCreateShader( compiler,input,output );
}
virtual void DeleteCompiler( SFunctionTable& functionTable,OpaqueCompiler& compiler ) override
{
functionTable.interface1.pfnDX12.pfnDeleteShaderCompiler( compiler );
}
virtual void DeleteShader( SFunctionTable& functionTable,OpaqueShader& shader ) override
{
functionTable.interface1.pfnDX12.pfnDeleteShader( shader );
}
};
bool RunTool( SFunctionTable& functionTable, ToolInputs& opts, API& api )
{
if ( !api.CanRun( opts ) )
return false;
for ( PlatformInfo& platform : opts.asics )
{
/// create compiler context
OpaqueCompiler pCompiler;
if ( !api.CreateCompiler( platform.Identifier,functionTable,pCompiler ) )
{
printf( "ERROR: %s\n",functionTable.interface1.pfnGetLastError( ) );
return false;
}
OpaqueShader output;
if( api.CreateShader( functionTable, pCompiler, output, opts ) )
{
size_t isaSize = 0;
const char* isaText = functionTable.interface1.pfnGetIsaText( output,isaSize );
if ( isaText )
{
std::stringstream isaFile;
if ( opts.isa_prefix )
isaFile << opts.isa_prefix;
isaFile << platform.platformName << ".asm";
std::string isaFileName = isaFile.str();
FILE* fp = fopen( isaFileName.c_str(), "w" );
if ( fp )
{
fprintf( fp,"%s",isaText );
fclose( fp );
}
else
{
printf( "Failed to open output file: %s\n",isaFileName.c_str() );
return false;
}
}
else
{
printf( "ERROR: %s\n", functionTable.interface1.pfnGetLastError( ) );
return false;
}
/// free up memory
api.DeleteShader( functionTable,output );
}
else
{
printf( "ERROR: %s\n", functionTable.interface1.pfnGetLastError( ) );
return false;
}
api.DeleteCompiler( functionTable,pCompiler );
}
return true;
}
void GetAsicList( SFunctionTable& functionTable, std::vector< IntelGPUCompiler::PlatformInfo >& asics )
{
size_t nPlatforms = functionTable.interface1.pfnEnumPlatforms( nullptr,0 );
asics.resize( nPlatforms );
functionTable.interface1.pfnEnumPlatforms( asics.data(),nPlatforms );
}
bool ListAsics()
{
HINSTANCE compilerInstance = (HINSTANCE)LoadLibraryA( DLL_NAME );
if ( !compilerInstance )
{
printf( "Failed to load: %s\n",DLL_NAME );
return false;
}
PFNOPENCOMPILER pfnOpenCompiler = (PFNOPENCOMPILER)GetProcAddress( compilerInstance,g_cOpenCompilerFnName );
if ( !pfnOpenCompiler )
{
printf( "GetProcAddress failed for: %s\n",g_cOpenCompilerFnName );
return false;
}
SFunctionTable functionTable;
SOpenCompiler desc;
desc.InterfaceVersion = 1;
desc.pCompilerFuncs = &functionTable;
/// get the right set of callbacks
if ( !pfnOpenCompiler( desc ) )
{
printf( "OpenCompiler failed\n" );
return false;
}
std::vector< IntelGPUCompiler::PlatformInfo > asics;
GetAsicList( functionTable,asics );
for ( size_t i=0; i<asics.size(); i++ )
printf( "%s\n", asics[i].platformName );
return true;
}
void ShowHelp()
{
printf( "To compile hlsl use: -s hlsl -p <profile> -f <function> <filename>\n" );
printf( "To compile dxbc use: -s dxbc <filename>\n" );
printf( "For details, read the readme\n" );
}
int main(int argc, char *argv[])
{
std::vector<const char*> asicNames;
const char* api = "dx11";
const char* rootsig_file = nullptr;
const char* source_lang = "dxbc";
ToolInputs opts;
FrontendOptions frontend_opts;
// parse the command line. Where possible we have tried to match the syntax of AMD's RGA
int i=1;
while( i < argc )
{
if ( _stricmp( argv[i], "-l" ) == 0 ||
_stricmp( argv[i], "--list-asics" ) == 0 )
{
if ( ListAsics() )
return 0;
else
return 1;
}
else if ( _stricmp( argv[i], "-h" ) == 0 ||
_stricmp( argv[i], "--help" ) == 0 )
{
ShowHelp();
return 0;
}
else if ( _stricmp( argv[i], "-c" ) == 0 ||
_stricmp( argv[i], "--asic" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for --asic\n" );
return 1;
}
asicNames.push_back( argv[++i] );
}
else if ( _stricmp( argv[i],"--api" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for --api\n" );
return 1;
}
api = argv[++i];
}
else if ( _stricmp( argv[i],"--rootsig_file" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for --rootsig_file\n" );
return 1;
}
rootsig_file = argv[++i];
}
else if ( _stricmp( argv[i],"--rootsig_profile" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n", argv[i] );
return 1;
}
frontend_opts.rs_profile = argv[++i];
}
else if ( _stricmp( argv[i],"--rootsig_macro" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n",argv[i] );
return 1;
}
frontend_opts.rs_macro = argv[++i];
}
else if ( _stricmp( argv[i],"--isa" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for --isa\n" );
return 1;
}
opts.isa_prefix = argv[++i];
}
else if ( strcmp( argv[i],"-s" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for -s\n" );
return 1;
}
source_lang = argv[++i];
}
else if ( strcmp( argv[i],"-D" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n", argv[i] );
return 1;
}
char* def = argv[++i];
char* value = def;
while ( *value )
{
if ( *(value++) == '=' )
{
value[-1] = '\0'; // replace '=' with null and stop scanning
break;
}
}
frontend_opts.defines.push_back( std::pair<char*,char*>( def,value ) );
}
else if ( _stricmp( argv[i],"--profile" ) == 0 ||
_stricmp( argv[i], "-p" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n",argv[i] );
return 1;
}
frontend_opts.profile = argv[++i];
}
else if ( _stricmp( argv[i],"--function" ) == 0 ||
_stricmp( argv[i],"-f" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n",argv[i] );
return 1;
}
frontend_opts.entry = argv[++i];
}
else if ( _stricmp( argv[i], "--DXFlags" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n",argv[i] );
return 1;
}
frontend_opts.dx_flags = strtoul( argv[++i], nullptr, 0 );
}
else if ( _stricmp( argv[i],"--DXLocation" ) == 0 )
{
if ( i == argc-1 )
{
printf( "Missing argument for %s\n",argv[i] );
return 1;
}
frontend_opts.dx_location = argv[++i];
}
else if ( argv[i][0] == '-' )
{
printf( "Don't understand what: '%s' means\n",argv[i] );
ShowHelp();
return 1;
}
else
{
frontend_opts.input_file = argv[i];
}
++i;
}
if ( frontend_opts.input_file == nullptr )
{
printf( "No input filename\n" );
return 1;
}
if ( _stricmp( source_lang,"hlsl" ) == 0 )
{
if ( !readAllText( frontend_opts.input_text,frontend_opts.input_file ) )
{
printf( "Failed to read source from: %s\n",frontend_opts.input_file );
return 1;
}
if ( frontend_opts.profile == nullptr )
{
printf( "Missing --profile\n" );
return 1;
}
if ( !CompileHLSL( frontend_opts, opts ) )
return 1;
}
else if ( _stricmp( source_lang,"dxbc" ) == 0 )
{
// load bytecode
if ( frontend_opts.input_file != nullptr )
{
if ( !readAllBytes( opts.bytecode, frontend_opts.input_file ) )
{
printf( "Unable to load bytecode from: %s\n", frontend_opts.input_file );
return 1;
}
}
// try to extract a root signature
if( opts.rootsig.empty() )
{
if( !GetRootSignatureFromDXBC( frontend_opts, opts ) )
{
// failure here indicates DX compiler DLL problems
// diagnostics will happen elsewhere
// Simply not having a root signature is considered success here...
return 1;
}
}
}
else
{
printf( "Source language: '%s' not recognized\n",source_lang );
return 1;
}
// load root signature if we're missing one
if ( opts.rootsig.empty() )
{
if ( rootsig_file != nullptr )
{
if ( !readAllBytes( opts.rootsig, rootsig_file ) )
{
printf( "Unable to load root signature from: %s\n",rootsig_file );
return 1;
}
}
}
// Load compiler DLL
HINSTANCE compilerInstance = (HINSTANCE)LoadLibraryA( DLL_NAME );
if ( !compilerInstance )
{
printf( "Failed to load: %s\n",DLL_NAME );
return 1;
}
PFNOPENCOMPILER pfnOpenCompiler = (PFNOPENCOMPILER)GetProcAddress( compilerInstance,g_cOpenCompilerFnName );
if ( !pfnOpenCompiler )
{
printf( "GetProcAddress failed for: %s\n",g_cOpenCompilerFnName );
return 1;
}
SFunctionTable functionTable;
SOpenCompiler desc;
desc.InterfaceVersion = 1;
desc.pCompilerFuncs = &functionTable;
// get the right set of callbacks
if ( !pfnOpenCompiler( desc ) )
{
printf( "OpenCompiler failed\n" );
return 1;
}
// get list of supported asics
GetAsicList( functionTable,opts.asics );
// filter asic list down to the ones we've been asked to use. By default use all of them
if ( !asicNames.empty() )
{
size_t nAsicsToKeep=0;
for ( size_t i=0; i<opts.asics.size(); i++ )
{
for ( const char* name : asicNames )
if ( _stricmp( name,opts.asics[i].platformName ) == 0 )
opts.asics[nAsicsToKeep++] = opts.asics[i];
}
opts.asics.resize( nAsicsToKeep );
}
// run the tool
if ( _stricmp( api,"dx11" ) == 0 )
{
API_DX11 api;
if( !RunTool( functionTable, opts, api ) )
return 1;
}
else if ( _stricmp( api,"dx12" ) == 0 )
{
API_DX12 api;
if( !RunTool( functionTable, opts, api ) )
return 1;
}
else
{
printf( "Unrecognized API: %s\n",api );
return 1;
}
return 0;
}
| 29.672978 | 136 | 0.533237 | GameTechDev |
f8a8c0029fffaa93ef561ceb3dd3fb9d7e6cf9d7 | 5,677 | hpp | C++ | include/edlib/Basis/Basis1DZ2.hpp | cecri/ExactDiagonalization | a168ed2f60149b1c3e5bd9ae46a5d169aea76773 | [
"MIT"
] | null | null | null | include/edlib/Basis/Basis1DZ2.hpp | cecri/ExactDiagonalization | a168ed2f60149b1c3e5bd9ae46a5d169aea76773 | [
"MIT"
] | null | null | null | include/edlib/Basis/Basis1DZ2.hpp | cecri/ExactDiagonalization | a168ed2f60149b1c3e5bd9ae46a5d169aea76773 | [
"MIT"
] | null | null | null | #pragma once
#include <cassert>
#include <cmath>
#include <map>
#include <vector>
#include <tbb/tbb.h>
#include "AbstractBasis1D.hpp"
#include "BasisJz.hpp"
namespace edlib
{
template<typename UINT> class Basis1DZ2 final : public AbstractBasis1D<UINT>
{
public:
struct RepData
{
int rot;
int parity;
};
private:
const int p_;
tbb::concurrent_vector<std::pair<UINT, RepData>> rpts_;
[[nodiscard]] int phase(int rot) const
{
const auto k = this->getK();
int N = this->getN();
if((k * rot % N) == 0)
{
return 1;
}
else
{
return -1;
}
}
void constructBasis(bool useU1)
{
tbb::concurrent_vector<std::pair<UINT, int>> candids;
const uint32_t N = this->getN();
candids.reserve((1U << (N - 3)) / N);
if(useU1)
{
const uint32_t nup = N / 2;
BasisJz<UINT> basis(N, nup);
tbb::parallel_for_each(basis.begin(), basis.end(), [&](UINT s) {
int r = this->checkState(s);
if(r > 0)
{
candids.emplace_back(s, r);
}
});
}
else
{
{ // insert 0
UINT s = 0;
int r = this->checkState(s);
if(r > 0)
{
candids.emplace_back(s, r);
}
}
// insert other candids. Exclude even as their LSB is 0 (shifted one must be smaller)
tbb::parallel_for(static_cast<UINT>(1), (UINT(1) << UINT(N)), static_cast<UINT>(2),
[&](UINT s) {
int r = this->checkState(s);
if(r > 0)
{
candids.emplace_back(s, r);
}
});
}
tbb::parallel_for(static_cast<std::size_t>(0), candids.size(), [&](std::size_t idx) {
UINT rep = candids[idx].first;
auto s = this->findMinRots(flip(rep));
if(s.first == rep && phase(s.second) * p_ == 1)
{
rpts_.emplace_back(rep, RepData{candids[idx].second, 0});
}
else if(s.first > rep)
{
rpts_.emplace_back(rep, RepData{candids[idx].second, 1});
}
else // s.first < rep
{
;
}
});
// sort to make it consistent over different instances
auto comp = [](const std::pair<UINT, RepData>& v1, const std::pair<UINT, RepData>& v2) {
return v1.first < v2.first;
};
tbb::parallel_sort(rpts_, comp);
}
public:
Basis1DZ2(uint32_t N, uint32_t k, int p, bool useU1) : AbstractBasis1D<UINT>{N, k}, p_(p)
{
assert(k == 0 || ((k == N / 2) && (N % 2 == 0)));
assert(p_ == 1 || p_ == -1);
constructBasis(useU1);
}
[[nodiscard]] uint32_t stateIdx(UINT rep) const
{
auto comp = [](const std::pair<UINT, RepData>& v1, UINT v2) {
return v1.first < v2;
};
auto iter = lower_bound(rpts_.begin(), rpts_.end(), rep, comp);
if((iter == rpts_.end()) || (iter->first != rep))
{
return getDim();
}
else
{
return distance(rpts_.begin(), iter);
}
}
[[nodiscard]] inline UINT flip(UINT value) const { return ((this->getUps()) ^ value); }
[[nodiscard]] inline int getP() const { return p_; }
[[nodiscard]] std::size_t getDim() const override { return rpts_.size(); }
[[nodiscard]] UINT getNthRep(uint32_t n) const override { return rpts_[n].first; }
[[nodiscard]] std::pair<int, double> hamiltonianCoeff(UINT bSigma, int aidx) const override
{
const auto k = this->getK();
double expk = (k == 0) ? 1.0 : -1.0;
auto pa = rpts_[aidx].second;
double Na = 1.0 / double(1 + pa.parity) / pa.rot;
double c = 1.0;
auto [bRep, bRot] = this->findMinRots(bSigma);
auto bidx = stateIdx(bRep);
if(bidx == getDim())
{
c *= p_;
std::tie(bRep, bRot) = this->findMinRots(this->flip(bSigma));
bidx = stateIdx(bRep);
if(bidx == getDim())
{
return std::make_pair(-1, 0.0);
}
}
auto pb = rpts_[bidx].second;
double Nb = 1.0 / double(1 + pb.parity) / pb.rot;
return std::make_pair(bidx, sqrt(Nb / Na) * pow(expk, bRot) * c);
}
/// return a vector of index/value pairs
[[nodiscard]] std::vector<std::pair<UINT, double>> basisVec(uint32_t n) const override
{
const auto k = this->getK();
const double expk = (k == 0) ? 1.0 : -1.0;
std::vector<std::pair<UINT, double>> res;
auto rep = getNthRep(n);
auto p = rpts_[n].second;
double norm = [&p]() {
if(p.parity == 0)
{
return 1.0 / sqrt(p.rot);
}
else
{
return 1.0 / sqrt(2.0 * p.rot);
}
}();
res.reserve(p.rot);
for(int k = 0; k < p.rot; k++)
{
res.emplace_back(this->rotl(rep, k), pow(expk, k) * norm);
}
if(p.parity == 0)
{
return res;
}
rep = this->flip(rep);
res.reserve(2 * p.rot);
for(int k = 0; k < p.rot; k++)
{
res.emplace_back(this->rotl(rep, k), p_ * pow(expk, k) * norm);
}
return res;
}
};
} // namespace edlib
| 26.652582 | 97 | 0.463977 | cecri |
f8aaffce8bea5ce66539b668dc72363536e71556 | 1,594 | cpp | C++ | src/page.windows.cpp | Curve/lime | 91f1132fc550f70627918547f87c687f437ff12a | [
"MIT"
] | 3 | 2021-10-17T17:16:37.000Z | 2022-03-09T07:12:20.000Z | src/page.windows.cpp | Curve/lime | 91f1132fc550f70627918547f87c687f437ff12a | [
"MIT"
] | 12 | 2021-11-09T07:19:34.000Z | 2022-02-28T07:25:15.000Z | src/page.windows.cpp | Curve/lime | 91f1132fc550f70627918547f87c687f437ff12a | [
"MIT"
] | null | null | null | #include "page.hpp"
#include <Windows.h>
namespace lime
{
page::page() : m_prot(0) {}
page::page(const page &) = default;
std::vector<page> page::get_pages()
{
std::vector<page> rtn;
void *address = nullptr;
MEMORY_BASIC_INFORMATION info;
while (VirtualQuery(address, &info, sizeof(info)))
{
if (info.State == MEM_COMMIT && !(info.Protect & PAGE_GUARD))
{
page page;
page.m_prot = info.Protect;
page.m_start = reinterpret_cast<std::uintptr_t>(info.BaseAddress);
page.m_end = page.m_start + info.RegionSize;
rtn.emplace_back(page);
}
address = reinterpret_cast<void *>(reinterpret_cast<std::uintptr_t>(info.BaseAddress) + info.RegionSize);
}
return rtn;
}
std::optional<page> page::get_page_at(const std::uintptr_t &address)
{
MEMORY_BASIC_INFORMATION info;
if (VirtualQuery(reinterpret_cast<void *>(address), &info, sizeof(info)))
{
page rtn;
rtn.m_prot = info.Protect;
rtn.m_start = reinterpret_cast<std::uintptr_t>(info.BaseAddress);
rtn.m_end = rtn.m_start + info.RegionSize;
return rtn;
}
return std::nullopt;
}
std::size_t page::get_end() const
{
return m_end;
}
std::uintptr_t page::get_start() const
{
return m_start;
}
std::uint8_t page::get_protection() const
{
return m_prot;
}
} // namespace lime | 25.709677 | 117 | 0.557716 | Curve |
f8b0a0e35c8190edaabcf3575968bee4af8ca573 | 1,074 | cpp | C++ | meshlib/builder/ConeBuilder.cpp | seanchas116/meshlib | f2b48717667adaff9d70f0e927d1bdd44633beed | [
"MIT"
] | 1 | 2021-02-05T09:59:10.000Z | 2021-02-05T09:59:10.000Z | meshlib/builder/ConeBuilder.cpp | seanchas116/meshlib | f2b48717667adaff9d70f0e927d1bdd44633beed | [
"MIT"
] | null | null | null | meshlib/builder/ConeBuilder.cpp | seanchas116/meshlib | f2b48717667adaff9d70f0e927d1bdd44633beed | [
"MIT"
] | null | null | null | #include "ConeBuilder.hpp"
#include <QtGlobal>
using namespace glm;
namespace meshlib {
Mesh ConeBuilder::build() const {
Mesh mesh;
std::vector<UVPointHandle> uvPoints;
float angleStep = float(M_PI) * 2 / segmentCount;
for (int i = 0; i < segmentCount; ++i) {
float angle = angleStep * i;
vec3 offset(0);
offset[(axis + 1) % 3] = cos(angle);
offset[(axis + 2) % 3] = sin(angle);
vec3 pos = center + offset * radius;
auto uv = mesh.addUVPoint(mesh.addVertex(pos), dvec2(0));
uvPoints.push_back(uv);
}
std::vector<UVPointHandle> reverseUVPoints(uvPoints.rbegin(), uvPoints.rend());
mesh.addFace(reverseUVPoints, material);
vec3 topPosition = center;
topPosition[axis] += height;
auto top = mesh.addUVPoint(mesh.addVertex(topPosition), vec2(0));
for (int i = 0; i < segmentCount; ++i) {
auto v0 = uvPoints[i];
auto v1 = uvPoints[(i + 1) % segmentCount];
mesh.addFace({v0, v1, top}, material);
}
return mesh;
}
} // namespace meshlib
| 25.571429 | 83 | 0.608007 | seanchas116 |
f8b2351a62d6130b2c441d7472fd2e8c9e8c6fb5 | 711 | cpp | C++ | public/plagiarism_plugin/input/24/24/24 24 5113100011--Bounce.cpp | laurensiusadi/elearning-pweb | c72ae1fc414895919ef71ae370686353d9086bce | [
"MIT"
] | null | null | null | public/plagiarism_plugin/input/24/24/24 24 5113100011--Bounce.cpp | laurensiusadi/elearning-pweb | c72ae1fc414895919ef71ae370686353d9086bce | [
"MIT"
] | null | null | null | public/plagiarism_plugin/input/24/24/24 24 5113100011--Bounce.cpp | laurensiusadi/elearning-pweb | c72ae1fc414895919ef71ae370686353d9086bce | [
"MIT"
] | null | null | null | #include <wx/wx.h>
#include "Bounce.h"
Bounce::Bounce(float x, float y)
{
this->x = x;
this->y = y;
radius = 30;
speedX = 20;
speedY = 20;
}
void Bounce::HitWall(int x1, int y1, int x2, int y2)
{
if ((x - radius) < x1 || (x + radius) > x2)
{
speedX = -speedX;
}
if ((y - radius) < y1 || (y + radius) > y2)
{
speedY = -speedY;
}
}
void Bounce::Collides(Bounce *otherBall)
{
int xd = x - otherBall->x;
int yd = y - otherBall->y;
float sumRadius = radius + otherBall->radius;
float sqrRadius = sumRadius = sumRadius*sumRadius;
float distSqr = (xd*xd) + (yd*yd);
if (distSqr <= sqrRadius)
{
speedX *= -1;
speedY *= -1;
}
}
void Bounce::move()
{
x = x + speedX;
y = y + speedY;
}
| 15.12766 | 52 | 0.576653 | laurensiusadi |
f8b7af427fa13d2ec2c44abbafe2532e7ff7c41e | 3,633 | cpp | C++ | 12_dynamic_2/12_distinct_subseq.cpp | ShyamNandanKumar/coding-ninja2 | a43a21575342261e573f71f7d8eff0572f075a17 | [
"MIT"
] | 11 | 2021-01-02T10:07:17.000Z | 2022-03-16T00:18:06.000Z | 12_dynamic_2/12_distinct_subseq.cpp | meyash/cp_master | 316bf47db2a5b40891edd73cff834517993c3d2a | [
"MIT"
] | null | null | null | 12_dynamic_2/12_distinct_subseq.cpp | meyash/cp_master | 316bf47db2a5b40891edd73cff834517993c3d2a | [
"MIT"
] | 5 | 2021-05-19T11:17:18.000Z | 2021-09-16T06:23:31.000Z | /*
Given a string, count the number of distinct subsequences of it ( including empty subsequence ). For the uninformed, A subsequence of a string is a new string which is formed from the original string by deleting some of the characters without disturbing the relative positions of the remaining characters.
For example, "AGH" is a subsequence of "ABCDEFGH" while "AHG" is not.
Input
First line of input contains an integer T which is equal to the number of test cases. You are required to process all test cases. Each of next T lines contains a string s.
Output
Output consists of T lines. Ith line in the output corresponds to the number of distinct subsequences of ith input string. Since, this number could be very large, you need to output ans%1000000007 where ans is the number of distinct subsequences.
Constraints and Limits
T ≤ 100, length(S) ≤ 100000
All input strings shall contain only uppercase letters.
Sample Input
3
AAA
ABCDEFG
CODECRAFT
Sample Output
4
128
496
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mod 1000000007
ll all_subseq(string s){
int len=s.length();
// to store no of subseq upto each index
ll *dp=new ll[len+1];
// to store previous occurance index of characters
// map is showing TLE
// map<char,int> m;
ll *previndice=new ll[26];
for(int i=0;i<26;i++){
previndice[i]=-1;
}
// empty string 1 possibility
dp[0]=1;
for(ll i=1;i<=len;i++){
dp[i]=(dp[i-1]*2)%mod;
// if(m[s[i-1]]!=0){
if(previndice[s[i-1]-65]!=-1){
//as it may go negative, +m %m will give us the required answer
// dp[i]=(dp[i]-dp[m[s[i-1]]-1]+mod)%mod;
dp[i]=(dp[i]-dp[previndice[s[i-1]-65]-1]+mod)%mod;
}
// m[s[i-1]]=i;
previndice[s[i-1]-65]=i;
}
ll ans=dp[len]%mod;
delete dp;
delete previndice;
return ans;
}
// recursive approach TLE
// void all_subseq(string input,string output,map<string,int> &m){
// if(input==""){
// if(output==""){
// m[" "]=1;
// }else{
// m[output]=1;
// }
// return;
// }
// // for each char in string we have 2 options
// // include
// all_subseq(input.substr(1),output+input[0],m);
// // not include
// all_subseq(input.substr(1),output,m);
// }
// TLE coming in some cases
// ll all_subseq(string s){
// map<string,int> m;
// map<string,int>::iterator it;
// // go from end to start ans find all subseq starting at current index
// for(int i=s.length()-1;i>=0;i--){
// map<string,int> m_curr;
// map<string,int>::iterator it_curr;
// // generate new subsequences from previous, by adding just current char in front of all previous
// for(it=m.begin();it!=m.end();it++){
// string curr_s=s[i]+it->first;
// m_curr[curr_s]++;
// }
// // single current char is also a subseq
// string single(1,s[i]);
// m[single]++;
// // add all newly generated subseq to the map
// for(it=m_curr.begin();it!=m_curr.end();it++){
// m[it->first]=1;
// }
// }
// // empty is also a subseq
// m[" "]++;
// return m.size()%mod;
// }
int main()
{
int t;
cin>>t;
while(t--){
string s;
cin>>s;
map<string,int> m;
cout<<all_subseq(s)<<endl;
// cout<<all_subseq(s)<<endl;
// string out;
// all_subseq(s,out,m);
// cout<<m.size()<<endl;
}
return 0;
}
| 28.606299 | 305 | 0.576658 | ShyamNandanKumar |
f8b9cb291b22295c778536309e5bfb19a57df14b | 987 | cpp | C++ | Code/Lib/sfmTargetedPedestrian.cpp | johnduffymsc/PHAS0100Assignment2 | d6dfe3dc102c14f441c1d6f334f0efd178728bd9 | [
"BSD-3-Clause"
] | null | null | null | Code/Lib/sfmTargetedPedestrian.cpp | johnduffymsc/PHAS0100Assignment2 | d6dfe3dc102c14f441c1d6f334f0efd178728bd9 | [
"BSD-3-Clause"
] | null | null | null | Code/Lib/sfmTargetedPedestrian.cpp | johnduffymsc/PHAS0100Assignment2 | d6dfe3dc102c14f441c1d6f334f0efd178728bd9 | [
"BSD-3-Clause"
] | 3 | 2021-02-12T14:27:32.000Z | 2021-04-04T00:09:33.000Z | /*=============================================================================
PHAS0100ASSIGNMENT2: PHAS0100 Assignment 2 Social Force Model
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
Author: John Duffy
=============================================================================*/
#include "sfmTypes.h"
#include "sfmPedestrian.h"
#include "sfmTargetedPedestrian.h"
#include <iostream>
namespace sfm {
TargetedPedestrian::TargetedPedestrian(Pos2d origin, Pos2d destination, double desired_speed, double relaxation_time)
: Pedestrian(origin, destination, desired_speed, relaxation_time) {}
TargetedPedestrian::~TargetedPedestrian() {}
Pos2d TargetedPedestrian::GetTarget(void) {
return destination;
}
} // end namespace
| 27.416667 | 119 | 0.646403 | johnduffymsc |
f8c1d37137f68f9c05fb5a4d8efc8ea52dc0f6fa | 26,155 | cpp | C++ | webcl/dxtcompressor/common/src/oclUtils.cpp | wolfviking0/webcl-translator | af173ef4617b310fd27c325bdd4a947728459302 | [
"MIT"
] | 19 | 2015-03-05T19:28:54.000Z | 2021-05-18T12:16:24.000Z | webcl/dxtcompressor/common/src/oclUtils.cpp | wolfviking0/webcl-translator | af173ef4617b310fd27c325bdd4a947728459302 | [
"MIT"
] | null | null | null | webcl/dxtcompressor/common/src/oclUtils.cpp | wolfviking0/webcl-translator | af173ef4617b310fd27c325bdd4a947728459302 | [
"MIT"
] | 5 | 2015-10-16T07:01:11.000Z | 2020-05-27T06:12:50.000Z | /*
* Copyright 1993-2009 NVIDIA Corporation. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and
* proprietary rights in and to this software and related documentation.
* Any use, reproduction, disclosure, or distribution of this software
* and related documentation without an express license agreement from
* NVIDIA Corporation is strictly prohibited.
*
* Please refer to the applicable NVIDIA end user license agreement (EULA)
* associated with this source code for terms and conditions that govern
* your use of this NVIDIA software.
*
*/
// *********************************************************************
// Utilities for NVIDIA OpenCL SDK
// *********************************************************************
#include "oclUtils.h"
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdarg.h>
// size of PGM file header
const unsigned int PGMHeaderSize = 0x40;
//////////////////////////////////////////////////////////////////////////////
//! Gets the platform ID for NVIDIA if available, otherwise default
//!
//! @return the id
//! @param clSelectedPlatformID OpenCL platoform ID
//////////////////////////////////////////////////////////////////////////////
cl_int oclGetPlatformID(cl_platform_id* clSelectedPlatformID)
{
char chBuffer[1024];
cl_uint num_platforms;
cl_platform_id* clPlatformIDs;
cl_int ciErrNum;
// Get OpenCL platform count
ciErrNum = clGetPlatformIDs (0, NULL, &num_platforms);
if (ciErrNum != CL_SUCCESS)
{
shrLog(LOGBOTH, 0, " Error %i in clGetPlatformIDs Call !!!\n\n", ciErrNum);
return -1000;
}
else
{
if(num_platforms == 0)
{
shrLog(LOGBOTH, 0, "No OpenCL platform found!\n\n");
return -2000;
}
else
{
// if there's a platform or more, make space for ID's
if ((clPlatformIDs = (cl_platform_id*)malloc(num_platforms * sizeof(cl_platform_id))) == NULL)
{
shrLog(LOGBOTH, 0, "Failed to allocate memory for cl_platform ID's!\n\n");
return -3000;
}
// get platform info for each platform and trap the NVIDIA platform if found
ciErrNum = clGetPlatformIDs (num_platforms, clPlatformIDs, NULL);
for(cl_uint i = 0; i < num_platforms; ++i)
{
ciErrNum = clGetPlatformInfo (clPlatformIDs[i], CL_PLATFORM_NAME, 1024, &chBuffer, NULL);
if(ciErrNum == CL_SUCCESS)
{
if(strstr(chBuffer, "NVIDIA") != NULL)
{
*clSelectedPlatformID = clPlatformIDs[i];
break;
}
}
}
// default to zeroeth platform if NVIDIA not found
if(*clSelectedPlatformID == NULL)
{
shrLog(LOGBOTH, 0, "WARNING: NVIDIA OpenCL platform not found - defaulting to first platform!\n\n");
*clSelectedPlatformID = clPlatformIDs[0];
}
free(clPlatformIDs);
}
}
return CL_SUCCESS;
}
//////////////////////////////////////////////////////////////////////////////
//! Print info about the device
//!
//! @param iLogMode enum LOGBOTH, LOGCONSOLE, LOGFILE
//! @param device OpenCL id of the device
//////////////////////////////////////////////////////////////////////////////
void oclPrintDevName(int iLogMode, cl_device_id device)
{
char device_string[1024];
clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_string), &device_string, NULL);
shrLog(iLogMode, 0.0, " Device %s\n", device_string);
}
//////////////////////////////////////////////////////////////////////////////
//! Print info about the device
//!
//! @param iLogMode enum LOGBOTH, LOGCONSOLE, LOGFILE
//! @param device OpenCL id of the device
//////////////////////////////////////////////////////////////////////////////
void oclPrintDevInfo(int iLogMode, cl_device_id device)
{
char device_string[1024];
bool nv_device_attibute_query = false;
// CL_DEVICE_NAME
clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_string), &device_string, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_NAME: \t\t\t%s\n", device_string);
// CL_DEVICE_VENDOR
clGetDeviceInfo(device, CL_DEVICE_VENDOR, sizeof(device_string), &device_string, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_VENDOR: \t\t\t%s\n", device_string);
// CL_DRIVER_VERSION
clGetDeviceInfo(device, CL_DRIVER_VERSION, sizeof(device_string), &device_string, NULL);
shrLog(iLogMode, 0.0, " CL_DRIVER_VERSION: \t\t\t%s\n", device_string);
// CL_DEVICE_INFO
cl_device_type type;
clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(type), &type, NULL);
if( type & CL_DEVICE_TYPE_CPU )
shrLog(iLogMode, 0.0, " CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_CPU");
if( type & CL_DEVICE_TYPE_GPU )
shrLog(iLogMode, 0.0, " CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_GPU");
if( type & CL_DEVICE_TYPE_ACCELERATOR )
shrLog(iLogMode, 0.0, " CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_ACCELERATOR");
if( type & CL_DEVICE_TYPE_DEFAULT )
shrLog(iLogMode, 0.0, " CL_DEVICE_TYPE:\t\t\t%s\n", "CL_DEVICE_TYPE_DEFAULT");
// CL_DEVICE_MAX_COMPUTE_UNITS
cl_uint compute_units;
clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(compute_units), &compute_units, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_COMPUTE_UNITS:\t\t%u\n", compute_units);
// CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS
size_t workitem_dims;
clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(workitem_dims), &workitem_dims, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS:\t%u\n", workitem_dims);
// CL_DEVICE_MAX_WORK_ITEM_SIZES
size_t workitem_size[3];
clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(workitem_size), &workitem_size, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_WORK_ITEM_SIZES:\t%u / %u / %u \n", workitem_size[0], workitem_size[1], workitem_size[2]);
// CL_DEVICE_MAX_WORK_GROUP_SIZE
size_t workgroup_size;
clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(workgroup_size), &workgroup_size, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_WORK_GROUP_SIZE:\t%u\n", workgroup_size);
// CL_DEVICE_MAX_CLOCK_FREQUENCY
cl_uint clock_frequency;
clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(clock_frequency), &clock_frequency, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_CLOCK_FREQUENCY:\t%u MHz\n", clock_frequency);
// CL_DEVICE_ADDRESS_BITS
cl_uint addr_bits;
clGetDeviceInfo(device, CL_DEVICE_ADDRESS_BITS, sizeof(addr_bits), &addr_bits, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_ADDRESS_BITS:\t\t%u\n", addr_bits);
// CL_DEVICE_MAX_MEM_ALLOC_SIZE
cl_ulong max_mem_alloc_size;
clGetDeviceInfo(device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(max_mem_alloc_size), &max_mem_alloc_size, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_MEM_ALLOC_SIZE:\t\t%u MByte\n", (unsigned int)(max_mem_alloc_size / (1024 * 1024)));
// CL_DEVICE_GLOBAL_MEM_SIZE
cl_ulong mem_size;
clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(mem_size), &mem_size, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_GLOBAL_MEM_SIZE:\t\t%u MByte\n", (unsigned int)(mem_size / (1024 * 1024)));
// CL_DEVICE_ERROR_CORRECTION_SUPPORT
cl_bool error_correction_support;
clGetDeviceInfo(device, CL_DEVICE_ERROR_CORRECTION_SUPPORT, sizeof(error_correction_support), &error_correction_support, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_ERROR_CORRECTION_SUPPORT:\t%s\n", error_correction_support == CL_TRUE ? "yes" : "no");
// CL_DEVICE_LOCAL_MEM_TYPE
cl_device_local_mem_type local_mem_type;
clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_TYPE, sizeof(local_mem_type), &local_mem_type, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_LOCAL_MEM_TYPE:\t\t%s\n", local_mem_type == 1 ? "local" : "global");
// CL_DEVICE_LOCAL_MEM_SIZE
clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(mem_size), &mem_size, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_LOCAL_MEM_SIZE:\t\t%u KByte\n", (unsigned int)(mem_size / 1024));
// CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
clGetDeviceInfo(device, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, sizeof(mem_size), &mem_size, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE:\t%u KByte\n", (unsigned int)(mem_size / 1024));
// CL_DEVICE_QUEUE_PROPERTIES
cl_command_queue_properties queue_properties;
clGetDeviceInfo(device, CL_DEVICE_QUEUE_PROPERTIES, sizeof(queue_properties), &queue_properties, NULL);
if( queue_properties & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE )
shrLog(iLogMode, 0.0, " CL_DEVICE_QUEUE_PROPERTIES:\t\t%s\n", "CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE");
if( queue_properties & CL_QUEUE_PROFILING_ENABLE )
shrLog(iLogMode, 0.0, " CL_DEVICE_QUEUE_PROPERTIES:\t\t%s\n", "CL_QUEUE_PROFILING_ENABLE");
// CL_DEVICE_IMAGE_SUPPORT
cl_bool image_support;
clGetDeviceInfo(device, CL_DEVICE_IMAGE_SUPPORT, sizeof(image_support), &image_support, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_IMAGE_SUPPORT:\t\t%u\n", image_support);
// CL_DEVICE_MAX_READ_IMAGE_ARGS
cl_uint max_read_image_args;
clGetDeviceInfo(device, CL_DEVICE_MAX_READ_IMAGE_ARGS, sizeof(max_read_image_args), &max_read_image_args, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_READ_IMAGE_ARGS:\t%u\n", max_read_image_args);
// CL_DEVICE_MAX_WRITE_IMAGE_ARGS
cl_uint max_write_image_args;
clGetDeviceInfo(device, CL_DEVICE_MAX_WRITE_IMAGE_ARGS, sizeof(max_write_image_args), &max_write_image_args, NULL);
shrLog(iLogMode, 0.0, " CL_DEVICE_MAX_WRITE_IMAGE_ARGS:\t%u\n", max_write_image_args);
// CL_DEVICE_IMAGE2D_MAX_WIDTH, CL_DEVICE_IMAGE2D_MAX_HEIGHT, CL_DEVICE_IMAGE3D_MAX_WIDTH, CL_DEVICE_IMAGE3D_MAX_HEIGHT, CL_DEVICE_IMAGE3D_MAX_DEPTH
size_t szMaxDims[5];
shrLog(iLogMode, 0.0, "\n CL_DEVICE_IMAGE <dim>");
clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t), &szMaxDims[0], NULL);
shrLog(iLogMode, 0.0, "\t\t\t2D_MAX_WIDTH\t %u\n", szMaxDims[0]);
clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t), &szMaxDims[1], NULL);
shrLog(iLogMode, 0.0, "\t\t\t\t\t2D_MAX_HEIGHT\t %u\n", szMaxDims[1]);
clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof(size_t), &szMaxDims[2], NULL);
shrLog(iLogMode, 0.0, "\t\t\t\t\t3D_MAX_WIDTH\t %u\n", szMaxDims[2]);
clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof(size_t), &szMaxDims[3], NULL);
shrLog(iLogMode, 0.0, "\t\t\t\t\t3D_MAX_HEIGHT\t %u\n", szMaxDims[3]);
clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof(size_t), &szMaxDims[4], NULL);
shrLog(iLogMode, 0.0, "\t\t\t\t\t3D_MAX_DEPTH\t %u\n", szMaxDims[4]);
// CL_DEVICE_EXTENSIONS: get device extensions, and if any then parse & log the string onto separate lines
clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, sizeof(device_string), &device_string, NULL);
if (device_string != 0)
{
shrLog(iLogMode, 0.0, "\n CL_DEVICE_EXTENSIONS:");
std::string stdDevString;
stdDevString = std::string(device_string);
size_t szOldPos = 0;
size_t szSpacePos = stdDevString.find(' ', szOldPos); // extensions string is space delimited
while (szSpacePos != stdDevString.npos && (szSpacePos - szOldPos) > 0)
{
if( strcmp("cl_nv_device_attribute_query", stdDevString.substr(szOldPos, szSpacePos - szOldPos).c_str()) == 0 )
nv_device_attibute_query = true;
if (szOldPos > 0)
{
shrLog(iLogMode, 0.0, "\t\t");
}
shrLog(iLogMode, 0.0, "\t\t\t%s\n", stdDevString.substr(szOldPos, szSpacePos - szOldPos).c_str());
szOldPos = szSpacePos + 1;
szSpacePos = stdDevString.find(' ', szOldPos);
}
}
else
{
shrLog(iLogMode, 0.0, " CL_DEVICE_EXTENSIONS: None\n");
}
if(nv_device_attibute_query)
{
cl_uint compute_capability_major, compute_capability_minor;
clGetDeviceInfo(device, CL_NV_DEVICE_COMPUTE_CAPABILITY_MAJOR, sizeof(cl_uint), &compute_capability_major, NULL);
clGetDeviceInfo(device, CL_NV_DEVICE_COMPUTE_CAPABILITY_MINOR, sizeof(cl_uint), &compute_capability_minor, NULL);
shrLog(iLogMode, 0.0, "\n CL_NV_DEVICE_COMPUTE_CAPABILITY:\t%u.%u\n", compute_capability_major, compute_capability_minor);
cl_uint regs_per_block;
clGetDeviceInfo(device, CL_NV_DEVICE_REGISTERS_PER_BLOCK, sizeof(cl_uint), ®s_per_block, NULL);
shrLog(iLogMode, 0.0, " CL_NV_DEVICE_REGISTERS_PER_BLOCK:\t%u\n", regs_per_block);
cl_uint warp_size;
clGetDeviceInfo(device, CL_NV_DEVICE_WARP_SIZE, sizeof(cl_uint), &warp_size, NULL);
shrLog(iLogMode, 0.0, " CL_NV_DEVICE_WARP_SIZE:\t\t%u\n", warp_size);
cl_bool gpu_overlap;
clGetDeviceInfo(device, CL_NV_DEVICE_GPU_OVERLAP, sizeof(cl_bool), &gpu_overlap, NULL);
shrLog(iLogMode, 0.0, " CL_NV_DEVICE_GPU_OVERLAP:\t\t%s\n", gpu_overlap == CL_TRUE ? "CL_TRUE" : "CL_FALSE");
cl_bool exec_timeout;
clGetDeviceInfo(device, CL_NV_DEVICE_KERNEL_EXEC_TIMEOUT, sizeof(cl_bool), &exec_timeout, NULL);
shrLog(iLogMode, 0.0, " CL_NV_DEVICE_KERNEL_EXEC_TIMEOUT:\t%s\n", exec_timeout == CL_TRUE ? "CL_TRUE" : "CL_FALSE");
cl_bool integrated_memory;
clGetDeviceInfo(device, CL_NV_DEVICE_INTEGRATED_MEMORY, sizeof(cl_bool), &integrated_memory, NULL);
shrLog(iLogMode, 0.0, " CL_NV_DEVICE_INTEGRATED_MEMORY:\t%s\n", integrated_memory == CL_TRUE ? "CL_TRUE" : "CL_FALSE");
}
// CL_DEVICE_PREFERRED_VECTOR_WIDTH_<type>
shrLog(iLogMode, 0.0, " CL_DEVICE_PREFERRED_VECTOR_WIDTH_<t>\t");
cl_uint vec_width [6];
clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, sizeof(cl_uint), &vec_width[0], NULL);
clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, sizeof(cl_uint), &vec_width[1], NULL);
clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), &vec_width[2], NULL);
clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG, sizeof(cl_uint), &vec_width[3], NULL);
clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(cl_uint), &vec_width[4], NULL);
clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, sizeof(cl_uint), &vec_width[5], NULL);
shrLog(iLogMode, 0.0, "CHAR %u, SHORT %u, INT %u, FLOAT %u, DOUBLE %u\n\n\n",
vec_width[0], vec_width[1], vec_width[2], vec_width[3], vec_width[4]);
}
//////////////////////////////////////////////////////////////////////////////
//! Gets the id of the first device from the context
//!
//! @return the id
//! @param cxGPUContext OpenCL context
//////////////////////////////////////////////////////////////////////////////
cl_device_id oclGetFirstDev(cl_context cxGPUContext)
{
size_t szParmDataBytes;
cl_device_id* cdDevices;
// get the list of GPU devices associated with context
clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
cdDevices = (cl_device_id*) malloc(szParmDataBytes);
clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);
cl_device_id first = cdDevices[0];
free(cdDevices);
return first;
}
//////////////////////////////////////////////////////////////////////////////
//! Gets the id of device with maximal FLOPS from the context
//!
//! @return the id
//! @param cxGPUContext OpenCL context
//////////////////////////////////////////////////////////////////////////////
cl_device_id oclGetMaxFlopsDev(cl_context cxGPUContext)
{
size_t szParmDataBytes;
cl_device_id* cdDevices;
// get the list of GPU devices associated with context
clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
cdDevices = (cl_device_id*) malloc(szParmDataBytes);
size_t device_count = szParmDataBytes / sizeof(cl_device_id);
clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);
cl_device_id max_flops_device = cdDevices[0];
int max_flops = 0;
size_t current_device = 0;
// CL_DEVICE_MAX_COMPUTE_UNITS
cl_uint compute_units;
clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(compute_units), &compute_units, NULL);
// CL_DEVICE_MAX_CLOCK_FREQUENCY
cl_uint clock_frequency;
clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(clock_frequency), &clock_frequency, NULL);
max_flops = compute_units * clock_frequency;
++current_device;
while( current_device < device_count )
{
// CL_DEVICE_MAX_COMPUTE_UNITS
cl_uint compute_units;
clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(compute_units), &compute_units, NULL);
// CL_DEVICE_MAX_CLOCK_FREQUENCY
cl_uint clock_frequency;
clGetDeviceInfo(cdDevices[current_device], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(clock_frequency), &clock_frequency, NULL);
int flops = compute_units * clock_frequency;
if( flops > max_flops )
{
max_flops = flops;
max_flops_device = cdDevices[current_device];
}
++current_device;
}
free(cdDevices);
return max_flops_device;
}
//////////////////////////////////////////////////////////////////////////////
//! Loads a Program file and prepends the cPreamble to the code.
//!
//! @return the source string if succeeded, 0 otherwise
//! @param cFilename program filename
//! @param cPreamble code that is prepended to the loaded file, typically a set of #defines or a header
//! @param szFinalLength returned length of the code string
//////////////////////////////////////////////////////////////////////////////
char* oclLoadProgSource(const char* cFilename, const char* cPreamble, size_t* szFinalLength)
{
// locals
FILE* pFileStream = NULL;
size_t szSourceLength;
// open the OpenCL source code file
#ifdef _WIN32 // Windows version
if(fopen_s(&pFileStream, cFilename, "rb") != 0)
{
return NULL;
}
#else // Linux version
pFileStream = fopen(cFilename, "rb");
if(pFileStream == 0)
{
return NULL;
}
#endif
size_t szPreambleLength = strlen(cPreamble);
// get the length of the source code
fseek(pFileStream, 0, SEEK_END);
szSourceLength = ftell(pFileStream);
fseek(pFileStream, 0, SEEK_SET);
// allocate a buffer for the source code string and read it in
char* cSourceString = (char *)malloc(szSourceLength + szPreambleLength + 1);
memcpy(cSourceString, cPreamble, szPreambleLength);
if (fread((cSourceString) + szPreambleLength, szSourceLength, 1, pFileStream) != 1)
{
fclose(pFileStream);
free(cSourceString);
return 0;
}
// close the file and return the total length of the combined (preamble + source) string
fclose(pFileStream);
if(szFinalLength != 0)
{
*szFinalLength = szSourceLength + szPreambleLength;
}
cSourceString[szSourceLength + szPreambleLength] = '\0';
return cSourceString;
}
//////////////////////////////////////////////////////////////////////////////
//! Gets the id of the nth device from the context
//!
//! @return the id or -1 when out of range
//! @param cxGPUContext OpenCL context
//! @param device_idx index of the device of interest
//////////////////////////////////////////////////////////////////////////////
cl_device_id oclGetDev(cl_context cxGPUContext, unsigned int nr)
{
size_t szParmDataBytes;
cl_device_id* cdDevices;
// get the list of GPU devices associated with context
clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
if( szParmDataBytes / sizeof(cl_device_id) < nr ) {
return (cl_device_id)-1;
}
cdDevices = (cl_device_id*) malloc(szParmDataBytes);
clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);
cl_device_id device = cdDevices[nr];
free(cdDevices);
return device;
}
//////////////////////////////////////////////////////////////////////////////
//! Get the binary (PTX) of the program associated with the device
//!
//! @param cpProgram OpenCL program
//! @param cdDevice device of interest
//! @param binary returned code
//! @param length length of returned code
//////////////////////////////////////////////////////////////////////////////
void oclGetProgBinary( cl_program cpProgram, cl_device_id cdDevice, char** binary, size_t* length)
{
// Grab the number of devices associated witht the program
cl_uint num_devices;
clGetProgramInfo(cpProgram, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &num_devices, NULL);
// Grab the device ids
cl_device_id* devices = (cl_device_id*) malloc(num_devices * sizeof(cl_device_id));
clGetProgramInfo(cpProgram, CL_PROGRAM_DEVICES, num_devices * sizeof(cl_device_id), devices, 0);
// Grab the sizes of the binaries
size_t* binary_sizes = (size_t*)malloc(num_devices * sizeof(size_t));
clGetProgramInfo(cpProgram, CL_PROGRAM_BINARY_SIZES, num_devices * sizeof(size_t), binary_sizes, NULL);
// Now get the binaries
char** ptx_code = (char**) malloc(num_devices * sizeof(char*));
for( unsigned int i=0; i<num_devices; ++i) {
ptx_code[i]= (char*)malloc(binary_sizes[i]);
}
clGetProgramInfo(cpProgram, CL_PROGRAM_BINARIES, 0, ptx_code, NULL);
// Find the index of the device of interest
unsigned int idx = 0;
while( idx<num_devices && devices[idx] != cdDevice ) ++idx;
// If it is associated prepare the result
if( idx < num_devices )
{
*binary = ptx_code[idx];
*length = binary_sizes[idx];
}
// Cleanup
free( devices );
free( binary_sizes );
for( unsigned int i=0; i<num_devices; ++i) {
if( i != idx ) free(ptx_code[i]);
}
free( ptx_code );
}
//////////////////////////////////////////////////////////////////////////////
//! Get and log the binary (PTX) from the OpenCL compiler for the requested program & device
//!
//! @param cpProgram OpenCL program
//! @param cdDevice device of interest
//! @param const char* cPtxFileName optional PTX file name
//////////////////////////////////////////////////////////////////////////////
void oclLogPtx(cl_program cpProgram, cl_device_id cdDevice, const char* cPtxFileName)
{
// Grab the number of devices associated with the program
cl_uint num_devices;
clGetProgramInfo(cpProgram, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &num_devices, NULL);
// Grab the device ids
cl_device_id* devices = (cl_device_id*) malloc(num_devices * sizeof(cl_device_id));
clGetProgramInfo(cpProgram, CL_PROGRAM_DEVICES, num_devices * sizeof(cl_device_id), devices, 0);
// Grab the sizes of the binaries
size_t* binary_sizes = (size_t*)malloc(num_devices * sizeof(size_t));
clGetProgramInfo(cpProgram, CL_PROGRAM_BINARY_SIZES, num_devices * sizeof(size_t), binary_sizes, NULL);
// Now get the binaries
char** ptx_code = (char**)malloc(num_devices * sizeof(char*));
for( unsigned int i=0; i<num_devices; ++i)
{
ptx_code[i] = (char*)malloc(binary_sizes[i]);
}
clGetProgramInfo(cpProgram, CL_PROGRAM_BINARIES, 0, ptx_code, NULL);
// Find the index of the device of interest
unsigned int idx = 0;
while((idx < num_devices) && (devices[idx] != cdDevice))
{
++idx;
}
// If the index is associated, log the result
if(idx < num_devices)
{
// if a separate filename is supplied, dump ptx there
if (NULL != cPtxFileName)
{
shrLog(LOGBOTH, 0, "\nWriting ptx to separate file: %s ...\n\n", cPtxFileName);
FILE* pFileStream = NULL;
#ifdef _WIN32
fopen_s(&pFileStream, cPtxFileName, "wb");
#else
pFileStream = fopen(cPtxFileName, "wb");
#endif
fwrite(ptx_code[idx], binary_sizes[idx], 1, pFileStream);
fclose(pFileStream);
}
else // log to logfile and console if no ptx file specified
{
shrLog(LOGBOTH, 0, "\n%s\nProgram Binary:\n%s\n%s\n", HDASHLINE, ptx_code[idx], HDASHLINE);
}
}
// Cleanup
free(devices);
free(binary_sizes);
for(unsigned int i = 0; i < num_devices; ++i)
{
free(ptx_code[i]);
}
free( ptx_code );
}
//////////////////////////////////////////////////////////////////////////////
//! Get and log the binary (PTX) from the OpenCL compiler for the requested program & device
//!
//! @param cpProgram OpenCL program
//! @param cdDevice device of interest
//////////////////////////////////////////////////////////////////////////////
void oclLogBuildInfo(cl_program cpProgram, cl_device_id cdDevice)
{
// write out the build log and ptx, then exit
char cBuildLog[10240];
clGetProgramBuildInfo(cpProgram, cdDevice, CL_PROGRAM_BUILD_LOG,
sizeof(cBuildLog), cBuildLog, NULL );
shrLog(LOGBOTH, 0, "\n%s\nBuild Log:\n%s\n%s\n", HDASHLINE, cBuildLog, HDASHLINE);
}
// Helper function for De-allocating cl objects
// *********************************************************************
void oclDeleteMemObjs(cl_mem* cmMemObjs, int iNumObjs)
{
int i;
for (i = 0; i < iNumObjs; i++)
{
if (cmMemObjs[i])clReleaseMemObject(cmMemObjs[i]);
}
}
| 42.253635 | 152 | 0.640145 | wolfviking0 |
f8c4b39e8ea1e07dc84794fb7d54c7ecd8c5e7af | 1,819 | cpp | C++ | rawtotxt.cpp | DBFritz/ParticleDetections | cd05979c58b79c27259479e948c445867a7a838f | [
"MIT"
] | 1 | 2018-04-05T02:26:57.000Z | 2018-04-05T02:26:57.000Z | rawtotxt.cpp | DBFritz/ParticleDetections | cd05979c58b79c27259479e948c445867a7a838f | [
"MIT"
] | null | null | null | rawtotxt.cpp | DBFritz/ParticleDetections | cd05979c58b79c27259479e948c445867a7a838f | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "rawImages.hpp"
#include "rawFilters.hpp"
int main(int argc, char *argv[])
{
using namespace std;
using namespace raw;
const int width=2592, height=1944;
rawPhoto_t photo(width,height);
switch (argc)
{
case 1:
for(int f=1; ;f++) // the first two images are bullsh**
{
char pathRaw[64];
char pathTxt[64];
sprintf(pathRaw, "/dev/shm/out.%04d.raw", f);
cout << "Intentando con el archivo " << pathRaw << '\r' << flush;
cout << " \r";
sprintf(pathTxt, "/dev/shm/out.%04d.txt", f);
photo.raspiraw(pathRaw);
if (photo.isEmpty()) return 0;
ofstream output(pathTxt);
if ( !output.is_open() ) {
cerr << "Error al abrir el archivo " << pathTxt << endl;
return -1;
}
photo.print(output);
}
break;
case 2:
cout << "Usage: " << argv[0] << " /pathto/source /pathto/destination" << endl;
break;
case 3:
photo.raspiraw(argv[1]);
if ( photo.isEmpty() ) {
cerr << "Error al abrir el archivo " << argv[1] << endl;
}
if (!photo.isValid()) cerr << "Hay un pixel mas grande de lo que deberia" << endl;
substract_mean_per_column(photo);
ofstream output(argv[2]);
if ( !output.is_open() ) {
cerr << "Error al escribir en el archivo " << argv[2] << endl;
return -1;
}
photo.print(output);
}
return 0;
}
| 28.873016 | 94 | 0.446949 | DBFritz |
f8c7316af82616a715047f22194c1e749a6e03b9 | 17,614 | cpp | C++ | frontend/module.cpp | llpm/SpatialC | 618d86fe948a7839fe4903a77da08941e169ae2e | [
"Apache-2.0"
] | null | null | null | frontend/module.cpp | llpm/SpatialC | 618d86fe948a7839fe4903a77da08941e169ae2e | [
"Apache-2.0"
] | null | null | null | frontend/module.cpp | llpm/SpatialC | 618d86fe948a7839fe4903a77da08941e169ae2e | [
"Apache-2.0"
] | null | null | null | #include "module.hpp"
#include <frontend/exception.hpp>
#include <frontend/event.hpp>
#include <frontend/expression.hpp>
#include <libraries/core/logic_intr.hpp>
#include <libraries/core/comm_intr.hpp>
#include <analysis/constant.hpp>
#include <llvm/IR/Constants.h>
#include <boost/format.hpp>
using namespace std;
namespace spatialc {
SpatialCModule::SpatialCModule(Package* pkg, std::string name) :
ContainerModule(pkg->set()->design(), name),
_package(pkg)
{ }
llpm::InputPort* SpatialCModule::addInputPort(Type ty,
std::string name) {
if (_nameTypes.count(name) > 0) {
throw new SemanticError("input port " + name +
" has invalid name. Name already in use");
}
assert(!ty.isArray());
_nameTypes.insert(make_pair(name, ty));
auto sink = new NullSink(ty.llvm());
auto ip = ContainerModule::addInputPort(sink->din(), name);
_namedInputs[name] = ip;
return ip;
}
llpm::OutputPort* SpatialCModule::addOutputPort(Type ty,
std::string name) {
if (_nameTypes.count(name) > 0) {
throw new SemanticError("output port " + name +
" has invalid name. Name already in use");
}
assert(!ty.isArray());
_nameTypes.insert(make_pair(name, ty));
auto sel = new Select(0, ty.llvm());
auto op = ContainerModule::addOutputPort(sel->dout(), name);
_namedOutputs[name] = op;
_outputSelects[op] = sel;
return op;
}
llpm::Identity* SpatialCModule::addInternalPort(Type ty,
std::string name) {
if (_nameTypes.count(name) > 0) {
throw new SemanticError("internal port " + name +
" has invalid name. Name already in use");
}
assert(!ty.isArray());
_nameTypes.insert(make_pair(name, ty));
auto id = new Identity(ty.llvm());
_namedInternal[name] = id;
auto sel = new Select(0, ty.llvm());
conns()->connect(sel->dout(), id->din());
_internalSelects[id] = sel;
return id;
}
void SpatialCModule::addSubmodule(std::string name, llpm::Module* mod) {
if (_submodules.find(name) != _submodules.end()) {
throw CodeError("Submodule name already in use!");
}
_submodules[name] = mod;
// For each submodule port, automatically add and connect an internal
// channel to make it easier for users
for (auto ip: mod->inputs()) {
auto ipName = name + "." + ip->name();
auto id = addInternalPort(Type(ip->type()), ipName);
conns()->connect(id->dout(), ip);
}
for (auto op: mod->outputs()) {
auto opName = name + "." + op->name();
auto id = addInternalPort(Type(op->type()), opName);
conns()->connect(_internalSelects[id]->createInput(), op);
}
}
void SpatialCModule::addReg(Type ty, std::string name) {
if (_nameTypes.count(name) > 0) {
throw new SemanticError("storage " + name +
" has invalid name. Name already in use");
}
_nameTypes.insert(make_pair(name, ty));
if (!ty.isSimple() && !ty.isStruct() && !ty.isVector())
throw CodeError("Can only create register of simple, struct, "
"or vector types");
// Create a register
auto reg = new Register(ty.llvm());
_namedStorage[name] = reg;
reg->name(name);
}
void SpatialCModule::addMem(Type ty, std::string name) {
if (_nameTypes.count(name) > 0) {
throw new SemanticError("storage " + name +
" has invalid name. Name already in use");
}
_nameTypes.insert(make_pair(name, ty));
if (!ty.asArray())
throw CodeError("Can only create memory from array type");
auto arrTy = ty.asArray();
auto contained = arrTy->contained();
if (contained.isSimple() || contained.isStruct()) {
auto mem = new FiniteArray(contained.llvm(), (unsigned)arrTy->length());
_namedStorage[name] = mem;
mem->name(name);
} else {
throw CodeError("Array type for " + name +
" must be simple or struct type");
}
}
void SpatialCModule::addSubmodule(Type ty, std::string name) {
if (_nameTypes.count(name) > 0) {
throw new SemanticError("storage " + name +
" has invalid name. Name already in use");
}
_nameTypes.insert(make_pair(name, ty));
if (ty.isArray()) {
auto arrTy = ty.asArray();
auto contained = arrTy->contained();
if (!contained.isModule()) {
throw CodeError("Type specified for submodule is not a module!");
}
for (unsigned i=0; i<arrTy->length(); i++) {
auto mod = contained.asModule()->instantiate();
string instName = str(boost::format("%1%[%2%]") % name % i);
mod->name(instName);
addSubmodule(instName, mod);
_submoduleArrays[name].push_back(mod);
}
} else {
if (!ty.isModule()) {
throw CodeError("Type specified for submodule is not a module!");
}
// Add submodule
auto mod = ty.asModule()->instantiate();
mod->name(name);
addSubmodule(name, mod);
}
}
void SpatialCModule::addEvent(Event* ev) {
for (auto npPair : ev->ioConnections()) {
auto name = npPair.first;
auto ports = npPair.second;
int connCount = 0;
auto inpF = _namedInputs.find(name);
if (inpF != _namedInputs.end()) {
// Input port connection!
for (auto port: ports) {
auto ip = dynamic_cast<InputPort*>(port);
assert(ip != nullptr);
auto driver = getDriver(inpF->second);
conns()->connect(driver, ip);
connCount++;
}
}
auto outpF = _namedOutputs.find(name);
if (outpF != _namedOutputs.end()) {
// Output port connection!
for (auto port: ports) {
auto op = dynamic_cast<OutputPort*>(port);
assert(op != nullptr);
auto sel = _outputSelects[outpF->second];
assert(sel != nullptr);
conns()->connect(op, sel->createInput());
connCount++;
}
}
auto intpF = _namedInternal.find(name);
if (intpF != _namedInternal.end()) {
// Internal port connection!
auto id = intpF->second;
auto sel = _internalSelects[id];
assert(sel != nullptr);
for (auto port: ports) {
auto op = port->asOutput();
if (op != nullptr) {
conns()->connect(op, sel->createInput());
connCount++;
}
auto ip = port->asInput();
if (ip != nullptr) {
conns()->connect(ip, id->dout());
connCount++;
}
}
}
if (connCount == 0) {
throw SemanticError(
"Could not find I/O '" + name + "' specified by event '"
+ ev->name() + "'.");
}
}
for (auto memPair: ev->memWriteConnections()) {
auto name = memPair.first;
auto storF = _namedStorage.find(name);
if (storF != _namedStorage.end()) {
for (auto ifacePair: memPair.second) {
auto mem = storF->second;
auto mux = mem->write()->multiplexer(*conns());
auto srvr = mux->createServer();
conns()->connect(ifacePair.first, srvr->req()->asInput());
conns()->connect(srvr->resp()->asOutput(), ifacePair.second);
}
} else {
throw CodeError("Could not find storage: " + name);
}
}
for (auto memPair: ev->memReadConnections()) {
auto name = memPair.first;
auto storF = _namedStorage.find(name);
if (storF != _namedStorage.end()) {
for (auto ifacePair: memPair.second) {
auto mem = storF->second;
auto mux = mem->read()->multiplexer(*conns());
auto srvr = mux->createServer();
conns()->connect(ifacePair.first, srvr->req()->asInput());
conns()->connect(srvr->resp()->asOutput(), ifacePair.second);
}
} else {
throw CodeError("Could not find storage: " + name);
}
}
_events.push_back(ev);
}
void SpatialCModule::addConnection(Context& ctxt, ::DefConnect* conn) {
auto portA = resolve(ctxt, conn->channelspecifier_1, true)->asOutput();
auto portB = resolve(ctxt, conn->channelspecifier_2, false)->asInput();
if (portA == nullptr || portB == nullptr) {
throw CodeError("Could not resolve ports specified", conn->line_number);
}
conns()->connect(portA, portB);
}
llpm::Port* SpatialCModule::resolve(Context& ctxt, std::string id, bool isOutput) {
if (isOutput) {
auto inpF = _namedInputs.find(id);
if (inpF != _namedInputs.end()) {
// Submodule port is driven by one of our inputs
return getDriver(inpF->second);
} else {
// Submodule port is driver by one of our internal channels
auto intF = _namedInternal.find(id);
if (intF != _namedInternal.end()) {
return intF->second->dout();
} else {
throw CodeError("Could not find driver " + id);
}
}
throw CodeError("Could not find output called " +
id);
} else {
auto outF = _namedOutputs.find(id);
if (outF != _namedOutputs.end()) {
// Submodule port is drives one of our outputs
return _outputSelects[outF->second]->createInput();
} else {
// Submodule port is drives one of our internal channels
auto intF = _namedInternal.find(id);
if (intF != _namedInternal.end()) {
return _internalSelects[intF->second]->createInput();
} else {
throw CodeError("Could not find sink " + id);
}
}
throw CodeError("Could not find output called " + id);
}
}
std::string SpatialCModule::nameChannelSpecifier(Context& ctxt, ::ChannelSpecifier* cs) {
auto simple = dynamic_cast<SimpleCS*>(cs);
if (simple != nullptr) {
return simple->id_;
}
auto arrayDot = dynamic_cast<ArrayDotCS*>(cs);
if (arrayDot != nullptr) {
auto idx = Expression::evalExpression(ctxt, arrayDot->exp_);
auto c = llpm::EvalConstant(ctxt.conns(), idx.val);
if (c == nullptr) {
throw CodeError("Array connections at module-level must have "
"compile-time resolvable indexes",
arrayDot->line_number);
}
if (!c->getType()->isIntegerTy()) {
throw CodeError("Array indexes must resolve to integers!",
arrayDot->line_number);
}
string name = str(boost::format("%1%[%2%].%3%")
% arrayDot->id_1
% c->getUniqueInteger().getLimitedValue()
% arrayDot->id_2);
return name;
}
auto dot = dynamic_cast<DotCS*>(cs);
if (dot != nullptr) {
auto smF = _submodules.find(dot->id_1);
if (smF == _submodules.end()) {
throw CodeError("Could not find submodule " + dot->id_1, dot->line_number);
}
return dot->id_1 + "." + dot->id_2;
}
return "";
}
llpm::Port* SpatialCModule::resolve(Context& ctxt, ::ChannelSpecifier* cs, bool isOutput) {
auto name = nameChannelSpecifier(ctxt, cs);
if (name != "")
return resolve(ctxt, name, isOutput);
assert(false);
}
Type SpatialCModule::getType(const Context* ctxt, string typeName) {
return Type::resolve(ctxt, typeName);
}
Type SpatialCModule::getType(const Context* ctxt, ::Type* astType) {
return Type::resolve(ctxt, astType);
}
bool SpatialCModule::handleDeclDef(Context& ctxt, ModDef* def) {
auto reg = dynamic_cast<DefReg*>(def);
if (reg != nullptr) {
string id = reg->id_;
auto ty = getType(&ctxt, reg->type_);
addReg(ty, id);
return true;
}
auto mem = dynamic_cast<DefMem*>(def);
if (mem!= nullptr) {
string id = mem->id_;
auto ty = getType(&ctxt, mem->type_);
addMem(ty, id);
return true;
}
auto sub = dynamic_cast<DefSubmodule*>(def);
if (sub != nullptr) {
string id = sub->id_;
auto ty = getType(&ctxt, sub->type_);
addSubmodule(ty, id);
return true;
}
auto inp = dynamic_cast<DefInput*>(def);
if (inp != nullptr) {
string id = inp->id_;
auto ty = getType(&ctxt, inp->type_);
if (ty.isArray())
throw CodeError("Ports cannot be arrays", def->line_number);
addInputPort(ty, id);
return true;
}
auto outp = dynamic_cast<DefOutput*>(def);
if (outp != nullptr) {
string id = outp->id_;
auto ty = getType(&ctxt, outp->type_);
if (ty.isArray())
throw CodeError("Ports cannot be arrays", def->line_number);
addOutputPort(ty, id);
return true;
}
auto intp = dynamic_cast<DefInternal*>(def);
if (intp != nullptr) {
string id = intp->id_;
auto ty = getType(&ctxt, intp->type_);
if (ty.isArray())
throw CodeError("Ports cannot be arrays", def->line_number);
addInternalPort(ty, id);
return true;
}
return false;
}
bool SpatialCModule::handleModDef(Context& ctxt, ModDef* def) {
auto event = dynamic_cast<DefEvent*>(def);
if (event != nullptr) {
auto ev = Event::create(&ctxt, event, this);
addEvent(ev);
return true;
}
auto init = dynamic_cast<DefInit*>(def);
if (init != nullptr) {
auto ev = Event::create(&ctxt, init, this);
addEvent(ev);
return true;
}
auto connection = dynamic_cast<DefConnect*>(def);
if (connection != nullptr) {
addConnection(ctxt, connection);
return true;
}
auto forDef = dynamic_cast<DefFor*>(def);
if (forDef != nullptr) {
Context forCtxt(&ctxt);
int64_t from = Expression::resolveToInt(ctxt, forDef->exp_1);
int64_t to = Expression::resolveToInt(ctxt, forDef->exp_2);
auto intTy = llvm::Type::getInt64Ty(ctxt.llvmCtxt());
for (int i=from; i<to; i++) {
auto llvmConst = llvm::ConstantInt::get(intTy, i, true);
Variable v(Type(intTy),
nullptr,
forDef->id_,
llvmConst);
forCtxt.push(v);
for (auto def: *forDef->listmoddef_) {
handleModDef(forCtxt, def);
}
}
return true;
}
return false;
}
void SpatialCModuleTemplate::parseParams() {
auto ctxt = _pkg->ctxt();
SomeParams* modParams = dynamic_cast<SomeParams*>(_modAst->metaparamdecl_);
if (modParams != nullptr) {
for (auto param: *modParams->listmetaparam_) {
auto pname = ((MetaParam1*)param)->id_;
auto ty = Type::resolve(ctxt, ((MetaParam1*)param)->type_);
_params[pname] = ty;
}
}
}
SpatialCModuleTemplate* SpatialCModuleTemplate::args(
std::map<std::string, Variable> templArgs) {
if (templArgs.size() == 0)
return this;
return new SpatialCModuleTemplate(this, templArgs);
}
SpatialCModule* SpatialCModuleTemplate::instantiate() {
SpatialCModule* mod = new SpatialCModule(_pkg, _modAst->id_);
Context ctxt(_pkg->ctxt(), mod);
SomeParams* modParams = dynamic_cast<SomeParams*>(_modAst->metaparamdecl_);
if (modParams != nullptr) {
for (auto param: *modParams->listmetaparam_) {
auto pname = ((MetaParam1*)param)->id_;
auto f = _args.find(pname);
if (f != _args.end()) {
auto v = f->second;
v.name = pname;
ctxt.push(v);
} else {
auto eqExp = dynamic_cast<EqExp*>(((MetaParam1*)param)->optionaleqexp_);
if (eqExp == nullptr) {
throw CodeError("Module parameter '" + pname +
"' must be specified!", param->line_number);
}
ValTy val = Expression::evalExpression(ctxt, eqExp->exp_);
val = Expression::truncOrExtend(ctxt, val, _params[pname]);
if (val.ty != _params[pname]) {
throw CodeError("Metaparameter/argument type mismatch",
param->line_number);
}
auto c = llpm::EvalConstant(mod->conns(), val.val);
ctxt.push(Variable(val.ty, val.val, pname, c));
}
}
}
set<ModDef*> done;
for (ModDef* def: *_modAst->listmoddef_) {
if (mod->handleDeclDef(ctxt, def))
done.insert(def);
}
for (ModDef* def: *_modAst->listmoddef_) {
auto rc = mod->handleModDef(ctxt, def);
if (done.count(def) == 0 && rc == false) {
assert(false && "Couldn't deal with module def!");
}
}
return mod;
}
} // namespace spatialc
| 33.614504 | 91 | 0.543034 | llpm |
f8c78784fe41f2e7386b8476ea8e45ebf1e900a6 | 2,383 | cpp | C++ | GLWrapper/Math/Vector2D.cpp | filipkunc/GLGraphics | fb696948034832e1fbc60b7c6095560a79952875 | [
"MIT"
] | 6 | 2015-12-29T11:24:29.000Z | 2021-07-17T06:00:30.000Z | GLWrapper/Math/Vector2D.cpp | filipkunc/GLGraphics | fb696948034832e1fbc60b7c6095560a79952875 | [
"MIT"
] | null | null | null | GLWrapper/Math/Vector2D.cpp | filipkunc/GLGraphics | fb696948034832e1fbc60b7c6095560a79952875 | [
"MIT"
] | 1 | 2021-05-27T07:35:57.000Z | 2021-05-27T07:35:57.000Z | //
// Vector2D.cpp
// OpenGLEditor
//
// Created by Filip Kunc on 6/21/09.
// For license see LICENSE.TXT
//
#include "stdafx.h"
#include "MathDeclaration.h"
Vector2D::Vector2D()
{
x = 0.0f;
y = 0.0f;
}
Vector2D::Vector2D(const float * v)
{
x = v[0];
y = v[1];
}
Vector2D::Vector2D(const Vector2D & v)
{
x = v.x;
y = v.y;
}
Vector2D::Vector2D(float x, float y)
{
this->x = x;
this->y = y;
}
Vector2D::operator float *()
{
return &x;
}
Vector2D::operator const float *() const
{
return &x;
}
Vector2D & Vector2D::operator += (const Vector2D &v)
{
x += v.x;
y += v.y;
return *this;
}
Vector2D & Vector2D::operator -= (const Vector2D & v)
{
x -= v.x;
y -= v.y;
return *this;
}
Vector2D & Vector2D::operator *= (float s)
{
x *= s;
y *= s;
return *this;
}
Vector2D & Vector2D::operator /= (float s)
{
float oos = 1.0f / s;
x *= oos;
y *= oos;
return *this;
}
Vector2D Vector2D::operator + () const
{
return Vector2D(x, y);
}
Vector2D Vector2D::operator - () const
{
return Vector2D(-x, -y);
}
Vector2D Vector2D::operator + (const Vector2D & v) const
{
return Vector2D(x + v.x, y + v.y);
}
Vector2D Vector2D::operator - (const Vector2D & v) const
{
return Vector2D(x - v.x, y - v.y);
}
Vector2D Vector2D::operator * (float s) const
{
return Vector2D(x * s, y * s);
}
Vector2D Vector2D::operator / (float s) const
{
float oos = 1.0f / s;
return Vector2D(x * oos, y * oos);
}
Vector2D operator * (float s, const class Vector2D & v)
{
return Vector2D(v.x * s, v.y * s);
}
bool Vector2D::operator == (const Vector2D & v) const
{
return (v.x == x && v.y == y);
}
bool Vector2D::operator != (const Vector2D & v) const
{
return (v.x != x || v.y != y);
}
float Vector2D::Dot(const Vector2D & v) const
{
return x * v.x + y * v.y;
}
float Vector2D::GetLength() const
{
return sqrtf(GetLengthSq());
}
float Vector2D::GetLengthSq() const
{
return x * x + y * y;
}
void Vector2D::SetLength(float length)
{
float s = length / GetLength();
*this *= s;
}
void Vector2D::Normalize()
{
SetLength(1.0f);
}
float Vector2D::Distance(const Vector2D & v) const
{
Vector2D mag = v - *this;
return mag.GetLength();
}
float Vector2D::SqDistance(const Vector2D & v) const
{
Vector2D mag = v - *this;
return mag.GetLengthSq();
}
Vector2D Vector2D::Lerp(const Vector2D & v, float w) const
{
return (*this * (1.0f - w) + v * w);
}
| 14.619632 | 58 | 0.612253 | filipkunc |
f8c79a238516f9ff6d9b814403e9a0e3747fee9e | 58,225 | cpp | C++ | vpr7_x2p/vpr/SRC/fpga_x2p/base/module_manager_utils.cpp | srtemp/OpenFPGA | dd3d5fb7da881ef71717ce049eee09ec9b91849a | [
"MIT"
] | null | null | null | vpr7_x2p/vpr/SRC/fpga_x2p/base/module_manager_utils.cpp | srtemp/OpenFPGA | dd3d5fb7da881ef71717ce049eee09ec9b91849a | [
"MIT"
] | null | null | null | vpr7_x2p/vpr/SRC/fpga_x2p/base/module_manager_utils.cpp | srtemp/OpenFPGA | dd3d5fb7da881ef71717ce049eee09ec9b91849a | [
"MIT"
] | null | null | null | /******************************************************************************
* This files includes most utilized functions
* for data structures for module management.
******************************************************************************/
#include <map>
#include <algorithm>
#include "util.h"
#include "vtr_assert.h"
#include "spice_types.h"
#include "circuit_library.h"
#include "circuit_library_utils.h"
#include "module_manager.h"
#include "fpga_x2p_naming.h"
#include "fpga_x2p_pbtypes_utils.h"
#include "fpga_x2p_mem_utils.h"
#include "module_manager_utils.h"
/******************************************************************************
* Add a module to the module manager based on the circuit-level
* description of a circuit model
* This function add a module with a given customized name
* as well as add the ports of circuit model to the module manager
******************************************************************************/
ModuleId add_circuit_model_to_module_manager(ModuleManager& module_manager,
const CircuitLibrary& circuit_lib, const CircuitModelId& circuit_model,
const std::string& module_name) {
ModuleId module = module_manager.add_module(module_name);
VTR_ASSERT(ModuleId::INVALID() != module);
/* Add ports */
/* Find global ports and add one by one */
for (const auto& port : circuit_lib.model_global_ports(circuit_model, false)) {
BasicPort port_info(circuit_lib.port_prefix(port), circuit_lib.port_size(port));
module_manager.add_port(module, port_info, ModuleManager::MODULE_GLOBAL_PORT);
}
/* Find other ports and add one by one */
/* Create a type-to-type map for ports */
std::map<enum e_spice_model_port_type, ModuleManager::e_module_port_type> port_type2type_map;
port_type2type_map[SPICE_MODEL_PORT_INOUT] = ModuleManager::MODULE_INOUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_INPUT] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_CLOCK] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_SRAM] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_BL] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_BLB] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_WL] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_WLB] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[SPICE_MODEL_PORT_OUTPUT] = ModuleManager::MODULE_OUTPUT_PORT;
/* Input ports (ignore all the global ports when searching the circuit_lib */
for (const auto& kv : port_type2type_map) {
for (const auto& port : circuit_lib.model_ports_by_type(circuit_model, kv.first, true)) {
BasicPort port_info(circuit_lib.port_prefix(port), circuit_lib.port_size(port));
module_manager.add_port(module, port_info, kv.second);
}
}
/* Return the new id */
return module;
}
/******************************************************************************
* Add a module to the module manager based on the circuit-level
* description of a circuit model
* This function add a module in the name of the circuit model
* as well as add the ports of circuit model to the module manager
*
* This function is a wrapper of a more customizable function in the same name
******************************************************************************/
ModuleId add_circuit_model_to_module_manager(ModuleManager& module_manager,
const CircuitLibrary& circuit_lib, const CircuitModelId& circuit_model) {
return add_circuit_model_to_module_manager(module_manager, circuit_lib, circuit_model, circuit_lib.model_name(circuit_model));
}
/********************************************************************
* Add a list of ports that are used for reserved SRAM ports to a module
* in the module manager
* The reserved SRAM ports are mainly designed for RRAM-based FPGA,
* which are shared across modules.
* Note that different modules may require different size of reserved
* SRAM ports but their LSB must all start from 0
* +---------+
* reserved_sram_port[0:X] --->| ModuleA |
* +---------+
*
* +---------+
* reserved_sram_port[0:Y] --->| ModuleB |
* +---------+
*
********************************************************************/
void add_reserved_sram_ports_to_module_manager(ModuleManager& module_manager,
const ModuleId& module_id,
const size_t& port_size) {
/* Add a reserved BLB port to the module */
std::string blb_port_name = generate_reserved_sram_port_name(SPICE_MODEL_PORT_BLB);
BasicPort blb_module_port(blb_port_name, port_size);
/* Add generated ports to the ModuleManager */
module_manager.add_port(module_id, blb_module_port, ModuleManager::MODULE_INPUT_PORT);
/* Add a reserved BLB port to the module */
std::string wl_port_name = generate_reserved_sram_port_name(SPICE_MODEL_PORT_WL);
BasicPort wl_module_port(wl_port_name, port_size);
/* Add generated ports to the ModuleManager */
module_manager.add_port(module_id, wl_module_port, ModuleManager::MODULE_INPUT_PORT);
}
/********************************************************************
* Add a list of ports that are used for formal verification to a module
* in the module manager
*
* The formal verification port will appear only when a pre-processing flag is defined
* This function will add the pre-processing flag along with the port
********************************************************************/
void add_formal_verification_sram_ports_to_module_manager(ModuleManager& module_manager,
const ModuleId& module_id,
const CircuitLibrary& circuit_lib,
const CircuitModelId& sram_model,
const std::string& preproc_flag,
const size_t& port_size) {
/* Create a port */
std::string port_name = generate_formal_verification_sram_port_name(circuit_lib, sram_model);
BasicPort module_port(port_name, port_size);
/* Add generated ports to the ModuleManager */
ModulePortId port_id = module_manager.add_port(module_id, module_port, ModuleManager::MODULE_INPUT_PORT);
/* Add pre-processing flag if defined */
module_manager.set_port_preproc_flag(module_id, port_id, preproc_flag);
}
/********************************************************************
* Add a list of ports that are used for SRAM configuration to a module
* in the module manager
* The type and names of added ports strongly depend on the
* organization of SRAMs.
* 1. Standalone SRAMs:
* two ports will be added, which are regular output and inverted output
* 2. Scan-chain Flip-flops:
* two ports will be added, which are the head of scan-chain
* and the tail of scan-chain
* IMPORTANT: the port size will be forced to 1 in this case
* because the head and tail are both 1-bit ports!!!
* 3. Memory decoders:
* 2-4 ports will be added, depending on the ports available in the SRAM
* Among these, two ports are mandatory: BL and WL
* The other two ports are optional: BLB and WLB
* Note that the constraints are correletated to the checking rules
* in check_circuit_library()
********************************************************************/
void add_sram_ports_to_module_manager(ModuleManager& module_manager,
const ModuleId& module_id,
const CircuitLibrary& circuit_lib,
const CircuitModelId& sram_model,
const e_sram_orgz sram_orgz_type,
const size_t& num_config_bits) {
std::vector<std::string> sram_port_names = generate_sram_port_names(circuit_lib, sram_model, sram_orgz_type);
size_t sram_port_size = generate_sram_port_size(sram_orgz_type, num_config_bits);
/* Add ports to the module manager */
switch (sram_orgz_type) {
case SPICE_SRAM_STANDALONE:
case SPICE_SRAM_MEMORY_BANK: {
for (const std::string& sram_port_name : sram_port_names) {
/* Add generated ports to the ModuleManager */
BasicPort sram_port(sram_port_name, sram_port_size);
module_manager.add_port(module_id, sram_port, ModuleManager::MODULE_INPUT_PORT);
}
break;
}
case SPICE_SRAM_SCAN_CHAIN: {
/* Note that configuration chain tail is an output while head is an input
* IMPORTANT: this is co-designed with function generate_sram_port_names()
* If the return vector is changed, the following codes MUST be adapted!
*/
VTR_ASSERT(2 == sram_port_names.size());
size_t port_counter = 0;
for (const std::string& sram_port_name : sram_port_names) {
/* Add generated ports to the ModuleManager */
BasicPort sram_port(sram_port_name, sram_port_size);
if (0 == port_counter) {
module_manager.add_port(module_id, sram_port, ModuleManager::MODULE_INPUT_PORT);
} else {
VTR_ASSERT(1 == port_counter);
module_manager.add_port(module_id, sram_port, ModuleManager::MODULE_OUTPUT_PORT);
}
port_counter++;
}
break;
}
default:
vpr_printf(TIO_MESSAGE_ERROR,
"(File:%s,[LINE%d]) Invalid type of SRAM organization !\n",
__FILE__, __LINE__);
exit(1);
}
}
/********************************************************************
* Add ports of a pb_type block to module manager
* Port addition will follow the sequence: inout, input, output, clock
* This will help use to keep a clean module definition when printing out
* To avoid port mismatch between the pb_type and its linked circuit model
* This function will also check that each pb_type port is actually exist
* in the linked circuit model
*******************************************************************/
void add_primitive_pb_type_ports_to_module_manager(ModuleManager& module_manager,
const ModuleId& module_id,
t_pb_type* cur_pb_type) {
/* Find the inout ports required by the primitive pb_type, and add them to the module */
std::vector<t_port*> pb_type_inout_ports = find_pb_type_ports_match_circuit_model_port_type(cur_pb_type, SPICE_MODEL_PORT_INOUT);
for (auto port : pb_type_inout_ports) {
BasicPort module_port(generate_pb_type_port_name(port), port->num_pins);
module_manager.add_port(module_id, module_port, ModuleManager::MODULE_INOUT_PORT);
/* Set the port to be wire-connection */
module_manager.set_port_is_wire(module_id, module_port.get_name(), true);
}
/* Find the input ports required by the primitive pb_type, and add them to the module */
std::vector<t_port*> pb_type_input_ports = find_pb_type_ports_match_circuit_model_port_type(cur_pb_type, SPICE_MODEL_PORT_INPUT);
for (auto port : pb_type_input_ports) {
BasicPort module_port(generate_pb_type_port_name(port), port->num_pins);
module_manager.add_port(module_id, module_port, ModuleManager::MODULE_INPUT_PORT);
/* Set the port to be wire-connection */
module_manager.set_port_is_wire(module_id, module_port.get_name(), true);
}
/* Find the output ports required by the primitive pb_type, and add them to the module */
std::vector<t_port*> pb_type_output_ports = find_pb_type_ports_match_circuit_model_port_type(cur_pb_type, SPICE_MODEL_PORT_OUTPUT);
for (auto port : pb_type_output_ports) {
BasicPort module_port(generate_pb_type_port_name(port), port->num_pins);
module_manager.add_port(module_id, module_port, ModuleManager::MODULE_OUTPUT_PORT);
/* Set the port to be wire-connection */
module_manager.set_port_is_wire(module_id, module_port.get_name(), true);
}
/* Find the clock ports required by the primitive pb_type, and add them to the module */
std::vector<t_port*> pb_type_clock_ports = find_pb_type_ports_match_circuit_model_port_type(cur_pb_type, SPICE_MODEL_PORT_CLOCK);
for (auto port : pb_type_clock_ports) {
BasicPort module_port(generate_pb_type_port_name(port), port->num_pins);
module_manager.add_port(module_id, module_port, ModuleManager::MODULE_CLOCK_PORT);
/* Set the port to be wire-connection */
module_manager.set_port_is_wire(module_id, module_port.get_name(), true);
}
}
/********************************************************************
* Add ports of a pb_type block to module manager
* This function is designed for non-primitive pb_types, which are
* NOT linked to any circuit model.
* Actually, this makes things much simpler.
* We just iterate over all the ports and add it to the module
* with the naming convention
*******************************************************************/
void add_pb_type_ports_to_module_manager(ModuleManager& module_manager,
const ModuleId& module_id,
t_pb_type* cur_pb_type) {
/* Create a type-to-type mapping between module ports and pb_type ports */
std::map<PORTS, ModuleManager::e_module_port_type> port_type2type_map;
port_type2type_map[IN_PORT] = ModuleManager::MODULE_INPUT_PORT;
port_type2type_map[OUT_PORT] = ModuleManager::MODULE_OUTPUT_PORT;
port_type2type_map[INOUT_PORT] = ModuleManager::MODULE_INOUT_PORT;
for (int port = 0; port < cur_pb_type->num_ports; ++port) {
t_port* pb_type_port = &(cur_pb_type->ports[port]);
BasicPort module_port(generate_pb_type_port_name(pb_type_port), pb_type_port->num_pins);
module_manager.add_port(module_id, module_port, port_type2type_map[pb_type_port->type]);
/* Set the port to be wire-connection */
module_manager.set_port_is_wire(module_id, module_port.get_name(), true);
}
}
/********************************************************************
* Identify if a net is a local wire inside a module:
* A net is a local wire if it connects between two instances,
* It means that any of its source and sink modules should not include current module_id
*******************************************************************/
bool module_net_is_local_wire(const ModuleManager& module_manager,
const ModuleId& module_id, const ModuleNetId& module_net) {
/* Check all the sink modules of the net,
* if we have a source module is the current module, this is not local wire
*/
for (ModuleId src_module : module_manager.net_source_modules(module_id, module_net)) {
if (module_id == src_module) {
/* Here, this is not a local wire */
return false;
}
}
/* Check all the sink modules of the net */
for (ModuleId sink_module : module_manager.net_sink_modules(module_id, module_net)) {
if (module_id == sink_module) {
/* Here, this is not a local wire */
return false;
}
}
return true;
}
/********************************************************************
* Identify if a net is an output short connection inside a module:
* The short connection is defined as the direct connection
* between two outputs port of the module
*
* module
* +-----------------------------+
* |
* src------>+--------------->|--->outputA
* | |
* | |
* +--------------->|--->outputB
* +-----------------------------+
*******************************************************************/
bool module_net_include_output_short_connection(const ModuleManager& module_manager,
const ModuleId& module_id, const ModuleNetId& module_net) {
/* Check all the sink modules of the net */
size_t contain_num_module_output = 0;
for (ModuleId sink_module : module_manager.net_sink_modules(module_id, module_net)) {
if (module_id == sink_module) {
contain_num_module_output++;
}
}
/* If we have found more than 1 module outputs, it indicated output short connection! */
return (1 < contain_num_module_output);
}
/********************************************************************
* Identify if a net is a local short connection inside a module:
* The short connection is defined as the direct connection
* between an input port of the module and an output port of the module
*
* module
* +-----------------------------+
* | |
* inputA--->|---------------------------->|--->outputB
* | |
* | |
* | |
* +-----------------------------+
*******************************************************************/
bool module_net_include_local_short_connection(const ModuleManager& module_manager,
const ModuleId& module_id, const ModuleNetId& module_net) {
/* Check all the sink modules of the net,
* if we have a source module is the current module, this is not local wire
*/
bool contain_module_input = false;
for (ModuleId src_module : module_manager.net_source_modules(module_id, module_net)) {
if (module_id == src_module) {
contain_module_input = true;
break;
}
}
/* Check all the sink modules of the net */
bool contain_module_output = false;
for (ModuleId sink_module : module_manager.net_sink_modules(module_id, module_net)) {
if (module_id == sink_module) {
contain_module_output = true;
break;
}
}
return contain_module_input & contain_module_output;
}
/********************************************************************
* Add the port-to-port connection between a pb_type and its linked circuit model
* This function is mainly used to create instance of the module for a pb_type
*
* Note: this function SHOULD be called after the pb_type_module is created
* and its child module is created!
*******************************************************************/
void add_primitive_pb_type_module_nets(ModuleManager& module_manager,
const ModuleId& pb_type_module,
const ModuleId& child_module,
const size_t& child_instance_id,
const CircuitLibrary& circuit_lib,
t_pb_type* cur_pb_type) {
for (int iport = 0; iport < cur_pb_type->num_ports; ++iport) {
t_port* pb_type_port = &(cur_pb_type->ports[iport]);
/* Must have a linked circuit model port */
VTR_ASSERT( CircuitPortId::INVALID() != pb_type_port->circuit_model_port);
/* Find the source port in pb_type module */
/* Get the src module port id */
ModulePortId src_module_port_id = module_manager.find_module_port(pb_type_module, generate_pb_type_port_name(pb_type_port));
VTR_ASSERT(ModulePortId::INVALID() != src_module_port_id);
BasicPort src_port = module_manager.module_port(pb_type_module, src_module_port_id);
/* Get the des module port id */
std::string des_module_port_name = circuit_lib.port_prefix(pb_type_port->circuit_model_port);
ModulePortId des_module_port_id = module_manager.find_module_port(child_module, des_module_port_name);
VTR_ASSERT(ModulePortId::INVALID() != des_module_port_id);
BasicPort des_port = module_manager.module_port(child_module, des_module_port_id);
/* Port size must match */
if (src_port.get_width() != des_port.get_width())
VTR_ASSERT(src_port.get_width() == des_port.get_width());
/* For each pin, generate the nets.
* For non-output ports (input ports, inout ports and clock ports),
* src_port is the source of the net
* For output ports
* src_port is the sink of the net
*/
switch (pb_type_port->type) {
case IN_PORT:
case INOUT_PORT:
for (size_t pin_id = 0; pin_id < src_port.pins().size(); ++pin_id) {
ModuleNetId net = module_manager.create_module_net(pb_type_module);
/* Add net source */
module_manager.add_module_net_source(pb_type_module, net, pb_type_module, 0, src_module_port_id, src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(pb_type_module, net, child_module, child_instance_id, des_module_port_id, des_port.pins()[pin_id]);
}
break;
case OUT_PORT:
for (size_t pin_id = 0; pin_id < src_port.pins().size(); ++pin_id) {
ModuleNetId net = module_manager.create_module_net(pb_type_module);
/* Add net source */
module_manager.add_module_net_sink(pb_type_module, net, pb_type_module, 0, src_module_port_id, src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_source(pb_type_module, net, child_module, child_instance_id, des_module_port_id, des_port.pins()[pin_id]);
}
break;
default:
vpr_printf(TIO_MESSAGE_ERROR,
"(File:%s, [LINE%d]) Invalid port of pb_type!\n",
__FILE__, __LINE__);
exit(1);
}
}
}
/********************************************************************
* Add the port-to-port connection between a logic module
* and a memory module
* Create nets to wire SRAM ports between logic module and memory module
*
* The information about SRAM ports of logic module are stored in the
* mem_output_bus_ports, where element [0] denotes the SRAM port while
* element [1] denotes the SRAMb port
*
* +---------+ +--------+
* | | regular SRAM port | |
* | Logic |-----------------------+ | Memory |
* | Module | mode-select SRAM port |->| Module |
* | |-----------------------+ | |
* +---------+ +--------+
*
* There could be multiple SRAM ports of logic module, which are wired to
* the SRAM ports of memory module
*
* Note: this function SHOULD be called after the pb_type_module is created
* and its child module (logic_module and memory_module) is created!
*
* Note: this function only handle either SRAM or SRAMb ports.
* So, this function may be called twice to complete the wiring
*******************************************************************/
static
void add_module_nets_between_logic_and_memory_sram_ports(ModuleManager& module_manager,
const ModuleId& parent_module,
const ModuleId& logic_module,
const size_t& logic_instance_id,
const ModuleId& memory_module,
const size_t& memory_instance_id,
const std::vector<ModulePortId>& logic_module_sram_port_ids,
const ModulePortId& mem_module_sram_port_id) {
/* Find mem_output_bus ports in logic module */
std::vector<BasicPort> logic_module_sram_ports;
for (const ModulePortId& logic_module_sram_port_id : logic_module_sram_port_ids) {
logic_module_sram_ports.push_back(module_manager.module_port(logic_module, logic_module_sram_port_id));
}
/* Create a list of virtual ports to align with the SRAM port of logic module
* Physical ports:
*
* logic_module_sram_port[0] logic_module_sram_port[1]
*
* LSB[0]------------>MSB[0] LSB------------------>MSB
*
* memory_sram_port
* LSBY---------------------------------------------->MSBY
*
* Virtual ports:
* mem_module_sram_port[0] mem_module_sram_port[1]
* LSBY--------------->MSBX MSBX+1------------------>MSBY
*
*/
BasicPort mem_module_port = module_manager.module_port(memory_module, mem_module_sram_port_id);
std::vector<BasicPort> virtual_mem_module_ports;
/* Create a counter for the LSB of virtual ports */
size_t port_lsb = 0;
for (const BasicPort& logic_module_sram_port : logic_module_sram_ports) {
BasicPort virtual_port;
virtual_port.set_name(mem_module_port.get_name());
virtual_port.set_width(port_lsb, port_lsb + logic_module_sram_port.get_width() - 1);
virtual_mem_module_ports.push_back(virtual_port);
port_lsb = virtual_port.get_msb() + 1;
}
/* port_lsb should be aligned with the MSB of memory_sram_port */
VTR_ASSERT(port_lsb == mem_module_port.get_msb() + 1);
/* Wire port to port */
for (size_t port_index = 0; port_index < logic_module_sram_ports.size(); ++port_index) {
/* Create a net for each pin */
for (size_t pin_id = 0; pin_id < logic_module_sram_ports[port_index].pins().size(); ++pin_id) {
ModuleNetId net = module_manager.create_module_net(parent_module);
/* TODO: Give a name to make it clear */
std::string net_name = module_manager.module_name(logic_module) + std::string("_") + std::to_string(logic_instance_id) + std::string("_") + logic_module_sram_ports[port_index].get_name();
module_manager.set_net_name(parent_module, net, net_name);
/* Add net source */
module_manager.add_module_net_source(parent_module, net, logic_module, logic_instance_id, logic_module_sram_port_ids[port_index], logic_module_sram_ports[port_index].pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(parent_module, net, memory_module, memory_instance_id, mem_module_sram_port_id, virtual_mem_module_ports[port_index].pins()[pin_id]);
}
}
}
/********************************************************************
* Add the port-to-port connection between a logic module
* and a memory module
* Create nets to wire SRAM ports between logic module and memory module
*
*
* +---------+ +--------+
* | | SRAM ports | |
* | Logic |----------------------->| Memory |
* | Module | SRAMb ports | Module |
* | |----------------------->| |
* +---------+ +--------+
*
* Note: this function SHOULD be called after the pb_type_module is created
* and its child module (logic_module and memory_module) is created!
*
*******************************************************************/
void add_module_nets_between_logic_and_memory_sram_bus(ModuleManager& module_manager,
const ModuleId& parent_module,
const ModuleId& logic_module,
const size_t& logic_instance_id,
const ModuleId& memory_module,
const size_t& memory_instance_id,
const CircuitLibrary& circuit_lib,
const CircuitModelId& logic_model) {
/* Connect SRAM port */
/* Find SRAM ports in the circuit model for logic module */
std::vector<std::string> logic_model_sram_port_names;
/* Regular sram port goes first */
for (CircuitPortId regular_sram_port : find_circuit_regular_sram_ports(circuit_lib, logic_model)) {
logic_model_sram_port_names.push_back(circuit_lib.port_prefix(regular_sram_port));
}
/* Mode-select sram port goes first */
for (CircuitPortId mode_select_sram_port : find_circuit_mode_select_sram_ports(circuit_lib, logic_model)) {
logic_model_sram_port_names.push_back(circuit_lib.port_prefix(mode_select_sram_port));
}
/* Find the port ids in the memory */
std::vector<ModulePortId> logic_module_sram_port_ids;
for (const std::string& logic_model_sram_port_name : logic_model_sram_port_names) {
/* Skip non-exist ports */
if (ModulePortId::INVALID() == module_manager.find_module_port(logic_module, logic_model_sram_port_name)) {
continue;
}
logic_module_sram_port_ids.push_back(module_manager.find_module_port(logic_module, logic_model_sram_port_name));
}
/* Get the SRAM port name of memory model */
/* TODO: this should be a constant expression and it should be the same for all the memory module! */
std::string memory_model_sram_port_name = generate_configuration_chain_data_out_name();
/* Find the corresponding ports in memory module */
ModulePortId mem_module_sram_port_id = module_manager.find_module_port(memory_module, memory_model_sram_port_name);
/* Do wiring only when we have sram ports */
if ( (false == logic_module_sram_port_ids.empty())
|| (ModulePortId::INVALID() == mem_module_sram_port_id) ) {
add_module_nets_between_logic_and_memory_sram_ports(module_manager, parent_module,
logic_module, logic_instance_id,
memory_module, memory_instance_id,
logic_module_sram_port_ids, mem_module_sram_port_id);
}
/* Connect SRAMb port */
/* Find SRAM ports in the circuit model for logic module */
std::vector<std::string> logic_model_sramb_port_names;
/* Regular sram port goes first */
for (CircuitPortId regular_sram_port : find_circuit_regular_sram_ports(circuit_lib, logic_model)) {
logic_model_sramb_port_names.push_back(circuit_lib.port_prefix(regular_sram_port) + std::string("_inv"));
}
/* Mode-select sram port goes first */
for (CircuitPortId mode_select_sram_port : find_circuit_mode_select_sram_ports(circuit_lib, logic_model)) {
logic_model_sramb_port_names.push_back(circuit_lib.port_prefix(mode_select_sram_port) + std::string("_inv"));
}
/* Find the port ids in the memory */
std::vector<ModulePortId> logic_module_sramb_port_ids;
for (const std::string& logic_model_sramb_port_name : logic_model_sramb_port_names) {
/* Skip non-exist ports */
if (ModulePortId::INVALID() == module_manager.find_module_port(logic_module, logic_model_sramb_port_name)) {
continue;
}
logic_module_sramb_port_ids.push_back(module_manager.find_module_port(logic_module, logic_model_sramb_port_name));
}
/* Get the SRAM port name of memory model */
std::string memory_model_sramb_port_name = generate_configuration_chain_inverted_data_out_name();
/* Find the corresponding ports in memory module */
ModulePortId mem_module_sramb_port_id = module_manager.find_module_port(memory_module, memory_model_sramb_port_name);
/* Do wiring only when we have sramb ports */
if ( (false == logic_module_sramb_port_ids.empty())
|| (ModulePortId::INVALID() == mem_module_sramb_port_id) ) {
add_module_nets_between_logic_and_memory_sram_ports(module_manager, parent_module,
logic_module, logic_instance_id,
memory_module, memory_instance_id,
logic_module_sramb_port_ids, mem_module_sramb_port_id);
}
}
/********************************************************************
* Connect all the memory modules under the parent module in a chain
*
* +--------+ +--------+ +--------+
* ccff_head --->| Memory |--->| Memory |--->... --->| Memory |----> ccff_tail
* | Module | | Module | | Module |
* | [0] | | [1] | | [N-1] |
* +--------+ +--------+ +--------+
* For the 1st memory module:
* net source is the configuration chain head of the primitive module
* net sink is the configuration chain head of the next memory module
*
* For the rest of memory modules:
* net source is the configuration chain tail of the previous memory module
* net sink is the configuration chain head of the next memory module
*********************************************************************/
void add_module_nets_cmos_memory_chain_config_bus(ModuleManager& module_manager,
const ModuleId& parent_module,
const e_sram_orgz& sram_orgz_type) {
for (size_t mem_index = 0; mem_index < module_manager.configurable_children(parent_module).size(); ++mem_index) {
ModuleId net_src_module_id;
size_t net_src_instance_id;
ModulePortId net_src_port_id;
ModuleId net_sink_module_id;
size_t net_sink_instance_id;
ModulePortId net_sink_port_id;
if (0 == mem_index) {
/* Find the port name of configuration chain head */
std::string src_port_name = generate_sram_port_name(sram_orgz_type, SPICE_MODEL_PORT_INPUT);
net_src_module_id = parent_module;
net_src_instance_id = 0;
net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = generate_configuration_chain_head_name();
net_sink_module_id = module_manager.configurable_children(parent_module)[mem_index];
net_sink_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index];
net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
} else {
/* Find the port name of previous memory module */
std::string src_port_name = generate_configuration_chain_tail_name();
net_src_module_id = module_manager.configurable_children(parent_module)[mem_index - 1];
net_src_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index - 1];
net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = generate_configuration_chain_head_name();
net_sink_module_id = module_manager.configurable_children(parent_module)[mem_index];
net_sink_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index];
net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
}
/* Get the pin id for source port */
BasicPort net_src_port = module_manager.module_port(net_src_module_id, net_src_port_id);
/* Get the pin id for sink port */
BasicPort net_sink_port = module_manager.module_port(net_sink_module_id, net_sink_port_id);
/* Port sizes of source and sink should match */
VTR_ASSERT(net_src_port.get_width() == net_sink_port.get_width());
/* Create a net for each pin */
for (size_t pin_id = 0; pin_id < net_src_port.pins().size(); ++pin_id) {
/* Create a net and add source and sink to it */
ModuleNetId net = module_manager.create_module_net(parent_module);
/* Add net source */
module_manager.add_module_net_source(parent_module, net, net_src_module_id, net_src_instance_id, net_src_port_id, net_src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(parent_module, net, net_sink_module_id, net_sink_instance_id, net_sink_port_id, net_sink_port.pins()[pin_id]);
}
}
/* For the last memory module:
* net source is the configuration chain tail of the previous memory module
* net sink is the configuration chain tail of the primitive module
*/
/* Find the port name of previous memory module */
std::string src_port_name = generate_configuration_chain_tail_name();
ModuleId net_src_module_id = module_manager.configurable_children(parent_module).back();
size_t net_src_instance_id = module_manager.configurable_child_instances(parent_module).back();
ModulePortId net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = generate_sram_port_name(sram_orgz_type, SPICE_MODEL_PORT_OUTPUT);
ModuleId net_sink_module_id = parent_module;
size_t net_sink_instance_id = 0;
ModulePortId net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
/* Get the pin id for source port */
BasicPort net_src_port = module_manager.module_port(net_src_module_id, net_src_port_id);
/* Get the pin id for sink port */
BasicPort net_sink_port = module_manager.module_port(net_sink_module_id, net_sink_port_id);
/* Port sizes of source and sink should match */
VTR_ASSERT(net_src_port.get_width() == net_sink_port.get_width());
/* Create a net for each pin */
for (size_t pin_id = 0; pin_id < net_src_port.pins().size(); ++pin_id) {
/* Create a net and add source and sink to it */
ModuleNetId net = module_manager.create_module_net(parent_module);
/* Add net source */
module_manager.add_module_net_source(parent_module, net, net_src_module_id, net_src_instance_id, net_src_port_id, net_src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(parent_module, net, net_sink_module_id, net_sink_instance_id, net_sink_port_id, net_sink_port.pins()[pin_id]);
}
}
/*********************************************************************
* Add the port-to-port connection between all the memory modules
* and their parent module
*
* Create nets to wire the control signals of memory module to
* the configuration ports of primitive module
*
* Configuration Chain
* -------------------
*
* config_bus (head) config_bus (tail)
* | ^
* primitive | |
* +---------------------------------------------+
* | | | |
* | v | |
* | +-------------------------------------+ |
* | | CMOS-based Memory Modules | |
* | +-------------------------------------+ |
* | | | |
* | v v |
* | sram_out sram_outb |
* | |
* +---------------------------------------------+
*
* Memory bank
* -----------
*
* config_bus (BL) config_bus (WL)
* | |
* primitive | |
* +---------------------------------------------+
* | | | |
* | v v |
* | +-------------------------------------+ |
* | | CMOS-based Memory Modules | |
* | +-------------------------------------+ |
* | | | |
* | v v |
* | sram_out sram_outb |
* | |
* +---------------------------------------------+
*
**********************************************************************/
static
void add_module_nets_cmos_memory_config_bus(ModuleManager& module_manager,
const ModuleId& parent_module,
const e_sram_orgz& sram_orgz_type) {
switch (sram_orgz_type) {
case SPICE_SRAM_STANDALONE:
/* Nothing to do */
break;
case SPICE_SRAM_SCAN_CHAIN: {
add_module_nets_cmos_memory_chain_config_bus(module_manager, parent_module, sram_orgz_type);
break;
}
case SPICE_SRAM_MEMORY_BANK:
/* TODO: */
break;
default:
vpr_printf(TIO_MESSAGE_ERROR,
"(File:%s,[LINE%d])Invalid type of SRAM organization!\n",
__FILE__, __LINE__);
exit(1);
}
}
/*********************************************************************
* TODO:
* Add the port-to-port connection between a logic module
* and a memory module inside a primitive module
*
* Memory bank
* -----------
* config_bus (BL) config_bus (WL) shared_config_bugs(shared_BL/WLs)
* | | | |
* primitive | | | |
* +------------------------------------------------------------+
* | | | | | |
* | v v v v |
* | +----------------------------------------------------+ |
* | | ReRAM-based Memory Module | |
* | +----------------------------------------------------+ |
* | | | |
* | v v |
* | mem_out mem_outb |
* | |
* +------------------------------------------------------------+
*
**********************************************************************/
/********************************************************************
* TODO:
* Add the port-to-port connection between a memory module
* and the configuration bus of a primitive module
*
* Create nets to wire the control signals of memory module to
* the configuration ports of primitive module
*
* Primitive module
* +----------------------------+
* | +--------+ |
* config | | | |
* ports --->|--------------->| Memory | |
* | | Module | |
* | | | |
* | +--------+ |
* +----------------------------+
* The detailed config ports really depend on the type
* of SRAM organization.
*
* The config_bus in the argument is the reserved address of configuration
* bus in the parent_module for this memory module
*
* The configuration bus connection will depend not only
* the design technology of the memory cells but also the
* configuration styles of FPGA fabric.
* Here we will branch on the design technology
*
* Note: this function SHOULD be called after the pb_type_module is created
* and its child module (logic_module and memory_module) is created!
*******************************************************************/
void add_module_nets_memory_config_bus(ModuleManager& module_manager,
const ModuleId& parent_module,
const e_sram_orgz& sram_orgz_type,
const e_spice_model_design_tech& mem_tech) {
switch (mem_tech) {
case SPICE_MODEL_DESIGN_CMOS:
add_module_nets_cmos_memory_config_bus(module_manager, parent_module,
sram_orgz_type);
break;
case SPICE_MODEL_DESIGN_RRAM:
/* TODO: */
break;
default:
vpr_printf(TIO_MESSAGE_ERROR,
"(File:%s,[LINE%d])Invalid type of memory design technology !\n",
__FILE__, __LINE__);
exit(1);
}
}
/********************************************************************
* Find the size of shared(reserved) configuration ports for module
*******************************************************************/
size_t find_module_num_shared_config_bits(const ModuleManager& module_manager,
const ModuleId& module_id) {
std::vector<std::string> shared_config_port_names;
shared_config_port_names.push_back(generate_reserved_sram_port_name(SPICE_MODEL_PORT_BLB));
shared_config_port_names.push_back(generate_reserved_sram_port_name(SPICE_MODEL_PORT_WL));
size_t num_shared_config_bits = 0; /* By default it has zero configuration bits*/
/* Try to find these ports in the module manager */
for (const std::string& shared_config_port_name : shared_config_port_names) {
ModulePortId module_port_id = module_manager.find_module_port(module_id, shared_config_port_name);
/* If the port does not exist, go to the next */
if (false == module_manager.valid_module_port_id(module_id, module_port_id)) {
continue;
}
/* The port exist, find the port size and update the num_config_bits if the size is larger */
BasicPort module_port = module_manager.module_port(module_id, module_port_id);
num_shared_config_bits = std::max((int)num_shared_config_bits, (int)module_port.get_width());
}
return num_shared_config_bits;
}
/********************************************************************
* Find the size of configuration ports for module
*******************************************************************/
size_t find_module_num_config_bits(const ModuleManager& module_manager,
const ModuleId& module_id,
const CircuitLibrary& circuit_lib,
const CircuitModelId& sram_model,
const e_sram_orgz& sram_orgz_type) {
std::vector<std::string> config_port_names = generate_sram_port_names(circuit_lib, sram_model, sram_orgz_type);
size_t num_config_bits = 0; /* By default it has zero configuration bits*/
/* Try to find these ports in the module manager */
for (const std::string& config_port_name : config_port_names) {
ModulePortId module_port_id = module_manager.find_module_port(module_id, config_port_name);
/* If the port does not exist, go to the next */
if (false == module_manager.valid_module_port_id(module_id, module_port_id)) {
continue;
}
/* The port exist, find the port size and update the num_config_bits if the size is larger */
BasicPort module_port = module_manager.module_port(module_id, module_port_id);
num_config_bits = std::max((int)num_config_bits, (int)module_port.get_width());
}
return num_config_bits;
}
/********************************************************************
* Add GPIO ports to the module:
* In this function, the following tasks are done:
* 1. find all the GPIO ports from the child modules and build a list of it,
* 2. Merge all the GPIO ports with the same name
* 3. add the ports to the pb_module
* 4. add module nets to connect to the GPIO ports of each sub module
*
* Note: This function should be call ONLY after all the sub modules (instances)
* have been added to the pb_module!
* Otherwise, some GPIO ports of the sub modules may be missed!
*******************************************************************/
void add_module_gpio_ports_from_child_modules(ModuleManager& module_manager,
const ModuleId& module_id) {
std::vector<BasicPort> gpio_ports_to_add;
/* Iterate over the child modules */
for (const ModuleId& child : module_manager.child_modules(module_id)) {
/* Iterate over the child instances */
for (size_t i = 0; i < module_manager.num_instance(module_id, child); ++i) {
/* Find all the global ports, whose port type is special */
for (BasicPort gpio_port : module_manager.module_ports_by_type(child, ModuleManager::MODULE_GPIO_PORT)) {
/* If this port is not mergeable, we update the list */
bool is_mergeable = false;
for (BasicPort& gpio_port_to_add : gpio_ports_to_add) {
if (false == gpio_port_to_add.mergeable(gpio_port)) {
continue;
}
is_mergeable = true;
/* For mergeable ports, we combine the port
* Note: do NOT use the merge() method!
* the GPIO ports should be accumulated by the sizes of ports
* not by the LSB/MSB range !!!
*/
gpio_port_to_add.combine(gpio_port);
break;
}
if (false == is_mergeable) {
/* Reach here, this is an unique gpio port, update the list */
gpio_ports_to_add.push_back(gpio_port);
}
}
}
}
/* Record the port id for each type of GPIO port */
std::vector<ModulePortId> gpio_port_ids;
/* Add the gpio ports for the module */
for (const BasicPort& gpio_port_to_add : gpio_ports_to_add) {
ModulePortId port_id = module_manager.add_port(module_id, gpio_port_to_add, ModuleManager::MODULE_GPIO_PORT);
gpio_port_ids.push_back(port_id);
}
/* Set up a counter for each type of GPIO port */
std::vector<size_t> gpio_port_lsb(gpio_ports_to_add.size(), 0);
/* Add module nets to connect the GPIOs of the module to the GPIOs of the sub module */
for (const ModuleId& child : module_manager.child_modules(module_id)) {
/* Iterate over the child instances */
for (const size_t& child_instance : module_manager.child_module_instances(module_id, child)) {
/* Find all the global ports, whose port type is special */
for (ModulePortId child_gpio_port_id : module_manager.module_port_ids_by_type(child, ModuleManager::MODULE_GPIO_PORT)) {
BasicPort child_gpio_port = module_manager.module_port(child, child_gpio_port_id);
/* Find the port with the same name! */
for (size_t iport = 0; iport < gpio_ports_to_add.size(); ++iport) {
if (false == gpio_ports_to_add[iport].mergeable(child_gpio_port)) {
continue;
}
/* For each pin of the child port, create a net and do wiring */
for (const size_t& pin_id : child_gpio_port.pins()) {
/* Reach here, it means this is the port we want, create a net and configure its source and sink */
ModuleNetId net = module_manager.create_module_net(module_id);
module_manager.add_module_net_source(module_id, net, module_id, 0, gpio_port_ids[iport], gpio_port_lsb[iport]);
module_manager.add_module_net_sink(module_id, net, child, child_instance, child_gpio_port_id, pin_id);
/* Update the LSB counter */
gpio_port_lsb[iport]++;
}
/* We finish for this child gpio port */
break;
}
}
}
}
/* Check: all the lsb should now match the size of each GPIO port */
for (size_t iport = 0; iport < gpio_ports_to_add.size(); ++iport) {
if (gpio_ports_to_add[iport].get_width() != gpio_port_lsb[iport])
VTR_ASSERT(gpio_ports_to_add[iport].get_width() == gpio_port_lsb[iport]);
}
}
/********************************************************************
* Add global ports to the module:
* In this function, the following tasks are done:
* 1. find all the global ports from the child modules and build a list of it,
* 2. add the ports to the pb_module
* 3. add the module nets to connect the pb_module global ports to those of child modules
*
* Note: This function should be call ONLY after all the sub modules (instances)
* have been added to the pb_module!
* Otherwise, some global ports of the sub modules may be missed!
*******************************************************************/
void add_module_global_ports_from_child_modules(ModuleManager& module_manager,
const ModuleId& module_id) {
std::vector<BasicPort> global_ports_to_add;
/* Iterate over the child modules */
for (const ModuleId& child : module_manager.child_modules(module_id)) {
/* Iterate over the child instances */
for (size_t i = 0; i < module_manager.num_instance(module_id, child); ++i) {
/* Find all the global ports, whose port type is special */
for (BasicPort global_port : module_manager.module_ports_by_type(child, ModuleManager::MODULE_GLOBAL_PORT)) {
/* Search in the global port list to be added, if this is unique, we update the list */
std::vector<BasicPort>::iterator it = std::find(global_ports_to_add.begin(), global_ports_to_add.end(), global_port);
if (it != global_ports_to_add.end()) {
continue;
}
/* Reach here, this is an unique global port, update the list */
global_ports_to_add.push_back(global_port);
}
}
}
/* Record the port id for each type of global port */
std::vector<ModulePortId> global_port_ids;
/* Add the global ports for the module */
for (const BasicPort& global_port_to_add : global_ports_to_add) {
ModulePortId port_id = module_manager.add_port(module_id, global_port_to_add, ModuleManager::MODULE_GLOBAL_PORT);
global_port_ids.push_back(port_id);
}
/* Add module nets to connect the global ports of the module to the global ports of the sub module */
/* Iterate over the child modules */
for (const ModuleId& child : module_manager.child_modules(module_id)) {
/* Iterate over the child instances */
for (const size_t& child_instance : module_manager.child_module_instances(module_id, child)) {
/* Find all the global ports, whose port type is special */
for (ModulePortId child_global_port_id : module_manager.module_port_ids_by_type(child, ModuleManager::MODULE_GLOBAL_PORT)) {
BasicPort child_global_port = module_manager.module_port(child, child_global_port_id);
/* Search in the global port list to be added, find the port id */
std::vector<BasicPort>::iterator it = std::find(global_ports_to_add.begin(), global_ports_to_add.end(), child_global_port);
VTR_ASSERT(it != global_ports_to_add.end());
ModulePortId module_global_port_id = global_port_ids[it - global_ports_to_add.begin()];
BasicPort module_global_port = module_manager.module_port(module_id, module_global_port_id);
/* The global ports should match in size */
VTR_ASSERT(module_global_port.get_width() == child_global_port.get_width());
/* For each pin of the child port, create a net and do wiring */
for (size_t pin_id = 0; pin_id < child_global_port.pins().size(); ++pin_id) {
/* Reach here, it means this is the port we want, create a net and configure its source and sink */
ModuleNetId net = module_manager.create_module_net(module_id);
module_manager.add_module_net_source(module_id, net, module_id, 0, module_global_port_id, module_global_port.pins()[pin_id]);
module_manager.add_module_net_sink(module_id, net, child, child_instance, child_global_port_id, child_global_port.pins()[pin_id]);
/* We finish for this child gpio port */
}
}
}
}
}
/********************************************************************
* Find the number of shared configuration bits for a module
* by selected the maximum number of shared configuration bits of child modules
*
* Note: This function should be call ONLY after all the sub modules (instances)
* have been added to the pb_module!
* Otherwise, some global ports of the sub modules may be missed!
*******************************************************************/
size_t find_module_num_shared_config_bits_from_child_modules(ModuleManager& module_manager,
const ModuleId& module_id) {
size_t num_shared_config_bits = 0;
/* Iterate over the child modules */
for (const ModuleId& child : module_manager.child_modules(module_id)) {
num_shared_config_bits = std::max((int)num_shared_config_bits, (int)find_module_num_shared_config_bits(module_manager, child));
}
return num_shared_config_bits;
}
/********************************************************************
* Find the number of configuration bits for a module
* by summing up the number of configuration bits of child modules
*
* Note: This function should be call ONLY after all the sub modules (instances)
* have been added to the pb_module!
* Otherwise, some global ports of the sub modules may be missed!
*******************************************************************/
size_t find_module_num_config_bits_from_child_modules(ModuleManager& module_manager,
const ModuleId& module_id,
const CircuitLibrary& circuit_lib,
const CircuitModelId& sram_model,
const e_sram_orgz& sram_orgz_type) {
size_t num_config_bits = 0;
/* Iterate over the child modules */
for (const ModuleId& child : module_manager.child_modules(module_id)) {
num_config_bits += find_module_num_config_bits(module_manager, child, circuit_lib, sram_model, sram_orgz_type);
}
return num_config_bits;
}
/********************************************************************
* TODO:
* Add the port-to-port connection between a logic module
* and a memory module inside a primitive module
*
* Create nets to wire the formal verification ports of
* primitive module to SRAM ports of logic module
*
* Primitive module
*
* formal_port_sram
* +-----------------------------------------------+
* | ^ |
* | +---------+ | +--------+ |
* | | | SRAM | | | |
* | | Logic |--------+--->| Memory | |
* | | Module | SRAMb | Module | |
* | | |--------+--->| | |
* | +---------+ | +--------+ |
* | v |
* +-----------------------------------------------+
* formal_port_sramb
*
*******************************************************************/
| 50.454939 | 193 | 0.597905 | srtemp |
f8c8a319edeff07cbe3f650e5df4c96c7ecde59f | 1,770 | cpp | C++ | modules/svg/src/SkSVGLinearGradient.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | modules/svg/src/SkSVGLinearGradient.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | modules/svg/src/SkSVGLinearGradient.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/effects/SkGradientShader.h"
#include "modules/svg/include/SkSVGLinearGradient.h"
#include "modules/svg/include/SkSVGRenderContext.h"
#include "modules/svg/include/SkSVGValue.h"
SkSVGLinearGradient::SkSVGLinearGradient() : INHERITED(SkSVGTag::kLinearGradient) {}
bool SkSVGLinearGradient::parseAndSetAttribute(const char* name, const char* value) {
return INHERITED::parseAndSetAttribute(name, value) ||
this->setX1(SkSVGAttributeParser::parse<SkSVGLength>("x1", name, value)) ||
this->setY1(SkSVGAttributeParser::parse<SkSVGLength>("y1", name, value)) ||
this->setX2(SkSVGAttributeParser::parse<SkSVGLength>("x2", name, value)) ||
this->setY2(SkSVGAttributeParser::parse<SkSVGLength>("y2", name, value));
}
sk_sp<SkShader> SkSVGLinearGradient::onMakeShader(
const SkSVGRenderContext& ctx, const SkColor* colors, const SkScalar* pos, int count,
SkTileMode tm, const SkMatrix& localMatrix) const {
const SkSVGLengthContext lctx =
this->getGradientUnits().type() == SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox
? SkSVGLengthContext({1, 1})
: ctx.lengthContext();
const auto x1 = lctx.resolve(fX1, SkSVGLengthContext::LengthType::kHorizontal);
const auto y1 = lctx.resolve(fY1, SkSVGLengthContext::LengthType::kVertical);
const auto x2 = lctx.resolve(fX2, SkSVGLengthContext::LengthType::kHorizontal);
const auto y2 = lctx.resolve(fY2, SkSVGLengthContext::LengthType::kVertical);
const SkPoint pts[2] = {{x1, y1}, {x2, y2}};
return SkGradientShader::MakeLinear(pts, colors, pos, count, tm, 0, &localMatrix);
}
| 44.25 | 94 | 0.731638 | NearTox |
f8cb56029f4da872149a26ba87fb3a9c35c4575b | 156 | cc | C++ | cake_test1.cc | maaku33/jnp-zadanie4 | c8faf6734b00f9fd367e0f2eeb33559fc26dc81c | [
"MIT"
] | null | null | null | cake_test1.cc | maaku33/jnp-zadanie4 | c8faf6734b00f9fd367e0f2eeb33559fc26dc81c | [
"MIT"
] | null | null | null | cake_test1.cc | maaku33/jnp-zadanie4 | c8faf6734b00f9fd367e0f2eeb33559fc26dc81c | [
"MIT"
] | null | null | null | #include "cake.h"
#include <iostream>
int main() {
CheeseCake<int, 10, 15> cheeseCake1(4);
CreamCake<int, 12, 12, double> creamCake(3, 25.9);
}
| 17.333333 | 54 | 0.628205 | maaku33 |
f8cbc90a691b72a235ad926f6a774ec7d4c69928 | 1,220 | cpp | C++ | src/gameworld/gameworld/obj/otherobj/scenearea.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/gameworld/gameworld/obj/otherobj/scenearea.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/gameworld/gameworld/obj/otherobj/scenearea.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #include "scenearea.h"
#include "scene/scene.h"
#include "obj/character/role.h"
#include "other/event/eventhandler.hpp"
#include "config/logicconfigmanager.hpp"
#include "scene/activityshadow/activityshadow.hpp"
#include "protocal/msgactivity.hpp"
SceneArea::SceneArea():Obj(OBJ_TYPE_SCENEAREA), m_range(4), m_aoi_handle(-1)
{
}
SceneArea::~SceneArea()
{
}
void SceneArea::Init(const Posi &pos, Axis aoi_range)
{
m_posi = pos;
m_range = aoi_range;
}
void SceneArea::OnEnterScene()
{
if (NULL == m_scene) return;
m_aoi_handle = m_scene->GetZoneMatrix()->CreateRectAOI(m_obj_id, m_posi, Posi(m_range, m_range),
Posi(m_range + 2, m_range + 2));
}
void SceneArea::OnLeaveScene()
{
if (NULL == m_scene) return;
m_scene->GetZoneMatrix()->DestroyAOI(m_aoi_handle);
}
void SceneArea::OnAOIEnter(ObjID obj_id)
{
if (NULL == m_scene) return;
/*Obj *obj = m_scene->GetObj(obj_id);
if (NULL != obj && Obj::OBJ_TYPE_ROLE == obj->GetObjType())
{
Role *role = (Role*)obj;
}*/
}
void SceneArea::OnAOILeave(ObjID obj_id)
{
/*if (NULL == m_scene) return;
Obj *obj = m_scene->GetObj(obj_id);
if (NULL != obj && Obj::OBJ_TYPE_ROLE == obj->GetObjType())
{
Role *role = (Role*)obj;
}*/
}
| 17.183099 | 98 | 0.681148 | mage-game |
f8cbf7dd019d48150a023d6da8da9a86b7e7037f | 293 | cpp | C++ | CPP/HelloCpp2/chapter_44/struct.cpp | hrntsm/study-language | 922578a5321d70c26b935e6052f400125e15649c | [
"MIT"
] | 1 | 2022-02-06T10:50:42.000Z | 2022-02-06T10:50:42.000Z | CPP/HelloCpp2/chapter_44/struct.cpp | hrntsm/study-language | 922578a5321d70c26b935e6052f400125e15649c | [
"MIT"
] | null | null | null | CPP/HelloCpp2/chapter_44/struct.cpp | hrntsm/study-language | 922578a5321d70c26b935e6052f400125e15649c | [
"MIT"
] | null | null | null | #include <iostream>
using std::cout;
struct Kitty
{
explicit Kitty(char *str)
{
this->str = str;
}
char *getStr()
{
return str;
}
private:
char *str;
};
int main()
{
Kitty obj("Kitty on your lap\n");
cout << obj.getStr();
return 0;
}
| 11.72 | 37 | 0.515358 | hrntsm |
f8d60b5407e1ab45b93d23e92851ed944bc95c6a | 7,291 | cpp | C++ | hacks/c_chams.cpp | Rebirator/GLadiators.technology-v2-Rifk7 | 7692ad3fce3f6e0638e7c8924f4bb972a2632d0f | [
"MIT"
] | 4 | 2020-08-13T11:11:31.000Z | 2021-09-24T16:55:42.000Z | hacks/c_chams.cpp | Rebirator/GLadiators.technology-v2-Rifk7 | 7692ad3fce3f6e0638e7c8924f4bb972a2632d0f | [
"MIT"
] | null | null | null | hacks/c_chams.cpp | Rebirator/GLadiators.technology-v2-Rifk7 | 7692ad3fce3f6e0638e7c8924f4bb972a2632d0f | [
"MIT"
] | 6 | 2020-07-15T17:00:14.000Z | 2022-03-25T07:45:13.000Z | #include "c_chams.h"
#include "../security/string_obfuscation.h"
#include "../sdk/c_material_system.h"
#include "../sdk/c_render_view.h"
#include "../menu/framework/macros.h"
#include "../utils/c_config.h"
#include "../sdk/c_client_entity_list.h"
#include "c_animation_system.h"
#include "../utils/math.h"
#include "../sdk/c_client_state.h"
#include "../sdk/c_prediction.h"
c_chams::c_chams() : current_player(nullptr), current_matrix(nullptr), second_pass(false),
alpha(255), direction(false) { }
void c_chams::latch_timer()
{
if (!engine_client()->is_ingame())
return;
if (alpha == 0 || alpha == 255)
direction = !direction;
linear_fade(alpha, 0, 255, 255 / 2.5f, direction);
}
void c_chams::draw_players()
{
if (!engine_client()->is_ingame())
return;
client_entity_list()->for_each_player_fixed_z_order([&] (c_cs_player* player) -> void
{
instance()->current_player = player;
instance()->second_pass = false;
const auto conf = player->is_enemy() ? config.chams.enemy : config.chams.team;
if (conf.xqz)
{
instance()->second_pass = true;
player->draw_model(1, 255);
}
if (player->is_enemy() && config.chams.backtrack.type)
{
matrix3x4 interpolated[128] = {};
if (get_backtrack_matrix(player, interpolated))
{
instance()->current_matrix = interpolated;
if (config.chams.backtrack.xqz)
{
instance()->second_pass = true;
player->draw_model(1, 255);
}
instance()->current_matrix = nullptr;
}
}
});
instance()->current_player = nullptr;
const auto local = c_cs_player::get_local_player();
if (local)
{
instance()->second_pass = true;
instance()->current_player = local;
local->draw_model(1, 255);
}
instance()->second_pass = false;
instance()->current_player = nullptr;
}
bool c_chams::get_backtrack_matrix(c_cs_player* player, matrix3x4* out)
{
if (!engine_client()->is_ingame())
return false;
if (!net_channel)
return false;
auto range = config.legit.backtrack / 100.f;
if (config.rage.enabled)
range = 1.f;
const auto last = animation_system->get_intermediate_animations(player, range);
if (!last.has_value())
return false;
const auto& first_invalid = last.value().first;
const auto& last_valid = last.value().second;
if ((first_invalid->origin - player->get_abs_origin()).length() < 7.5f)
return false;
if (first_invalid->dormant)
return false;
if (last_valid->sim_time - first_invalid->sim_time > 0.5f)
return false;
const auto next = last_valid->origin;
const auto curtime = prediction()->get_unpredicted_globals()->curtime;
auto delta = 1.f - (curtime - last_valid->interp_time) / (last_valid->sim_time - first_invalid->sim_time);
if (delta < 0.f || delta > 1.f)
last_valid->interp_time = curtime;
delta = 1.f - (curtime - last_valid->interp_time) / (last_valid->sim_time - first_invalid->sim_time);
const auto lerp = math::interpolate(next, first_invalid->origin, std::clamp(delta, 0.f, 1.f));
matrix3x4 ret[128];
memcpy(ret, first_invalid->bones, sizeof(matrix3x4[128]));
for (size_t i{}; i < 128; ++i)
{
const auto matrix_delta = math::matrix_get_origin(first_invalid->bones[i]) - first_invalid->origin;
math::matrix_set_origin(matrix_delta + lerp, ret[i]);
}
memcpy(out, ret, sizeof(matrix3x4[128]));
return true;
}
void c_chams::player_chams(const std::function<void()> original, c_config::config_conf::chams_conf::chams& conf)
{
if (!conf.type)
return;
static const auto glow = find_mat("dev/glow_armsrace");
static const auto cube = find_mat("debug/debugambientcube");
static const auto glass = find_mat("models/gibs/glass/glass");
static const auto skull = find_mat("models/gibs/hgibs/skull1");
const auto alpha = conf.type == 1 ? instance()->alpha : 255;
set_ignorez(instance()->second_pass ? conf.xqz : false);
if (conf.type == 1)
{
if (!instance()->current_matrix)
original();
modulate(conf.color, glow);
modulate_exp(glow, alpha / 255.f, 60.f);
model_render()->forced_material_override(glow);
if (instance()->second_pass && conf.xqz)
{
original();
if (!instance()->current_matrix)
{
set_ignorez(false);
render_view()->set_color_modulation(c_color(255, 255, 255));
model_render()->forced_material_override(nullptr);
original();
}
modulate(conf.color, glow);
modulate_exp(glow, alpha / 255.f, 60.f);
model_render()->forced_material_override(glow);
}
}
else
{
const auto material = conf.type == 2 ? cube : conf.type == 3 ? skull : glass;
modulate(conf.color, material);
model_render()->forced_material_override(material);
original();
modulate(c_color::foreground(), glow);
modulate_exp(glow, alpha / 255.f, 60.f);
model_render()->forced_material_override(glow);
original();
if (instance()->second_pass && conf.xqz)
{
set_ignorez(false);
modulate(conf.color, material);
model_render()->forced_material_override(material);
original();
modulate(c_color::foreground(), glow);
modulate_exp(glow, alpha / 255.f, 60.f);
model_render()->forced_material_override(glow);
}
}
}
void c_chams::viewmodel_chams(const std::function<void()> original, c_config::config_conf::chams_conf::chams& conf)
{
if (!conf.type)
return;
static const auto glow = find_mat("dev/glow_armsrace");
static const auto fbi = find_mat("models/player/ct_fbi/ct_fbi_glass");
static const auto tags = find_mat("models/inventory_items/dogtags/dogtags_lightray");
const auto alpha = conf.type == 1 || conf.type == 4 ? instance()->alpha : 255;
if (conf.type == 1)
{
original();
modulate(conf.color, glow);
modulate_exp(glow, alpha / 255.f);
model_render()->forced_material_override(glow);
}
else
{
modulate(c_color::background(), fbi);
model_render()->forced_material_override(fbi);
original();
render_view()->set_blend(alpha / 255.f);
tags->set_material_var_flag(material_var_wireframe, true);
modulate(conf.color, tags);
model_render()->forced_material_override(tags);
if (conf.type > 2)
{
original();
render_view()->set_blend(1.f);
modulate(conf.color, glow);
modulate_exp(glow, alpha / 255.f);
model_render()->forced_material_override(glow);
}
}
}
void c_chams::modulate(const c_color color, c_material* material)
{
if (material)
{
material->modulate(color);
const auto tint = material->find_var(_("$envmaptint"));
if (tint)
tint->set_vector(c_vector3d(color.red / 255.f, color.green / 255.f, color.blue / 255.f));
}
render_view()->set_color_modulation(color);
}
void c_chams::modulate_exp(c_material* material, const float alpha, const float width)
{
const auto transform = material->find_var(_("$envmapfresnelminmaxexp"));
if (transform)
transform->set_vector_component(width * alpha, 1);
}
void c_chams::set_ignorez(const bool enabled)
{
static const auto glow = find_mat("dev/glow_armsrace");
static const auto cube = find_mat("debug/debugambientcube");
static const auto glass = find_mat("models/gibs/glass/glass");
static const auto skull = find_mat("models/gibs/hgibs/skull1");
glow->set_material_var_flag(material_var_ignorez, enabled);
cube->set_material_var_flag(material_var_ignorez, enabled);
glass->set_material_var_flag(material_var_ignorez, enabled);
skull->set_material_var_flag(material_var_ignorez, enabled);
}
| 27.205224 | 115 | 0.702647 | Rebirator |
f8d7f6f1c57c208c2252bde3cd88d05785d01dc0 | 13,888 | cpp | C++ | bin/windows/cpp/obj/src/flash/display/LoaderInfo.cpp | DrSkipper/twogames | 916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b | [
"MIT"
] | null | null | null | bin/windows/cpp/obj/src/flash/display/LoaderInfo.cpp | DrSkipper/twogames | 916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b | [
"MIT"
] | null | null | null | bin/windows/cpp/obj/src/flash/display/LoaderInfo.cpp | DrSkipper/twogames | 916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b | [
"MIT"
] | null | null | null | #include <hxcpp.h>
#ifndef INCLUDED_flash_display_DisplayObject
#include <flash/display/DisplayObject.h>
#endif
#ifndef INCLUDED_flash_display_DisplayObjectContainer
#include <flash/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_flash_display_IBitmapDrawable
#include <flash/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_flash_display_InteractiveObject
#include <flash/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_flash_display_Loader
#include <flash/display/Loader.h>
#endif
#ifndef INCLUDED_flash_display_LoaderInfo
#include <flash/display/LoaderInfo.h>
#endif
#ifndef INCLUDED_flash_display_Sprite
#include <flash/display/Sprite.h>
#endif
#ifndef INCLUDED_flash_events_Event
#include <flash/events/Event.h>
#endif
#ifndef INCLUDED_flash_events_EventDispatcher
#include <flash/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_flash_events_IEventDispatcher
#include <flash/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_flash_events_UncaughtErrorEvents
#include <flash/events/UncaughtErrorEvents.h>
#endif
#ifndef INCLUDED_flash_net_URLLoader
#include <flash/net/URLLoader.h>
#endif
#ifndef INCLUDED_flash_net_URLLoaderDataFormat
#include <flash/net/URLLoaderDataFormat.h>
#endif
#ifndef INCLUDED_flash_net_URLRequest
#include <flash/net/URLRequest.h>
#endif
#ifndef INCLUDED_flash_system_ApplicationDomain
#include <flash/system/ApplicationDomain.h>
#endif
#ifndef INCLUDED_flash_utils_ByteArray
#include <flash/utils/ByteArray.h>
#endif
#ifndef INCLUDED_flash_utils_IDataInput
#include <flash/utils/IDataInput.h>
#endif
#ifndef INCLUDED_flash_utils_IDataOutput
#include <flash/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_openfl_utils_IMemoryRange
#include <openfl/utils/IMemoryRange.h>
#endif
namespace flash{
namespace display{
Void LoaderInfo_obj::__construct()
{
HX_STACK_PUSH("LoaderInfo::new","flash/display/LoaderInfo.hx",37);
{
HX_STACK_LINE(39)
super::__construct(null());
HX_STACK_LINE(41)
this->applicationDomain = ::flash::system::ApplicationDomain_obj::currentDomain;
HX_STACK_LINE(42)
this->childAllowsParent = true;
HX_STACK_LINE(43)
this->frameRate = (int)0;
HX_STACK_LINE(44)
this->dataFormat = ::flash::net::URLLoaderDataFormat_obj::BINARY;
HX_STACK_LINE(45)
this->loaderURL = null();
HX_STACK_LINE(46)
this->addEventListener(::flash::events::Event_obj::COMPLETE,this->this_onComplete_dyn(),null(),null(),null());
}
;
return null();
}
LoaderInfo_obj::~LoaderInfo_obj() { }
Dynamic LoaderInfo_obj::__CreateEmpty() { return new LoaderInfo_obj; }
hx::ObjectPtr< LoaderInfo_obj > LoaderInfo_obj::__new()
{ hx::ObjectPtr< LoaderInfo_obj > result = new LoaderInfo_obj();
result->__construct();
return result;}
Dynamic LoaderInfo_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< LoaderInfo_obj > result = new LoaderInfo_obj();
result->__construct();
return result;}
::flash::utils::ByteArray LoaderInfo_obj::get_bytes( ){
HX_STACK_PUSH("LoaderInfo::get_bytes","flash/display/LoaderInfo.hx",113);
HX_STACK_THIS(this);
HX_STACK_LINE(113)
return this->data;
}
HX_DEFINE_DYNAMIC_FUNC0(LoaderInfo_obj,get_bytes,return )
Void LoaderInfo_obj::this_onComplete( ::flash::events::Event event){
{
HX_STACK_PUSH("LoaderInfo::this_onComplete","flash/display/LoaderInfo.hx",99);
HX_STACK_THIS(this);
HX_STACK_ARG(event,"event");
HX_STACK_LINE(99)
this->url = this->__pendingURL;
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC1(LoaderInfo_obj,this_onComplete,(void))
Void LoaderInfo_obj::load( ::flash::net::URLRequest request){
{
HX_STACK_PUSH("LoaderInfo::load","flash/display/LoaderInfo.hx",68);
HX_STACK_THIS(this);
HX_STACK_ARG(request,"request");
HX_STACK_LINE(70)
this->__pendingURL = request->url;
HX_STACK_LINE(71)
int dot = this->__pendingURL.lastIndexOf(HX_CSTRING("."),null()); HX_STACK_VAR(dot,"dot");
HX_STACK_LINE(72)
::String extension = ( (((dot > (int)0))) ? ::String(this->__pendingURL.substr((dot + (int)1),null()).toLowerCase()) : ::String(HX_CSTRING("")) ); HX_STACK_VAR(extension,"extension");
struct _Function_1_1{
inline static ::String Block( ::String &extension,::flash::display::LoaderInfo_obj *__this){
HX_STACK_PUSH("*::closure","flash/display/LoaderInfo.hx",74);
{
HX_STACK_LINE(74)
::String _switch_1 = (extension);
if ( ( _switch_1==HX_CSTRING("swf"))){
HX_STACK_LINE(76)
return HX_CSTRING("application/x-shockwave-flash");
}
else if ( ( _switch_1==HX_CSTRING("jpg")) || ( _switch_1==HX_CSTRING("jpeg"))){
HX_STACK_LINE(77)
return HX_CSTRING("image/jpeg");
}
else if ( ( _switch_1==HX_CSTRING("png"))){
HX_STACK_LINE(78)
return HX_CSTRING("image/png");
}
else if ( ( _switch_1==HX_CSTRING("gif"))){
HX_STACK_LINE(79)
return HX_CSTRING("image/gif");
}
else {
HX_STACK_LINE(80)
return hx::Throw ((HX_CSTRING("Unrecognized file ") + __this->__pendingURL));
}
;
;
}
return null();
}
};
HX_STACK_LINE(74)
this->contentType = _Function_1_1::Block(extension,this);
HX_STACK_LINE(85)
this->url = null();
HX_STACK_LINE(87)
this->super::load(request);
}
return null();
}
::flash::display::LoaderInfo LoaderInfo_obj::create( ::flash::display::Loader loader){
HX_STACK_PUSH("LoaderInfo::create","flash/display/LoaderInfo.hx",51);
HX_STACK_ARG(loader,"loader");
HX_STACK_LINE(53)
::flash::display::LoaderInfo loaderInfo = ::flash::display::LoaderInfo_obj::__new(); HX_STACK_VAR(loaderInfo,"loaderInfo");
HX_STACK_LINE(54)
loaderInfo->loader = loader;
HX_STACK_LINE(55)
loaderInfo->uncaughtErrorEvents = ::flash::events::UncaughtErrorEvents_obj::__new(null());
HX_STACK_LINE(57)
if (((loader == null()))){
HX_STACK_LINE(57)
loaderInfo->url = HX_CSTRING("");
}
HX_STACK_LINE(63)
return loaderInfo;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(LoaderInfo_obj,create,return )
LoaderInfo_obj::LoaderInfo_obj()
{
}
void LoaderInfo_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(LoaderInfo);
HX_MARK_MEMBER_NAME(__pendingURL,"__pendingURL");
HX_MARK_MEMBER_NAME(uncaughtErrorEvents,"uncaughtErrorEvents");
HX_MARK_MEMBER_NAME(width,"width");
HX_MARK_MEMBER_NAME(url,"url");
HX_MARK_MEMBER_NAME(sharedEvents,"sharedEvents");
HX_MARK_MEMBER_NAME(sameDomain,"sameDomain");
HX_MARK_MEMBER_NAME(parentAllowsChild,"parentAllowsChild");
HX_MARK_MEMBER_NAME(parameters,"parameters");
HX_MARK_MEMBER_NAME(loaderURL,"loaderURL");
HX_MARK_MEMBER_NAME(loader,"loader");
HX_MARK_MEMBER_NAME(height,"height");
HX_MARK_MEMBER_NAME(frameRate,"frameRate");
HX_MARK_MEMBER_NAME(contentType,"contentType");
HX_MARK_MEMBER_NAME(content,"content");
HX_MARK_MEMBER_NAME(childAllowsParent,"childAllowsParent");
HX_MARK_MEMBER_NAME(bytes,"bytes");
HX_MARK_MEMBER_NAME(applicationDomain,"applicationDomain");
super::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void LoaderInfo_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(__pendingURL,"__pendingURL");
HX_VISIT_MEMBER_NAME(uncaughtErrorEvents,"uncaughtErrorEvents");
HX_VISIT_MEMBER_NAME(width,"width");
HX_VISIT_MEMBER_NAME(url,"url");
HX_VISIT_MEMBER_NAME(sharedEvents,"sharedEvents");
HX_VISIT_MEMBER_NAME(sameDomain,"sameDomain");
HX_VISIT_MEMBER_NAME(parentAllowsChild,"parentAllowsChild");
HX_VISIT_MEMBER_NAME(parameters,"parameters");
HX_VISIT_MEMBER_NAME(loaderURL,"loaderURL");
HX_VISIT_MEMBER_NAME(loader,"loader");
HX_VISIT_MEMBER_NAME(height,"height");
HX_VISIT_MEMBER_NAME(frameRate,"frameRate");
HX_VISIT_MEMBER_NAME(contentType,"contentType");
HX_VISIT_MEMBER_NAME(content,"content");
HX_VISIT_MEMBER_NAME(childAllowsParent,"childAllowsParent");
HX_VISIT_MEMBER_NAME(bytes,"bytes");
HX_VISIT_MEMBER_NAME(applicationDomain,"applicationDomain");
super::__Visit(HX_VISIT_ARG);
}
Dynamic LoaderInfo_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"url") ) { return url; }
break;
case 4:
if (HX_FIELD_EQ(inName,"load") ) { return load_dyn(); }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { return width; }
if (HX_FIELD_EQ(inName,"bytes") ) { return inCallProp ? get_bytes() : bytes; }
break;
case 6:
if (HX_FIELD_EQ(inName,"create") ) { return create_dyn(); }
if (HX_FIELD_EQ(inName,"loader") ) { return loader; }
if (HX_FIELD_EQ(inName,"height") ) { return height; }
break;
case 7:
if (HX_FIELD_EQ(inName,"content") ) { return content; }
break;
case 9:
if (HX_FIELD_EQ(inName,"get_bytes") ) { return get_bytes_dyn(); }
if (HX_FIELD_EQ(inName,"loaderURL") ) { return loaderURL; }
if (HX_FIELD_EQ(inName,"frameRate") ) { return frameRate; }
break;
case 10:
if (HX_FIELD_EQ(inName,"sameDomain") ) { return sameDomain; }
if (HX_FIELD_EQ(inName,"parameters") ) { return parameters; }
break;
case 11:
if (HX_FIELD_EQ(inName,"contentType") ) { return contentType; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__pendingURL") ) { return __pendingURL; }
if (HX_FIELD_EQ(inName,"sharedEvents") ) { return sharedEvents; }
break;
case 15:
if (HX_FIELD_EQ(inName,"this_onComplete") ) { return this_onComplete_dyn(); }
break;
case 17:
if (HX_FIELD_EQ(inName,"parentAllowsChild") ) { return parentAllowsChild; }
if (HX_FIELD_EQ(inName,"childAllowsParent") ) { return childAllowsParent; }
if (HX_FIELD_EQ(inName,"applicationDomain") ) { return applicationDomain; }
break;
case 19:
if (HX_FIELD_EQ(inName,"uncaughtErrorEvents") ) { return uncaughtErrorEvents; }
}
return super::__Field(inName,inCallProp);
}
Dynamic LoaderInfo_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"url") ) { url=inValue.Cast< ::String >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"bytes") ) { bytes=inValue.Cast< ::flash::utils::ByteArray >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"loader") ) { loader=inValue.Cast< ::flash::display::Loader >(); return inValue; }
if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"content") ) { content=inValue.Cast< ::flash::display::DisplayObject >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"loaderURL") ) { loaderURL=inValue.Cast< ::String >(); return inValue; }
if (HX_FIELD_EQ(inName,"frameRate") ) { frameRate=inValue.Cast< Float >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"sameDomain") ) { sameDomain=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"parameters") ) { parameters=inValue.Cast< Dynamic >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"contentType") ) { contentType=inValue.Cast< ::String >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__pendingURL") ) { __pendingURL=inValue.Cast< ::String >(); return inValue; }
if (HX_FIELD_EQ(inName,"sharedEvents") ) { sharedEvents=inValue.Cast< ::flash::events::EventDispatcher >(); return inValue; }
break;
case 17:
if (HX_FIELD_EQ(inName,"parentAllowsChild") ) { parentAllowsChild=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"childAllowsParent") ) { childAllowsParent=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"applicationDomain") ) { applicationDomain=inValue.Cast< ::flash::system::ApplicationDomain >(); return inValue; }
break;
case 19:
if (HX_FIELD_EQ(inName,"uncaughtErrorEvents") ) { uncaughtErrorEvents=inValue.Cast< ::flash::events::UncaughtErrorEvents >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void LoaderInfo_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("__pendingURL"));
outFields->push(HX_CSTRING("uncaughtErrorEvents"));
outFields->push(HX_CSTRING("width"));
outFields->push(HX_CSTRING("url"));
outFields->push(HX_CSTRING("sharedEvents"));
outFields->push(HX_CSTRING("sameDomain"));
outFields->push(HX_CSTRING("parentAllowsChild"));
outFields->push(HX_CSTRING("parameters"));
outFields->push(HX_CSTRING("loaderURL"));
outFields->push(HX_CSTRING("loader"));
outFields->push(HX_CSTRING("height"));
outFields->push(HX_CSTRING("frameRate"));
outFields->push(HX_CSTRING("contentType"));
outFields->push(HX_CSTRING("content"));
outFields->push(HX_CSTRING("childAllowsParent"));
outFields->push(HX_CSTRING("bytes"));
outFields->push(HX_CSTRING("applicationDomain"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("create"),
String(null()) };
static ::String sMemberFields[] = {
HX_CSTRING("get_bytes"),
HX_CSTRING("this_onComplete"),
HX_CSTRING("load"),
HX_CSTRING("__pendingURL"),
HX_CSTRING("uncaughtErrorEvents"),
HX_CSTRING("width"),
HX_CSTRING("url"),
HX_CSTRING("sharedEvents"),
HX_CSTRING("sameDomain"),
HX_CSTRING("parentAllowsChild"),
HX_CSTRING("parameters"),
HX_CSTRING("loaderURL"),
HX_CSTRING("loader"),
HX_CSTRING("height"),
HX_CSTRING("frameRate"),
HX_CSTRING("contentType"),
HX_CSTRING("content"),
HX_CSTRING("childAllowsParent"),
HX_CSTRING("bytes"),
HX_CSTRING("applicationDomain"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(LoaderInfo_obj::__mClass,"__mClass");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(LoaderInfo_obj::__mClass,"__mClass");
};
Class LoaderInfo_obj::__mClass;
void LoaderInfo_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("flash.display.LoaderInfo"), hx::TCanCast< LoaderInfo_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void LoaderInfo_obj::__boot()
{
}
} // end namespace flash
} // end namespace display
| 33.22488 | 187 | 0.744312 | DrSkipper |
f8d8a1a2ae392039352bbe1a39ee224a7757d9dd | 1,516 | cc | C++ | lib/asan/lit_tests/stack-use-after-return.cc | tylerfox/compiler-rt | 940db39932e702fbc6ced148ff16263562862f5a | [
"MIT"
] | null | null | null | lib/asan/lit_tests/stack-use-after-return.cc | tylerfox/compiler-rt | 940db39932e702fbc6ced148ff16263562862f5a | [
"MIT"
] | null | null | null | lib/asan/lit_tests/stack-use-after-return.cc | tylerfox/compiler-rt | 940db39932e702fbc6ced148ff16263562862f5a | [
"MIT"
] | null | null | null | // XFAIL: *
// RUN: %clangxx_asan -fsanitize=use-after-return -m64 -O0 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m64 -O1 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m64 -O2 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m64 -O3 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m32 -O0 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m32 -O1 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m32 -O2 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
// RUN: %clangxx_asan -fsanitize=use-after-return -m32 -O3 %s -o %t && \
// RUN: %t 2>&1 | %symbolize | FileCheck %s
#include <stdio.h>
__attribute__((noinline))
char *Ident(char *x) {
fprintf(stderr, "1: %p\n", x);
return x;
}
__attribute__((noinline))
char *Func1() {
char local;
return Ident(&local);
}
__attribute__((noinline))
void Func2(char *x) {
fprintf(stderr, "2: %p\n", x);
*x = 1;
// CHECK: WRITE of size 1 {{.*}} thread T0
// CHECK: #0{{.*}}Func2{{.*}}stack-use-after-return.cc:[[@LINE-2]]
// CHECK: is located {{.*}} in frame <{{.*}}Func1{{.*}}> of T0's stack
}
int main(int argc, char **argv) {
Func2(Func1());
return 0;
}
| 32.956522 | 72 | 0.587731 | tylerfox |
f8d8c41e067c94c324edc6afb8a5bbae757d4546 | 890 | cpp | C++ | codeforces/A - Equality/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/A - Equality/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/A - Equality/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Sep/06/2018 21:38
* solution_verdict: Accepted language: GNU C++14
* run_time: 31 ms memory_used: 900 KB
* problem: https://codeforces.com/contest/1038/problem/A
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5;
int mp[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,k;cin>>n>>k;
string s;cin>>s;
for(auto x:s)mp[x-'A']++;
int mn=N+2;
for(int i=0;i<k;i++)
mn=min(mn,mp[i]);
cout<<mn*k<<endl;
return 0;
} | 38.695652 | 111 | 0.373034 | kzvd4729 |
f8dbe8186ab42f40b2659c9a1085957e609a5161 | 384 | hpp | C++ | phylanx/plugins/dist_keras_support/dist_keras_support.hpp | NanmiaoWu/phylanx | 295b5f82cc39925a0d53e77ba3b6d02a65204535 | [
"BSL-1.0"
] | 83 | 2017-08-27T15:09:13.000Z | 2022-01-18T17:03:41.000Z | phylanx/plugins/dist_keras_support/dist_keras_support.hpp | NanmiaoWu/phylanx | 295b5f82cc39925a0d53e77ba3b6d02a65204535 | [
"BSL-1.0"
] | 808 | 2017-08-27T15:35:01.000Z | 2021-12-14T17:30:50.000Z | phylanx/plugins/dist_keras_support/dist_keras_support.hpp | NanmiaoWu/phylanx | 295b5f82cc39925a0d53e77ba3b6d02a65204535 | [
"BSL-1.0"
] | 55 | 2017-08-27T15:09:22.000Z | 2022-03-25T12:07:34.000Z | // Copyright (c) 2020 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(PHYLANX_PLUGINS_DIST_KERAS_SUPPORT_JUN_25_2020)
#define PHYLANX_PLUGINS_DIST_KERAS_SUPPORT_JUN_25_2020
#include <phylanx/plugins/dist_keras_support/dist_conv1d.hpp>
#endif
| 32 | 80 | 0.807292 | NanmiaoWu |
f8df6b8663a88c1d78558888700220fdfad5405d | 712 | cpp | C++ | math/montmort_number_mod/sol/correct.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 290 | 2019-06-06T22:20:36.000Z | 2022-03-27T12:45:04.000Z | math/montmort_number_mod/sol/correct.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 536 | 2019-06-06T18:25:36.000Z | 2022-03-29T11:46:36.000Z | math/montmort_number_mod/sol/correct.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 82 | 2019-06-06T18:17:55.000Z | 2022-03-21T07:40:31.000Z | #include <assert.h>
#include <stdint.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// number of permutations with p_i != i
template<typename T>
struct Montmort{
using ll = long long;
vector<T> dp;
Montmort(int n,int mod):dp(n+1,0){
for(int k=2;k<=n;k++){
dp[k]=(ll)dp[k-1]*k%mod;
if(~k&1) dp[k]+=1;
else dp[k]+=mod-1;
if(dp[k]>=mod) dp[k]-=mod;
}
}
T operator[](int n){return dp[n];}
};
// https://judge.yosupo.jp/problem/montmort_number_mod
int main() {
int N, M;
scanf("%d %d", &N, &M);
Montmort<int> mm(N, M);
for(int i=1;i<=N;i++){
if(i) printf(" ");
printf("%d", mm[i]);
}
printf("\n");
return 0;
}
| 17.365854 | 54 | 0.558989 | tko919 |
25c91f04e321be66d4bfecee0cf70e261ef8d4a2 | 35,656 | cpp | C++ | WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/olesvr2.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/olesvr2.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/olesvr2.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#define new DEBUG_NEW
//////////////////////////////////////////////////////////////////////////////
// COleServerItem implementation
COleServerItem::COleServerItem(COleServerDoc* pServerDoc, BOOL bAutoDelete)
{
if (pServerDoc != NULL)
ASSERT_VALID(pServerDoc);
m_dwRef = 0; // always start in disconnected state
m_bAutoDelete = bAutoDelete;
m_bNeedUnlock = FALSE;
// initially, item does not have an extent
m_sizeExtent.cx = 0;
m_sizeExtent.cy = 0;
// initialize advise holders
m_lpOleAdviseHolder = NULL;
m_lpDataAdviseHolder = NULL;
// add presentation formats to the data source
m_dataSource.m_nGrowBy = 1;
FORMATETC formatEtc;
formatEtc.ptd = NULL;
formatEtc.dwAspect = DVASPECT_CONTENT;
formatEtc.lindex = -1;
// by default, a COleServerItem supports CF_METAFILEPICT
formatEtc.cfFormat = CF_METAFILEPICT;
formatEtc.tymed = TYMED_MFPICT;
m_dataSource.DelayRenderData(0, &formatEtc);
// add item to server document
m_pDocument = NULL;
if (pServerDoc != NULL)
pServerDoc->AddItem(this);
ASSERT(m_pDocument == pServerDoc);
AfxOleLockApp();
}
COleServerItem::~COleServerItem()
{
m_bAutoDelete = FALSE; // no delete during destructor
// release any advise holders
RELEASE(m_lpOleAdviseHolder);
RELEASE(m_lpDataAdviseHolder);
ExternalDisconnect();
// disconnect from the document
COleServerDoc* pDoc = GetDocument();
if (pDoc != NULL)
{
// remove external lock from it
if (m_bNeedUnlock)
{
pDoc->LockExternal(FALSE, TRUE);
m_bNeedUnlock = FALSE;
}
// reset m_pEmbeddedItem if destroying embedded item
if (pDoc->m_pEmbeddedItem == this)
pDoc->m_pEmbeddedItem = NULL;
// remove from list
pDoc->RemoveItem(this);
}
// cleanup any references
AfxOleUnlockApp();
}
BOOL COleServerItem::IsBlank() const
{
// server items are blank in order to keep them from serializing when
// COleDocument::Serialize is called.
return TRUE;
}
BOOL COleServerItem::IsConnected() const
{
// if item is connected in any way, return TRUE
if (m_dwRef != 0)
return TRUE;
// otherwise check if embedded item and document is connected
if (!IsLinkedItem() && GetDocument()->m_lpClientSite != NULL)
return TRUE;
return FALSE; // not connected
}
void COleServerItem::NotifyClient(OLE_NOTIFICATION nCode, DWORD_PTR dwParam)
{
switch (nCode)
{
// IDataObject notifications
case OLE_CHANGED:
if (m_lpDataAdviseHolder != NULL)
m_lpDataAdviseHolder->SendOnDataChange(GetDataObject(), (DWORD)dwParam, 0);
break;
// IOleObject notifications
case OLE_SAVED:
if (m_lpOleAdviseHolder != NULL)
m_lpOleAdviseHolder->SendOnSave();
break;
case OLE_CLOSED:
if (m_lpOleAdviseHolder != NULL)
m_lpOleAdviseHolder->SendOnClose();
break;
case OLE_RENAMED:
if (m_lpOleAdviseHolder != NULL)
{
// Note: the moniker should already be updated for this to work
LPMONIKER lpMoniker = (LPMONIKER)dwParam;
m_lpOleAdviseHolder->SendOnRename(lpMoniker);
}
break;
default:
ASSERT(FALSE);
}
}
/////////////////////////////////////////////////////////////////////////////
// Helpers for getting commonly used interfaces through interface map
LPDATAOBJECT COleServerItem::GetDataObject()
{
LPDATAOBJECT lpDataObject =
(LPDATAOBJECT)GetInterface(&IID_IDataObject);
ASSERT(lpDataObject != NULL);
return lpDataObject;
}
LPOLEOBJECT COleServerItem::GetOleObject()
{
LPOLEOBJECT lpOleObject =
(LPOLEOBJECT)GetInterface(&IID_IOleObject);
ASSERT(lpOleObject != NULL);
return lpOleObject;
}
/////////////////////////////////////////////////////////////////////////////
// COleServerItem overrides
BOOL COleServerItem::OnQueryUpdateItems()
{
COleDocument* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// update all of the embedded objects
POSITION pos = pDoc->GetStartPosition();
COleClientItem* pItem;
while ((pItem = pDoc->GetNextClientItem(pos)) != NULL)
{
// if any item is out-of-date, then this item is out-of-date
if (pItem->m_lpObject->IsUpToDate() != NULL)
return TRUE; // update needed
}
return FALSE; // update not needed
}
void COleServerItem::OnUpdateItems()
{
COleDocument* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// update all of the embedded objects
POSITION pos = pDoc->GetStartPosition();
COleClientItem* pItem;
while ((pItem = pDoc->GetNextClientItem(pos)) != NULL)
{
// update any out-of-date item
if (pItem->m_lpObject->IsUpToDate() != NULL)
pItem->m_lpObject->Update();
}
}
BOOL COleServerItem::OnSetExtent(DVASPECT dwDrawAspect, const CSize& size)
{
ASSERT_VALID(this);
if (dwDrawAspect == DVASPECT_CONTENT)
{
m_sizeExtent = size; // simply remember the extent
return TRUE;
}
return FALSE; // not implemented for that dwDrawAspect
}
BOOL COleServerItem::OnGetExtent(DVASPECT /*dwDrawAspect*/, CSize& rSize)
{
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(&rSize, sizeof(CSize)));
// the default implementation doesn't know what the extent is
rSize.cx = 0;
rSize.cy = 0;
return FALSE;
}
void COleServerItem::OnDoVerb(LONG iVerb)
{
switch (iVerb)
{
// open - maps to OnOpen
case OLEIVERB_OPEN:
case -OLEIVERB_OPEN-1: // allows positive OLEIVERB_OPEN-1 in registry
OnOpen();
break;
// primary, show, and unknown map to OnShow
case OLEIVERB_PRIMARY: // OLEIVERB_PRIMARY is 0 and "Edit" in registry
case OLEIVERB_SHOW:
OnShow();
break;
// hide maps to OnHide
case OLEIVERB_HIDE:
case -OLEIVERB_HIDE-1: // allows positive OLEIVERB_HIDE-1 in registry
OnHide();
break;
default:
// negative verbs not understood should return E_NOTIMPL
if (iVerb < 0)
AfxThrowOleException(E_NOTIMPL);
// positive verb not processed --
// according to OLE spec, primary verb should be executed
// instead.
OnDoVerb(OLEIVERB_PRIMARY);
// also, OLEOBJ_S_INVALIDVERB should be returned.
AfxThrowOleException(OLEOBJ_S_INVALIDVERB);
}
}
BOOL COleServerItem::OnDrawEx(CDC* pDC, DVASPECT nDrawAspect, CSize& rSize)
{
ASSERT_VALID(pDC);
ASSERT(AfxIsValidAddress(&rSize, sizeof(CSize)));
if (nDrawAspect != DVASPECT_CONTENT)
return FALSE;
return OnDraw(pDC, rSize);
}
void COleServerItem::OnShow()
{
ASSERT_VALID(this);
// attempt in place activation (if not supported, fall back on "Open")
COleServerDoc* pDoc = GetDocument();
if (!pDoc->ActivateInPlace())
{
// by default OnShow() maps to OnOpen() if in-place activation
// not supported
OnOpen();
}
}
void COleServerItem::OnOpen()
{
ASSERT_VALID(this);
// default implementation shows the document
COleServerDoc* pDoc = GetDocument();
ASSERT(pDoc != NULL);
pDoc->OnShowDocument(TRUE);
}
void COleServerItem::OnHide()
{
ASSERT_VALID(this);
// default implementation hides the document
COleServerDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
pDoc->OnShowDocument(FALSE);
}
BOOL COleServerItem::GetMetafileData(LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium)
{
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));
ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
ASSERT(lpStgMedium->tymed == TYMED_NULL); // GetDataHere not valid
ASSERT(lpStgMedium->pUnkForRelease == NULL);
// medium must be TYMED_MFPICT -- cannot fill in existing HGLOBAL
if (!(lpFormatEtc->tymed & TYMED_MFPICT) || lpStgMedium->hGlobal != NULL)
return FALSE;
// create appropriate memory metafile DC
CMetaFileDC dc;
if (!dc.Create())
return FALSE;
// create attribute DC according to lpFormatEtc->ptd
HDC hAttribDC = _AfxOleCreateDC(lpFormatEtc->ptd);
if (hAttribDC == NULL)
return FALSE;
dc.SetAttribDC(hAttribDC);
// Paint directly into the metafile.
CSize size(0, 0);
BOOL bResult = OnDrawEx(&dc, (DVASPECT)lpFormatEtc->dwAspect, size);
// attribute DC is no longer necessary
dc.SetAttribDC(NULL);
::DeleteDC(hAttribDC);
if (!bResult)
{
TRACE(traceOle, 1, "calling COleServerItem::OnDrawEx()failed.\n");
return FALSE;
}
HMETAFILE hMF = dc.Close();
if (hMF == NULL)
return FALSE;
HGLOBAL hPict;
if ((hPict =
::GlobalAlloc(GMEM_SHARE|GMEM_MOVEABLE, sizeof(METAFILEPICT))) == NULL)
{
DeleteMetaFile(hMF);
return FALSE;
}
LPMETAFILEPICT lpPict;
if ((lpPict = (LPMETAFILEPICT)::GlobalLock(hPict)) == NULL)
{
DeleteMetaFile(hMF);
::GlobalFree(hPict);
return FALSE;
}
// set the metafile size
lpPict->mm = MM_ANISOTROPIC;
lpPict->hMF = hMF;
if (size.cx == 0 && size.cy == 0 &&
!OnGetExtent((DVASPECT)lpFormatEtc->dwAspect, size))
{
TRACE(traceOle, 0, "Warning: OnGetExtent failed during OnDrawEx --\n");
TRACE(traceOle, 0, "\tpresentation metafile may be badly formed!\n");
}
lpPict->xExt = size.cx;
lpPict->yExt = size.cy; // HIMETRIC height
if (lpPict->yExt < 0)
{
TRACE(traceOle, 0, "Warning: HIMETRIC natural size is negative.\n");
lpPict->yExt = -lpPict->yExt; // backward compatibility fix
}
#ifdef _DEBUG
if (lpPict->xExt == 0 || lpPict->yExt == 0)
{
// usually the natural extent is set to something interesting
TRACE(traceOle, 0, "Warning: COleServerItem has no natural size --\n");
TRACE(traceOle, 0, "\twill not work with some apps like MS Write.\n");
}
#endif
// return the medium with the hGlobal to the METAFILEPICT
::GlobalUnlock(hPict);
lpStgMedium->hGlobal = hPict;
lpStgMedium->tymed = TYMED_MFPICT;
return TRUE;
}
BOOL COleServerItem::OnSetColorScheme(const LOGPALETTE* /*lpLogPalette*/)
{
ASSERT_VALID(this);
return FALSE; // default does nothing
}
BOOL COleServerItem::OnInitFromData(
COleDataObject* /*pDataObject*/, BOOL /*bCreation*/)
{
ASSERT_VALID(this);
AfxThrowOleException(E_NOTIMPL);
}
void COleServerItem::CopyToClipboard(BOOL bIncludeLink)
{
ASSERT_VALID(this);
COleDataSource* pDataSource = OnGetClipboardData(bIncludeLink, NULL, NULL);
// put it on the clipboard
pDataSource->SetClipboard();
}
COleDataSource* COleServerItem::OnGetClipboardData(BOOL bIncludeLink,
LPPOINT lpOffset, LPSIZE lpSize)
{
ASSERT_VALID(this);
COleDataSource* pDataSource = new COleDataSource;
TRY
{
GetClipboardData(pDataSource, bIncludeLink, lpOffset, lpSize);
}
CATCH_ALL(e)
{
delete pDataSource;
THROW_LAST();
}
END_CATCH_ALL
ASSERT_VALID(pDataSource);
return pDataSource;
}
DROPEFFECT COleServerItem::DoDragDrop(LPCRECT lpItemRect, CPoint ptOffset,
BOOL bIncludeLink, DWORD dwEffects, LPCRECT lpRectStartDrag)
{
ASSERT(AfxIsValidAddress(lpItemRect, sizeof(RECT)));
ASSERT_VALID(this);
ASSERT_VALID(this);
DROPEFFECT dropEffect = DROPEFFECT_NONE;
COleDataSource *pDataSource = NULL;
TRY
{
// get clipboard data for this item
CSize sizeItem(
lpItemRect->right - lpItemRect->left,
lpItemRect->bottom - lpItemRect->top);
pDataSource = OnGetClipboardData(bIncludeLink, &ptOffset, &sizeItem);
// add DROPEFFECT_LINK if link source is available
LPDATAOBJECT lpDataObject = (LPDATAOBJECT)
pDataSource->GetInterface(&IID_IDataObject);
ASSERT(lpDataObject != NULL);
FORMATETC formatEtc;
formatEtc.cfFormat = (CLIPFORMAT)_oleData.cfLinkSource;
formatEtc.ptd = NULL;
formatEtc.dwAspect = DVASPECT_CONTENT;
formatEtc.lindex = -1;
formatEtc.tymed = (DWORD) -1;
if (lpDataObject->QueryGetData(&formatEtc) == S_OK)
dwEffects |= DROPEFFECT_LINK;
// calculate default sensitivity rectangle
CRect rectDrag;
if (lpRectStartDrag == NULL)
{
rectDrag.SetRect(lpItemRect->left, lpItemRect->top, lpItemRect->left,
lpItemRect->top);
lpRectStartDrag = &rectDrag;
}
// do drag drop operation
dropEffect = pDataSource->DoDragDrop(dwEffects, lpRectStartDrag);
pDataSource->InternalRelease();
}
CATCH_ALL(e)
{
if (pDataSource != NULL)
pDataSource->InternalRelease();
THROW_LAST();
}
END_CATCH_ALL
return dropEffect;
}
void COleServerItem::GetClipboardData(COleDataSource* pDataSource,
BOOL bIncludeLink, LPPOINT lpOffset, LPSIZE lpSize)
{
ASSERT_VALID(this);
ASSERT_VALID(pDataSource);
ASSERT(lpOffset == NULL ||
AfxIsValidAddress(lpOffset, sizeof(POINT), FALSE));
// add CF_EMBEDDEDOBJECT by creating memory storage copy of the object
STGMEDIUM stgMedium;
GetEmbedSourceData(&stgMedium);
pDataSource->CacheData((CLIPFORMAT)_oleData.cfEmbedSource, &stgMedium);
// add CF_OBJECTDESCRIPTOR
GetObjectDescriptorData(lpOffset, lpSize, &stgMedium);
pDataSource->CacheData((CLIPFORMAT)_oleData.cfObjectDescriptor,
&stgMedium);
// add any presentation entries/conversion formats that the item
// can produce.
AddOtherClipboardData(pDataSource);
// add CF_LINKSOURCE if supporting links to pseudo objects
if (bIncludeLink && GetLinkSourceData(&stgMedium))
{
pDataSource->CacheData((CLIPFORMAT)_oleData.cfLinkSource, &stgMedium);
// add CF_LINKSOURCEDESCRIPTOR
GetObjectDescriptorData(lpOffset, lpSize, &stgMedium);
pDataSource->CacheData((CLIPFORMAT)_oleData.cfLinkSourceDescriptor,
&stgMedium);
}
}
void COleServerItem::GetEmbedSourceData(LPSTGMEDIUM lpStgMedium)
{
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
LPLOCKBYTES lpLockBytes;
SCODE sc = ::CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes);
if (sc != S_OK)
AfxThrowOleException(sc);
ASSERT(lpLockBytes != NULL);
LPSTORAGE lpStorage;
sc = ::StgCreateDocfileOnILockBytes(lpLockBytes,
STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0, &lpStorage);
if (sc != S_OK)
{
VERIFY(lpLockBytes->Release() == 0);
AfxThrowOleException(sc);
}
ASSERT(lpStorage != NULL);
// setup for save copy as
COleServerDoc* pDoc = GetDocument();
pDoc->m_bSameAsLoad = FALSE;
pDoc->m_bRemember = FALSE;
TRY
{
OnSaveEmbedding(lpStorage);
pDoc->CommitItems(FALSE);
}
CATCH_ALL(e)
{
// release storage and lock bytes
VERIFY(lpStorage->Release() == 0);
VERIFY(lpLockBytes->Release() == 0);
pDoc->m_bSameAsLoad = TRUE;
pDoc->m_bRemember = TRUE;
THROW_LAST();
}
END_CATCH_ALL
pDoc->m_bSameAsLoad = TRUE;
pDoc->m_bRemember = TRUE;
lpLockBytes->Release();
// add it to the data source
lpStgMedium->tymed = TYMED_ISTORAGE;
lpStgMedium->pstg = lpStorage;
lpStgMedium->pUnkForRelease = NULL;
}
void COleServerItem::AddOtherClipboardData(COleDataSource* pDataSource)
{
ASSERT_VALID(this);
ASSERT_VALID(pDataSource);
// get IEnumFORMATETC interface for the IDataObject
LPDATAOBJECT lpDataObject = GetDataObject();
LPENUMFORMATETC lpEnumFORMATETC;
if (lpDataObject->EnumFormatEtc(DATADIR_GET, &lpEnumFORMATETC) != S_OK)
return;
ASSERT(lpEnumFORMATETC != NULL);
// get all formats that the object will give us
FORMATETC formatEtc;
while (lpEnumFORMATETC->Next(1, &formatEtc, NULL) == S_OK)
{
STGMEDIUM stgMedium;
if (lpDataObject->GetData(&formatEtc, &stgMedium) != S_OK)
{
// data is not available
CoTaskMemFree(formatEtc.ptd);
}
else if (stgMedium.pUnkForRelease != NULL)
{
// don't cache data with pUnkForRelease != NULL
::ReleaseStgMedium(&stgMedium);
CoTaskMemFree(formatEtc.ptd);
}
else
{
// cache the data (now we own the stgMedium)
pDataSource->CacheData(0, &stgMedium, &formatEtc);
}
}
// cleanup
lpEnumFORMATETC->Release();
}
LPMONIKER COleServerItem::GetMoniker(OLEGETMONIKER nAssign)
{
// get IOleObject interface for this item
LPOLEOBJECT lpOleObject = GetOleObject();
ASSERT(lpOleObject != NULL);
// get moniker from OLE object
LPMONIKER lpMoniker = NULL;
lpOleObject->GetMoniker(nAssign, OLEWHICHMK_OBJFULL, &lpMoniker);
return lpMoniker;
}
BOOL COleServerItem::GetLinkSourceData(LPSTGMEDIUM lpStgMedium)
{
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
LPOLEOBJECT lpOleObject = GetOleObject();
ASSERT(lpOleObject != NULL);
// get moniker from ole object
LPMONIKER lpMoniker;
SCODE sc = lpOleObject->GetMoniker(OLEGETMONIKER_TEMPFORUSER,
OLEWHICHMK_OBJFULL, &lpMoniker);
if (sc != S_OK)
{
TRACE(traceOle, 0, "Warning: unable to get moniker for object.\n");
return FALSE;
}
ASSERT(lpMoniker != NULL);
// create a memory based stream to write the moniker to
LPSTREAM lpStream;
if (::CreateStreamOnHGlobal(NULL, TRUE, &lpStream) != S_OK)
{
lpMoniker->Release();
AfxThrowMemoryException();
}
ASSERT(lpStream != NULL);
// write the moniker to the stream, and add it to the clipboard
sc = ::OleSaveToStream(lpMoniker, lpStream);
lpMoniker->Release();
if (sc != S_OK)
{
lpStream->Release();
AfxThrowOleException(sc);
}
// write the class ID of the document to the stream as well
COleLinkingDoc* pDoc = GetDocument();
ASSERT(pDoc->m_pFactory != NULL);
sc = WriteClassStm(lpStream, pDoc->m_pFactory->GetClassID());
if (sc != S_OK)
{
lpStream->Release();
AfxThrowOleException(sc);
}
// setup the STGMEDIUM
lpStgMedium->tymed = TYMED_ISTREAM;
lpStgMedium->pstm = lpStream;
lpStgMedium->pUnkForRelease = NULL;
return TRUE;
}
void COleServerItem::GetObjectDescriptorData(
LPPOINT lpOffset, LPSIZE lpSize, LPSTGMEDIUM lpStgMedium)
{
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
ASSERT(lpOffset == NULL ||
AfxIsValidAddress(lpOffset, sizeof(POINT), FALSE));
LPOLEOBJECT lpOleObject = GetOleObject();
ASSERT(lpOleObject != NULL);
// get the object descriptor for the IOleObject
POINTL pointl = { 0, 0 };
if (lpOffset != NULL)
{
CSize ptOffset(lpOffset->x, lpOffset->y);
((CDC*)NULL)->DPtoHIMETRIC(&ptOffset);
pointl.x = ptOffset.cx;
pointl.y = ptOffset.cy;
}
SIZEL sizel;
if (lpSize != NULL)
{
sizel.cx = lpSize->cx;
sizel.cy = lpSize->cy;
((CDC*)NULL)->DPtoHIMETRIC(&sizel);
}
else
{
sizel.cx = 0;
sizel.cy = 0;
}
InterlockedIncrement(&m_dwRef); // protect against destruction during this call
HGLOBAL hGlobal = _AfxOleGetObjectDescriptorData(
lpOleObject, NULL, DVASPECT_CONTENT, pointl, &sizel);
InterlockedDecrement(&m_dwRef);
if (hGlobal == NULL)
AfxThrowMemoryException();
// setup the STGMEDIUM
lpStgMedium->tymed = TYMED_HGLOBAL;
lpStgMedium->hGlobal = hGlobal;
lpStgMedium->pUnkForRelease = NULL;
}
void COleServerItem::OnSaveEmbedding(LPSTORAGE lpStorage)
{
ASSERT(lpStorage != NULL);
// always (logically) a "File.Save Copy As" operation
COleServerDoc* pDoc = GetDocument();
LPSTORAGE lpOrigStg = pDoc->m_lpRootStg;
pDoc->m_lpRootStg = lpStorage;
TRY
{
ASSERT(pDoc->m_lpRootStg != NULL);
pDoc->SaveToStorage(this); // use helper to serialize to storage
}
CATCH_ALL(e)
{
// save as failed: re-attach original storage
pDoc->m_lpRootStg = lpOrigStg;
THROW_LAST();
}
END_CATCH_ALL
// re-attach original storage
pDoc->m_lpRootStg = lpOrigStg;
}
/////////////////////////////////////////////////////////////////////////////
// COleServerItem data-object callback default implementation
BOOL COleServerItem::OnRenderGlobalData(
LPFORMATETC /*lpFormatEtc*/, HGLOBAL* /*phGlobal*/)
{
ASSERT_VALID(this);
return FALSE; // default does nothing
}
BOOL COleServerItem::OnRenderFileData(
LPFORMATETC /*lpFormatEtc*/, CFile* /*pFile*/)
{
ASSERT_VALID(this);
return FALSE; // default does nothing
}
BOOL COleServerItem::OnRenderData(LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium)
{
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));
ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
// default implementation does not support extended layout
if (lpFormatEtc->lindex != -1)
return FALSE;
// default implementation supports both types of metafiles
if (lpFormatEtc->cfFormat == CF_METAFILEPICT)
return GetMetafileData(lpFormatEtc, lpStgMedium);
return FALSE; // cfFormat not supported
}
BOOL COleServerItem::OnSetData(
LPFORMATETC /*lpFormatEtc*/, LPSTGMEDIUM /*lpStgMedium*/, BOOL /*bRelease*/)
{
ASSERT_VALID(this);
return FALSE; // default does nothing
}
/////////////////////////////////////////////////////////////////////////////
// COleServerItem OLE interface implementation
BEGIN_INTERFACE_MAP(COleServerItem, CDocItem)
INTERFACE_PART(COleServerItem, IID_IOleObject, OleObject)
INTERFACE_PART(COleServerItem, IID_IDataObject, DataObject)
END_INTERFACE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COleServerItem::XOleObject
STDMETHODIMP_(ULONG) COleServerItem::XOleObject::AddRef()
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleServerItem::XOleObject::Release()
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
return pThis->ExternalRelease();
}
STDMETHODIMP COleServerItem::XOleObject::QueryInterface(
REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
// COleServerItem has special Release semantics. In particular, the item
// is only deleted from memory if m_bAutoDelete is TRUE.
// Also, it unlocks the document if the reference count reaches zero.
void COleServerItem::OnFinalRelease()
{
ASSERT_VALID(this);
COleServerDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
pDoc->InternalAddRef(); // make document stable
// if connected to a document -- remove external lock from it
if (m_bNeedUnlock)
{
pDoc->LockExternal(FALSE, TRUE);
m_bNeedUnlock = FALSE;
}
// delete this item if no longer needed
if (m_bAutoDelete)
delete this;
// release artificial reference (may destroy the document)
pDoc->InternalRelease();
}
STDMETHODIMP COleServerItem::XOleObject::SetClientSite(
LPOLECLIENTSITE /*pClientSite*/)
{
// linked objects do not support SetClientSite
return E_NOTIMPL;
}
STDMETHODIMP COleServerItem::XOleObject::GetClientSite(
LPOLECLIENTSITE* ppClientSite)
{
// linked objects do not support GetClientSite
*ppClientSite = NULL;
return E_NOTIMPL;
}
STDMETHODIMP COleServerItem::XOleObject::SetHostNames(
LPCOLESTR /*szContainerApp*/, LPCOLESTR /*szContainerObj*/)
{
// linked objects do not support SetHostNames
return E_NOTIMPL;
}
STDMETHODIMP COleServerItem::XOleObject::Close(DWORD /*dwSaveOption*/)
{
// linked objects do not support close
return E_NOTIMPL;
}
STDMETHODIMP COleServerItem::XOleObject::SetMoniker(
DWORD /*dwWhichMoniker*/, LPMONIKER /*pmk*/)
{
// linked objects do not support SetMoniker
return E_NOTIMPL;
}
STDMETHODIMP COleServerItem::XOleObject::GetMoniker(
DWORD dwAssign, DWORD dwWhichMoniker, LPMONIKER* ppMoniker)
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
COleServerDoc* pDoc = pThis->GetDocument();
ASSERT_VALID(pDoc);
ASSERT_KINDOF(COleServerDoc, pDoc);
ASSERT(ppMoniker != NULL);
*ppMoniker = NULL;
switch (dwWhichMoniker)
{
case OLEWHICHMK_CONTAINER:
// simply return the moniker of the container document
*ppMoniker = pDoc->GetMoniker((OLEGETMONIKER)dwAssign);
break;
case OLEWHICHMK_OBJREL:
{
// no relative moniker if no item name
if (pThis->m_strItemName.IsEmpty())
break;
// don't return relative moniker if no document moniker
LPMONIKER lpMoniker = pDoc->GetMoniker((OLEGETMONIKER)dwAssign);
if (lpMoniker == NULL)
break;
lpMoniker->Release(); // don't need document moniker
// relative monikers have to handle assignment correctly
switch (dwAssign)
{
case OLEGETMONIKER_TEMPFORUSER:
case OLEGETMONIKER_ONLYIFTHERE:
case OLEGETMONIKER_FORCEASSIGN:
{
// create item moniker from name
const CStringW strItemName(pThis->m_strItemName);
CreateItemMoniker(OLESTDDELIMOLE, strItemName.GetString(),
ppMoniker);
break;
}
case OLEGETMONIKER_UNASSIGN:
ASSERT(FALSE); // should never get UNASSIGN
break;
}
}
break;
case OLEWHICHMK_OBJFULL:
{
// get each sub-moniker: item & document
LPMONIKER lpMoniker1, lpMoniker2;
GetMoniker(dwAssign, OLEWHICHMK_CONTAINER, &lpMoniker1);
GetMoniker(dwAssign, OLEWHICHMK_OBJREL, &lpMoniker2);
if (lpMoniker1 != NULL && lpMoniker2 != NULL)
{
// create composite from two parts
::CreateGenericComposite(lpMoniker1, lpMoniker2, ppMoniker);
}
else if (lpMoniker1 != NULL)
{
// just use container moniker
*ppMoniker = lpMoniker1;
lpMoniker1 = NULL;
}
// release sub-monikers
RELEASE(lpMoniker1);
RELEASE(lpMoniker2);
}
break;
}
return *ppMoniker == NULL ? E_FAIL : S_OK;
}
STDMETHODIMP COleServerItem::XOleObject::InitFromData(
LPDATAOBJECT /*pDataObject*/, BOOL /*fCreation*/, DWORD /*dwReserved*/)
{
// linked objects do not support InitFromData
return E_NOTIMPL;
}
STDMETHODIMP COleServerItem::XOleObject::GetClipboardData(
DWORD /*dwReserved*/, LPDATAOBJECT* ppDataObject)
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
*ppDataObject = NULL;
SCODE sc;
TRY
{
COleDataSource* pDataSource = pThis->OnGetClipboardData(TRUE, NULL, NULL);
ASSERT(pDataSource != NULL);
*ppDataObject =
(LPDATAOBJECT)pDataSource->GetInterface(&IID_IDataObject);
ASSERT(*ppDataObject != NULL);
sc = S_OK;
}
CATCH_ALL(e)
{
sc = COleException::Process(e);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
return sc;
}
STDMETHODIMP COleServerItem::XOleObject::DoVerb(
LONG iVerb, LPMSG /*lpmsg*/, LPOLECLIENTSITE /*pActiveSite*/, LONG /*lindex*/,
HWND /*hwndParent*/, LPCRECT /*lpPosRect*/)
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
pThis->InternalAddRef(); // protect this object
SCODE sc;
TRY
{
pThis->OnDoVerb(iVerb);
sc = S_OK;
}
CATCH_ALL(e)
{
sc = COleException::Process(e);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
pThis->InternalRelease(); // may 'delete this'
return sc;
}
STDMETHODIMP COleServerItem::XOleObject::EnumVerbs(
IEnumOLEVERB** ppenumOleVerb)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
*ppenumOleVerb = NULL;
CLSID clsid;
pThis->GetOleObject()->GetUserClassID(&clsid);
return OleRegEnumVerbs(clsid, ppenumOleVerb);
}
STDMETHODIMP COleServerItem::XOleObject::Update()
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
SCODE sc;
TRY
{
pThis->OnUpdateItems();
sc = S_OK;
}
CATCH_ALL(e)
{
sc = COleException::Process(e);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
return sc;
}
STDMETHODIMP COleServerItem::XOleObject::IsUpToDate()
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
SCODE sc;
TRY
{
sc = pThis->OnQueryUpdateItems() ? S_FALSE : S_OK;
}
CATCH_ALL(e)
{
sc = COleException::Process(e);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
return sc;
}
STDMETHODIMP COleServerItem::XOleObject::GetUserClassID(CLSID* pClsid)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
COleServerDoc* pDoc = pThis->GetDocument();
return pDoc->m_xPersistFile.GetClassID(pClsid);
}
STDMETHODIMP COleServerItem::XOleObject::GetUserType(
DWORD dwFormOfType, LPOLESTR* ppszUserType)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
*ppszUserType = NULL;
CLSID clsid;
pThis->GetOleObject()->GetUserClassID(&clsid);
return OleRegGetUserType(clsid, dwFormOfType, ppszUserType);
}
STDMETHODIMP COleServerItem::XOleObject::SetExtent(
DWORD /*dwDrawAspect*/, LPSIZEL /*lpsizel*/)
{
// linked objects do not support SetExtent
return E_FAIL;
}
STDMETHODIMP COleServerItem::XOleObject::GetExtent(
DWORD dwDrawAspect, LPSIZEL lpsizel)
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
SCODE sc = E_INVALIDARG;
TRY
{
// call to get regular windows size
CSize size;
if (pThis->OnGetExtent((DVASPECT)dwDrawAspect, size))
{
if (size.cy < 0)
size.cy = -size.cy; // extents are always positive
lpsizel->cx = size.cx;
lpsizel->cy = size.cy;
sc = S_OK;
}
}
CATCH_ALL(e)
{
sc = COleException::Process(e);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
return sc;
}
STDMETHODIMP COleServerItem::XOleObject::Advise(
IAdviseSink* pAdvSink, DWORD* pdwConnection)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
*pdwConnection = 0;
if (pThis->m_lpOleAdviseHolder == NULL &&
::CreateOleAdviseHolder(&pThis->m_lpOleAdviseHolder) != S_OK)
{
return E_OUTOFMEMORY;
}
ASSERT(pThis->m_lpOleAdviseHolder != NULL);
return pThis->m_lpOleAdviseHolder->Advise(pAdvSink, pdwConnection);
}
STDMETHODIMP COleServerItem::XOleObject::Unadvise(DWORD dwConnection)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
if (pThis->m_lpOleAdviseHolder == NULL)
return E_FAIL;
ASSERT(pThis->m_lpOleAdviseHolder != NULL);
return pThis->m_lpOleAdviseHolder->Unadvise(dwConnection);
}
STDMETHODIMP COleServerItem::XOleObject::EnumAdvise(
LPENUMSTATDATA* ppenumAdvise)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
*ppenumAdvise = NULL;
if (pThis->m_lpOleAdviseHolder == NULL)
return E_FAIL;
ASSERT(pThis->m_lpOleAdviseHolder != NULL);
return pThis->m_lpOleAdviseHolder->EnumAdvise(ppenumAdvise);
}
STDMETHODIMP COleServerItem::XOleObject::GetMiscStatus(
DWORD dwAspect, DWORD* pdwStatus)
{
METHOD_PROLOGUE_EX_(COleServerItem, OleObject)
*pdwStatus = 0;
CLSID clsid;
pThis->GetOleObject()->GetUserClassID(&clsid);
return OleRegGetMiscStatus(clsid, dwAspect, pdwStatus);
}
STDMETHODIMP COleServerItem::XOleObject::SetColorScheme(LPLOGPALETTE lpLogpal)
{
METHOD_PROLOGUE_EX(COleServerItem, OleObject)
ASSERT_VALID(pThis);
SCODE sc = E_NOTIMPL;
TRY
{
// delegate to embedded item
if (pThis->OnSetColorScheme(lpLogpal))
sc = S_OK;
}
END_TRY
return sc;
}
/////////////////////////////////////////////////////////////////////////////
// COleServerItem::XDataObject
STDMETHODIMP_(ULONG) COleServerItem::XDataObject::AddRef()
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleServerItem::XDataObject::Release()
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->ExternalRelease();
}
STDMETHODIMP COleServerItem::XDataObject::QueryInterface(
REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleServerItem::XDataObject::GetData(
LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->m_dataSource.m_xDataObject.GetData(lpFormatEtc, lpStgMedium);
}
STDMETHODIMP COleServerItem::XDataObject::GetDataHere(
LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->m_dataSource.m_xDataObject.GetDataHere(
lpFormatEtc, lpStgMedium);
}
STDMETHODIMP COleServerItem::XDataObject::QueryGetData(LPFORMATETC lpFormatEtc)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->m_dataSource.m_xDataObject.QueryGetData(lpFormatEtc);
}
STDMETHODIMP COleServerItem::XDataObject::GetCanonicalFormatEtc(
LPFORMATETC /*lpFormatEtcIn*/, LPFORMATETC /*lpFormatEtcOut*/)
{
// because we support the target-device (ptd) for server metafile format,
// all members of the FORMATETC are significant.
return DATA_S_SAMEFORMATETC;
}
STDMETHODIMP COleServerItem::XDataObject::SetData(
LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium, BOOL bRelease)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->m_dataSource.m_xDataObject.SetData(
lpFormatEtc, lpStgMedium, bRelease);
}
STDMETHODIMP COleServerItem::XDataObject::EnumFormatEtc(
DWORD dwDirection, LPENUMFORMATETC* ppenumFormatEtc)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
return pThis->m_dataSource.m_xDataObject.EnumFormatEtc(
dwDirection, ppenumFormatEtc);
}
STDMETHODIMP COleServerItem::XDataObject::DAdvise(
FORMATETC* pFormatEtc, DWORD advf,
LPADVISESINK pAdvSink, DWORD* pdwConnection)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
*pdwConnection = 0;
// this special case is for apps like Excel which ask for DAdvise
// on CF_METAFILEPICT, DVASPECT_ICON for insert as icon.
FORMATETC formatEtc = *pFormatEtc;
if (formatEtc.cfFormat == CF_METAFILEPICT &&
formatEtc.dwAspect == DVASPECT_ICON)
{
formatEtc.dwAspect = DVASPECT_CONTENT;
}
// make sure the FORMATETC is valid
if (!(pFormatEtc->cfFormat == 0 && pFormatEtc->ptd == NULL &&
pFormatEtc->dwAspect == -1 && pFormatEtc->lindex == -1 &&
pFormatEtc->tymed == -1) &&
pThis->GetDataObject()->QueryGetData(&formatEtc) != S_OK)
{
// it is not a wildcard advise -and- the format is not acceptable
return DATA_E_FORMATETC;
}
// create the advise holder, if necessary
if (pThis->m_lpDataAdviseHolder == NULL &&
CreateDataAdviseHolder(&pThis->m_lpDataAdviseHolder) != S_OK)
{
return E_OUTOFMEMORY;
}
ASSERT(pThis->m_lpDataAdviseHolder != NULL);
return pThis->m_lpDataAdviseHolder->Advise(this, pFormatEtc, advf,
pAdvSink, pdwConnection);
}
STDMETHODIMP COleServerItem::XDataObject::DUnadvise(DWORD dwConnection)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
if (pThis->m_lpDataAdviseHolder == NULL)
return E_FAIL;
ASSERT(pThis->m_lpDataAdviseHolder != NULL);
return pThis->m_lpDataAdviseHolder->Unadvise(dwConnection);
}
STDMETHODIMP COleServerItem::XDataObject::EnumDAdvise(
LPENUMSTATDATA* ppenumAdvise)
{
METHOD_PROLOGUE_EX_(COleServerItem, DataObject)
*ppenumAdvise = NULL;
if (pThis->m_lpDataAdviseHolder == NULL)
return E_FAIL;
ASSERT(pThis->m_lpDataAdviseHolder != NULL);
return pThis->m_lpDataAdviseHolder->EnumAdvise(ppenumAdvise);
}
//////////////////////////////////////////////////////////////////////////////
// special CItemDataSource implementation
BOOL COleServerItem::CItemDataSource::OnRenderGlobalData(
LPFORMATETC lpFormatEtc, HGLOBAL* phGlobal)
{
ASSERT_VALID(this);
COleServerItem* pItem = (COleServerItem*)
((BYTE*)this - offsetof(COleServerItem, m_dataSource));
return pItem->OnRenderGlobalData(lpFormatEtc, phGlobal);
// Note: COleDataSource has no implementation
}
BOOL COleServerItem::CItemDataSource::OnRenderFileData(
LPFORMATETC lpFormatEtc, CFile* pFile)
{
ASSERT_VALID(this);
COleServerItem* pItem = (COleServerItem*)
((BYTE*)this - offsetof(COleServerItem, m_dataSource));
return pItem->OnRenderFileData(lpFormatEtc, pFile);
// Note: COleDataSource has no implementation
}
BOOL COleServerItem::CItemDataSource::OnRenderData(
LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium)
{
ASSERT_VALID(this);
COleServerItem* pItem = (COleServerItem*)
((BYTE*)this - offsetof(COleServerItem, m_dataSource));
if (pItem->OnRenderData(lpFormatEtc, lpStgMedium))
return TRUE;
return COleDataSource::OnRenderData(lpFormatEtc, lpStgMedium);
}
BOOL COleServerItem::CItemDataSource::OnSetData(
LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium, BOOL bRelease)
{
ASSERT_VALID(this);
COleServerItem* pItem = (COleServerItem*)
((BYTE*)this - offsetof(COleServerItem, m_dataSource));
return pItem->OnSetData(lpFormatEtc, lpStgMedium, bRelease);
// Note: COleDataSource has no implementation
}
//////////////////////////////////////////////////////////////////////////////
// COleServerItem Diagnostics
#ifdef _DEBUG
void COleServerItem::AssertValid() const
{
CDocItem::AssertValid();
// must be attached to a document
ASSERT(m_pDocument != NULL);
m_dataSource.AssertValid();
}
void COleServerItem::Dump(CDumpContext& dc) const
{
CDocItem::Dump(dc);
dc << "m_bNeedUnlock = " << m_bNeedUnlock;
dc << "\nm_bAutoDelete = " << m_bAutoDelete;
dc << "\nm_strItemName = " << m_strItemName;
dc << "\nm_lpOleAdviseHolder = " << m_lpOleAdviseHolder;
dc << "\nm_lpDataAdviseHolder = " << m_lpDataAdviseHolder;
dc << "\nwith m_dataSource: " << &m_dataSource;
}
#endif
/////////////////////////////////////////////////////////////////////////////
| 24.709633 | 86 | 0.727704 | intj-t |
25dc384092633652732e3f72e87a55219981ed10 | 1,664 | cc | C++ | src/leveldb/util/hash_test.cc | yinchengtsinghua/BitCoinCppChinese | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | [
"MIT"
] | 13 | 2019-01-23T04:36:05.000Z | 2022-02-21T11:20:25.000Z | src/leveldb/util/hash_test.cc | yinchengtsinghua/BitCoinCppChinese | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | [
"MIT"
] | null | null | null | src/leveldb/util/hash_test.cc | yinchengtsinghua/BitCoinCppChinese | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | [
"MIT"
] | 3 | 2019-01-24T07:48:15.000Z | 2021-06-11T13:34:44.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2011 LevelDB作者。版权所有。
//此源代码的使用受可以
//在许可证文件中找到。有关参与者的名称,请参阅作者文件。
#include "util/hash.h"
#include "util/testharness.h"
namespace leveldb {
class HASH { };
TEST(HASH, SignedUnsignedIssue) {
const unsigned char data1[1] = {0x62};
const unsigned char data2[2] = {0xc3, 0x97};
const unsigned char data3[3] = {0xe2, 0x99, 0xa5};
const unsigned char data4[4] = {0xe1, 0x80, 0xb9, 0x32};
const unsigned char data5[48] = {
0x01, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x18,
0x28, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
ASSERT_EQ(Hash(0, 0, 0xbc9f1d34), 0xbc9f1d34);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data1), sizeof(data1), 0xbc9f1d34),
0xef1345c4);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data2), sizeof(data2), 0xbc9f1d34),
0x5b663814);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data3), sizeof(data3), 0xbc9f1d34),
0x323c078f);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data4), sizeof(data4), 0xbc9f1d34),
0xed21633a);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data5), sizeof(data5), 0x12345678),
0xf333dabb);
}
} //命名空间级别数据库
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
| 26.412698 | 76 | 0.673077 | yinchengtsinghua |
25e011f1d71e5331ac58d00912a4c8e9bc7528cc | 925 | cpp | C++ | LeetCodeCPP/335. Self Crossing/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | 1 | 2019-03-29T03:33:56.000Z | 2019-03-29T03:33:56.000Z | LeetCodeCPP/335. Self Crossing/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | LeetCodeCPP/335. Self Crossing/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// 335. Self Crossing
//
// Created by admin on 2019/8/14.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool isSelfCrossing(vector<int>& x) {
int m=x.size();
if(m<4){
return false;
}
for(int i=3;i<m;i++){
if(x[i]>=x[i-2] && x[i-1]<=x[i-3]) return true;
if(i>=4){
if(x[i-1]==x[i-3] && x[i-2]<=x[i]+x[i-4]) return true;
}
if(i>=5){
if(x[i-2]>=x[i-4] && x[i]>=x[i-2]-x[i-4] && x[i-1]>=x[i-3]-x[i-5] && x[i-1]<=x[i-3]) return true;
}
}
return false;
}
};
int main(int argc, const char * argv[]) {
vector<int> input={2,1,1,2};
Solution so=Solution();
bool ret=so.isSelfCrossing(input);
cout<<"The ret is:"<<ret<<endl;
return 0;
}
| 22.560976 | 113 | 0.467027 | 18600130137 |
25e03d19de061ef015ec92b1441873c45a49cc7f | 1,479 | cpp | C++ | examples/basic/main.cpp | igagis/stdjson | 2db77b24d0ee941086e9871333127e058034dd7a | [
"MIT"
] | 1 | 2021-06-17T13:39:50.000Z | 2021-06-17T13:39:50.000Z | examples/basic/main.cpp | igagis/stdjson | 2db77b24d0ee941086e9871333127e058034dd7a | [
"MIT"
] | null | null | null | examples/basic/main.cpp | igagis/stdjson | 2db77b24d0ee941086e9871333127e058034dd7a | [
"MIT"
] | 1 | 2020-12-15T01:48:43.000Z | 2020-12-15T01:48:43.000Z | #include <iostream>
#include <cassert>
#include <jsondom/dom.hpp>
#include <utki/debug.hpp>
const char* json = R"qwertyuiop(
{
"key1": "value1",
"key2": "value2"
}
)qwertyuiop";
int main(int c, const char** v){
// parse the JSON to DOM
auto dom = jsondom::read(json);
// check that root node is a JSON object, just to be sure
utki::assert(dom.is_object(), SL);
// let's check if there is an expected key1-value1 pair,
// but do not fail if there is no such key or value is not of an expected type
auto value1_i = dom.object().find("key1");
if(value1_i != dom.object().end()){
auto& value1 = value1_i->second;
if(value1.is_string()){
std::cout << "value1 = " << value1.string() << std::endl;
}else{
// this never happens in this example, but just to show how
// to handle cases when JSON value type is not as expected
std::cout << "value1 is not a string" << std::endl;
}
}else{
// this never happens in this example, but just to show how
// to handle cases when JSON key is not found
std::cout << "key1 is not found" << std::endl;
}
// Try to use key2-value2 pair, relying on that it exists.
// An exception will be thrown if something goes wrong, like
// no 'key2' key is found or value is of unexpected type.
try{
std::cout << "value2 = " << dom.object().at("key2").string() << std::endl;
}catch(std::logic_error& e){
// handle exception here if needed
std::cout << e.what() << std::endl;
throw;
}
return 0;
}
| 26.890909 | 79 | 0.650439 | igagis |
25e4f3a861ed66ad20a050f325957b3c46e85b4e | 201 | hpp | C++ | src/reyes/config.hpp | cwbaker/sweet_render | 259830adba09fabe4de2eef3537f4a95828965d3 | [
"MIT"
] | null | null | null | src/reyes/config.hpp | cwbaker/sweet_render | 259830adba09fabe4de2eef3537f4a95828965d3 | [
"MIT"
] | null | null | null | src/reyes/config.hpp | cwbaker/sweet_render | 259830adba09fabe4de2eef3537f4a95828965d3 | [
"MIT"
] | null | null | null | #pragma once
#if defined(BUILD_VARIANT_DEBUG)
#define REYES_ASSERT_ENABLED
#elif defined(BUILD_VARIANT_RELEASE)
#define REYES_ASSERT_ENABLED
#elif defined(BUILD_VARIANT_SHIPPING)
#endif
| 16.75 | 38 | 0.79602 | cwbaker |
25e5dd1051ef29602a493e302b7ccbaf82b04d5f | 1,991 | cpp | C++ | LibSrc/Common/Bits.cpp | mice777/ProfiMail-Symbian- | 97cd5bf1abc65c7decdf8d49f0ac155064683b4b | [
"Apache-2.0"
] | null | null | null | LibSrc/Common/Bits.cpp | mice777/ProfiMail-Symbian- | 97cd5bf1abc65c7decdf8d49f0ac155064683b4b | [
"Apache-2.0"
] | null | null | null | LibSrc/Common/Bits.cpp | mice777/ProfiMail-Symbian- | 97cd5bf1abc65c7decdf8d49f0ac155064683b4b | [
"Apache-2.0"
] | null | null | null | // Multi-platform mobile library
// (c) Lonely Cat Games
//----------------------------
#include <Rules.h>
//----------------------------
dword FindHighestBit(dword mask){
int base = 0;
if(mask&0xffff0000){
base = 16;
mask >>= 16;
}
if(mask&0xff00){
base += 8;
mask >>= 8;
}
if(mask&0xf0){
base += 4;
mask >>= 4;
}
static const signed char lut[] = {-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3};
return base + lut[mask];
}
//----------------------------
dword FindLowestBit(dword mask){
if(!mask)
return dword(-1);
int base = 0;
if(!(mask&0xffff)){
base = 16;
mask >>= 16;
}
if(!(mask&0xff)){
base += 8;
mask >>= 8;
}
if(!(mask & 0xf)){
base += 4;
mask >>= 4;
}
static const signed char lut[] = {-1, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
return base + lut[mask&15];
}
//----------------------------
dword ReverseBits(dword mask){
mask = ((mask >> 1) & 0x55555555) | ((mask << 1) & 0xaaaaaaaa);
mask = ((mask >> 2) & 0x33333333) | ((mask << 2) & 0xcccccccc);
mask = ((mask >> 4) & 0x0f0f0f0f) | ((mask << 4) & 0xf0f0f0f0);
mask = ((mask >> 8) & 0x00ff00ff) | ((mask << 8) & 0xff00ff00);
mask = ((mask >> 16) & 0x0000ffff) | ((mask << 16) & 0xffff0000) ;
return mask;
}
//----------------------------
dword CountBits(dword mask){
mask = (mask&0x55555555) + ((mask&0xaaaaaaaa) >> 1);
mask = (mask&0x33333333) + ((mask&0xcccccccc) >> 2);
mask = (mask&0x0f0f0f0f) + ((mask&0xf0f0f0f0) >> 4);
mask = (mask&0x00ff00ff) + ((mask&0xff00ff00) >> 8);
mask = (mask&0x0000ffff) + ((mask&0xffff0000) >> 16);
return mask;
}
//----------------------------
dword RotateLeft(dword mask, int shift){
return (mask<<shift) | (mask>>(32-shift));
}
//----------------------------
dword RotateRight(dword mask, int shift){
return (mask>>shift) | (mask<<(32-shift));
}
//----------------------------
| 22.122222 | 86 | 0.459568 | mice777 |
25e7c9da2160ce3f53d1865fdffb1e2998c7fe93 | 3,187 | cpp | C++ | cpu.cpp | aydanh/HasGB | 05a5f005c03f59b1f47ae4f7af43eedc2beba224 | [
"MIT"
] | null | null | null | cpu.cpp | aydanh/HasGB | 05a5f005c03f59b1f47ae4f7af43eedc2beba224 | [
"MIT"
] | null | null | null | cpu.cpp | aydanh/HasGB | 05a5f005c03f59b1f47ae4f7af43eedc2beba224 | [
"MIT"
] | null | null | null | #include "cpu.h"
#define A r.rAF.hl.h
#define F r.rAF.hl.l
#define B r.rBC.hl.h
#define C r.rBC.hl.l
#define D r.rDE.hl.h
#define E r.rDE.hl.l
#define H r.rHL.hl.h
#define L r.rHL.hl.l
#define AF r.rAF.w
#define BC r.rBC.w
#define DE r.rDE.w
#define HL r.rHL.w
#define PC r.rPC.w
#define SP r.rSP.w
CPU::CPU() {}
CPU::~CPU() {}
void CPU::reset()
{
PC = 0x100;
SP = 0xFFFE;
AF = 0x11B0;
BC = 0x0013;
DE = 0x00D8;
HL = 0x014D;
IME = true;
halt = false;
haltFlag = 0;
opCycle = 0;
gbMode = &mmu->gbMode;
speedMode = 1;
}
int CPU::step()
{
if(IME) { if(checkIntr()){ return 16; } }
else if(halt) { if((haltFlag != (*mmu->intrFlag)) && ((*mmu->intrFlag)&(*mmu->intrMask)&0x1F)) { halt = false; haltFlag = 0; PC++;} }
u8 opcode = mmu->read(PC++);
opCycle = opCyclesData[opcode];
switch(opcode)
{
#include "ops.h"
case CB: { stepCB(); } break;
default: { printf("Unknown opcode %#4x encountered at %#4x\n", opcode, (PC)-1); }
}
return opCycle/speedMode;
}
void CPU::stepCB()
{
u8 opcode = mmu->read(PC++);
opCycle = opCyclesCBData[opcode];
switch(opcode)
{
#include "opsCB.h"
default: { printf("Unknown opcode %d encountered at %d\n", opcode, (PC)-1); }
}
}
int CPU::checkIntr()
{
if(((*mmu->intrFlag)&0x01) && ((*mmu->intrMask)&0x01)) { (*mmu->intrFlag) = ((*mmu->intrFlag)&0xFE); IME = false; if(halt) { PC++; halt = false;} SP -= 2; mmu->writeB(SP, PC); PC = 0x0040; return 1; }
else if(((*mmu->intrFlag)&0x02) && ((*mmu->intrMask)&0x02)) { (*mmu->intrFlag) = ((*mmu->intrFlag)&0xFD); IME = false; if(halt) { PC++; halt = false;} SP -= 2; mmu->writeB(SP, PC); PC = 0x0048; return 1; }
else if(((*mmu->intrFlag)&0x04) && ((*mmu->intrMask)&0x04)) { (*mmu->intrFlag) = ((*mmu->intrFlag)&0xFB); IME = false; if(halt) { PC++; halt = false;} SP -= 2; mmu->writeB(SP, PC); PC = 0x0050; return 1; }
//else if(((*mmu->intrFlag)&0x08) && ((*mmu->intrMask)&0x08)) { (*mmu->intrFlag) = ((*mmu->intrFlag)&0xF7); IME = false; if(halt) { PC++; halt = false;} SP -= 2; mmu->writeB(SP, PC); PC = 0x0058; return 1; }
else if(((*mmu->intrFlag)&0x10) && ((*mmu->intrMask)&0x10)) { (*mmu->intrFlag) = ((*mmu->intrFlag)&0xEF); IME = false; if(halt) { PC++; halt = false;} SP -= 2; mmu->writeB(SP, PC); PC = 0x0060; return 1; }
}
void CPU::setMem(MMU* n_mmu)
{
mmu = n_mmu;
}
void CPU::printState()
{
printf("Next OP %#4x\n", mmu->read(PC));
printf("PC %#4x\n", PC);
printf("A %#4x\n", A);
printf("F %#4x\n", F);
printf("B %#4x\n", B);
printf("C %#4x\n", C);
printf("D %#4x\n", D);
printf("E %#4x\n", E);
printf("H %#4x\n", H);
printf("L %#4x\n", L);
printf("SP %#4x\n", SP);
printf("IF %#4x\n", (*mmu->intrFlag));
printf("IE %#4x\n", (*mmu->intrMask));
printf("IME %#4x\n",IME);
}
u16 CPU::getNextInstAddr()
{
return (PC + opBytesData[mmu->read(PC)]);
}
u16 CPU::getPC()
{
return PC;
}
int CPU::getSpeedMode()
{
return speedMode;
}
/*
int CPU::getHalt()
{
if(IME) { return (!halt || ((*mmu->intrFlag)&(*mmu->intrMask)&0x1F)); }
else{ return (!halt || (*mmu->intrFlag) != haltFlag); }
}*/ | 26.338843 | 211 | 0.553185 | aydanh |
25f290cffa3c7835bf46b47b9ec301f84409ea6f | 665 | cpp | C++ | bin/barftest/sem/TypeIdentifier.cpp | vdods/barf | 5c943ddbd6a0a7624645158b0c85994431dde269 | [
"Apache-2.0"
] | 1 | 2021-01-16T00:55:45.000Z | 2021-01-16T00:55:45.000Z | bin/barftest/sem/TypeIdentifier.cpp | vdods/barf | 5c943ddbd6a0a7624645158b0c85994431dde269 | [
"Apache-2.0"
] | null | null | null | bin/barftest/sem/TypeIdentifier.cpp | vdods/barf | 5c943ddbd6a0a7624645158b0c85994431dde269 | [
"Apache-2.0"
] | null | null | null | // 2016.09.18 - Victor Dods
#include "barftest/sem/TypeIdentifier.hpp"
#include "barftest/sem/Identifier.hpp"
namespace barftest {
namespace sem {
bool TypeIdentifier::equals (Base const &other_) const
{
TypeIdentifier const &other = dynamic_cast<TypeIdentifier const &>(other_);
return are_equal(this->m_id, other.m_id);
}
TypeIdentifier *TypeIdentifier::cloned () const
{
return new TypeIdentifier(firange(), clone_of(m_id));
}
void TypeIdentifier::print (Log &out) const
{
out << "TypeIdentifier(" << firange() << '\n';
out << IndentGuard()
<< m_id << '\n';
out << ')';
}
} // end namespace sem
} // end namespace barftest
| 21.451613 | 79 | 0.67218 | vdods |
25f516b83d82464ebef4a7e6668c6eb99d8f7dc9 | 3,563 | cpp | C++ | programs/chapter_04/underHoodpsc.cpp | epernia/arm_book | ffdd17618c2c7372cef338fc743f517bf6f0f42b | [
"BSD-3-Clause"
] | 2 | 2021-05-03T17:21:37.000Z | 2021-06-08T08:32:07.000Z | programs/chapter_04/underHoodpsc.cpp | epernia/arm_book | ffdd17618c2c7372cef338fc743f517bf6f0f42b | [
"BSD-3-Clause"
] | null | null | null | programs/chapter_04/underHoodpsc.cpp | epernia/arm_book | ffdd17618c2c7372cef338fc743f517bf6f0f42b | [
"BSD-3-Clause"
] | 2 | 2020-10-14T19:06:24.000Z | 2021-06-08T08:32:09.000Z |
#define NUMBER_OF_BITS 12 // En este caso son 12 bits, porque así está el ejemplo.
DigitalOut startOfConversion(LED1); // Se prende solamente al principio una vez para indicar que empieza.
DigitalOut stepOfConversion(LED2); // Se prende cada vez que se completa uno de los doce pasos.
DigitalOut endOfConversion(LED3); // Se prende solamente una vez al final para indicar que terminó.
DigitalIn nextStepButton(Button1); // Con este botón vamos haciendo la pausa entre cada paso (12 pasos)
AnalogIn potentiometer(A0); // Esto se usar para ingresar las lecturas de analogInput
float analogInput; //Ver por favor la figura del Under the hood para entender qué es esta señal
float digitalOutputScaledIntoRange0to1 = 0; //Esto lo usamos para dar la salida en el rando 0 a 1
int conversionStep = 0; // Con esta variable llevaremos la cuenta del paso en que vamos (0 a 11)
bool comparatorOutput = 0; // Ver por favor la figura del Under the hood para entender qué es esta señal
bool DACInput[NUMBER_OF_BITS]; //Acá vamos a ir guardando los 12 bits de la conversión (ver la fig.)
bool digitalOutput[NUMBER_OF_BITS]; //Este es el resultado de la convesión (ver la fig.)
bool analogComparator (input1, input2) // Esta función representa al bloque Analog Comparator (ver fig.)
float digitalToAnalogConverter (array of bool); // Esta función representa al bloque DAC (ver fig.)
void resetIterativeConversionController (array of bool) // Esta función se usa al inicio para resetar DACInput
void showConversionStatus (conversionStep, analogInput, dacOutput, dacInput)
// Esta función se usa para ir mostrando el estado de la conversión en cada paso.
void main () // Lo que está acá adentro se debería repetir indefinidamente.
{
startOfConversion (); // Esta función espera a que se presione el botón de nextStepButton
// Puede poner en la PC un cartel alusivo a que está esperando
// Cuando se presiona el botón debería hacer analogInput = potentiometer.read();
// Debería encender por un segundo el LED startOfConversion
resetIterativeConversionController (); // Se resetea cada bit, se enciende 1 seg startOfConversion,
//se envía un showConversionStatus a la PC.
for (conversionStep = 1 to <= NUMBER_OF_BITS) {
DACInput [NUMBER_OF_BITS - conversionStep] =
iterativeConversionControllerStep (conversionStep, comparatorOutput, DACOutput);
DACOutput = digitalToAnalogConverter(DACInput); //falta escribirla
comparatorOutput = analogComparator (analogInput, DACOutput); //falta escribirla
showConversionStatus (conversionStep, analogInput, dacOutput, dacInput);
}
endOfConversion // Esta función avisa con un cartel en la PC que se terminó la conversión
// Ese cartel debería indicar expresamente el valor de digitalOutput
// Debería mostrar además digitalOutputScaledIntoRange0to1 (que sería entre 0 y 1)
// También debería encender por un segundo el LED endOfConversion
// Debería dejar comparatorOutput = 0 así ya empieza bien la próxima vez.
}
// Declaración de las funciones
showConversionStatus (conversionStep, analogInput, dacOutput, dacInput)
{
printf (conversionStep, analogInput, dacOutput, dacInput)
delay (1000);
while (!nextStepButton);
}
bool analogComparator (analogInput1, analogInput2)
{
//Completa Pablin
}
bool iterativeConversionControllerStep (currentConversionStep,comparisonResult, DACStatus)
{
if (comparatorOutput = 1) {
DACOutput[i] = 1;
} else {
DACOutput[i] = 0;
}
}
| 41.917647 | 110 | 0.751333 | epernia |
25f5f28d0b63b7b9bc00d513dfc4dfb5248ac12d | 525 | hpp | C++ | test/test_prefix.hpp | Oberon00/apollo | 831f4e505afaa04ea827e99f4ced247bb0f0e476 | [
"BSD-2-Clause"
] | 25 | 2016-01-04T23:07:06.000Z | 2022-03-03T11:24:55.000Z | test/test_prefix.hpp | Oberon00/apollo | 831f4e505afaa04ea827e99f4ced247bb0f0e476 | [
"BSD-2-Clause"
] | 2 | 2018-05-21T18:15:49.000Z | 2018-05-21T18:47:05.000Z | test/test_prefix.hpp | Oberon00/apollo | 831f4e505afaa04ea827e99f4ced247bb0f0e476 | [
"BSD-2-Clause"
] | 6 | 2019-12-05T04:05:06.000Z | 2022-03-03T11:24:38.000Z | // Part of the apollo library -- Copyright (c) Christian Neumüller 2015
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause
#ifdef APOLLO_TEST_PREFIX_HPP_INCLUDED
# error Test prefix may only be included once.
#endif
#define APOLLO_TEST_PREFIX_HPP_INCLUDED APOLLO_TEST_PREFIX_HPP_INCLUDED
#include "testutil.hpp"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(
BOOST_JOIN(BOOST_TEST_MODULE, _suite),
lstate_fixture)
| 30.882353 | 71 | 0.790476 | Oberon00 |
25fa3fb51b15ebc92610d417bb9dbf9e1640aaba | 3,329 | cpp | C++ | select_serv.cpp | MatrixWood/sometestsnippet | 5ab058d6110233c948f2db44b1ba8e70fec04ab9 | [
"MIT"
] | null | null | null | select_serv.cpp | MatrixWood/sometestsnippet | 5ab058d6110233c948f2db44b1ba8e70fec04ab9 | [
"MIT"
] | null | null | null | select_serv.cpp | MatrixWood/sometestsnippet | 5ab058d6110233c948f2db44b1ba8e70fec04ab9 | [
"MIT"
] | null | null | null | #include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <sys/time.h>
#include <vector>
#include <errno.h>
#define INVALID_FD -1
int main(int argc, char* argv[]) {
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == INVALID_FD) {
std::cout << "create listen socket error." << std::endl;
return -1;
}
struct sockaddr_in bindaddr;
bindaddr.sin_addr.s_addr = htonl(INADDR_ANY);
bindaddr.sin_family = AF_INET;
bindaddr.sin_port = htons(3000);
if (bind(listenfd, (struct sockaddr*)&bindaddr, sizeof(bindaddr)) == -1) {
std::cout << "bind listen socket error." << std::endl;
close(listenfd);
return -1;
}
if (listen(listenfd, SOMAXCONN) == -1) {
std::cout << "listen error." << std::endl;
close(listenfd);
return -1;
}
std::vector<int> clientfds;
int maxfd;
while (true) {
fd_set readset;
FD_ZERO(&readset);
FD_SET(listenfd, &readset);
maxfd = listenfd;
int clientfdslength = clientfds.size();
for (int i = 0; i < clientfdslength; ++i) {
if (clientfds[i] != INVALID_FD) {
FD_SET(clientfds[i], &readset);
if (maxfd < clientfds[i])
maxfd = clientfds[i];
}
}
timeval tm;
tm.tv_sec = 1;
tm.tv_usec = 0;
int ret = select(maxfd + 1, &readset, nullptr, nullptr, &tm);
if (ret == -1) {
// error
if (errno != EINTR)
break;
}
else if (ret == 0) {
// timeout
continue;
}
else {
if (FD_ISSET(listenfd, &readset)) {
struct sockaddr_in clientaddr;
socklen_t clientaddrlen = sizeof(clientaddr);
int clientfd = accept(listenfd, (struct sockaddr*)&clientaddr, &clientaddrlen);
if (clientfd == INVALID_FD)
break;
std::cout << "accept a client connection, fd: " << clientfd << std::endl;
clientfds.push_back(clientfd);
}
else {
char recvbuf[64];
int clientfdslength = clientfds.size();
for (int i = 0; i < clientfdslength; ++i) {
if (clientfds[i] != INVALID_FD && FD_ISSET(clientfds[i], &readset)) {
memset(recvbuf, 0, sizeof(recvbuf));
int length = recv(clientfds[i], recvbuf, 64, 0);
if (length <= 0) {
std::cout << "recv data error, clientfd: " << clientfds[i] << std::endl;
close(clientfds[i]);
clientfds[i] = INVALID_FD;
continue;
}
std::cout << "clientfd: " << clientfds[i] << ", recv data: " << recvbuf << std::endl;
}
}
}
}
}
// close all socket
for (int i = 0; i < clientfds.size(); ++i) {
if (clientfds[i] != INVALID_FD) {
close(clientfds[i]);
}
}
close(listenfd);
return 0;
} | 31.40566 | 109 | 0.47672 | MatrixWood |
d301b004ffea4ee8214e970feb3fbd1ce3683bae | 1,635 | hpp | C++ | include/editor/display_options/display_options.hpp | riscygeek/AntSimulator | b35d1b0e0a3601ec326eb2839fb7551672d036af | [
"MIT"
] | null | null | null | include/editor/display_options/display_options.hpp | riscygeek/AntSimulator | b35d1b0e0a3601ec326eb2839fb7551672d036af | [
"MIT"
] | null | null | null | include/editor/display_options/display_options.hpp | riscygeek/AntSimulator | b35d1b0e0a3601ec326eb2839fb7551672d036af | [
"MIT"
] | null | null | null | #pragma once
#include "editor/GUI/named_container.hpp"
#include "editor/GUI/utils.hpp"
#include "editor/control_state.hpp"
#include "editor/GUI/toggle.hpp"
struct DisplayOption : public GUI::NamedContainer
{
ControlState& control_state;
bool draw_ants = false;
bool draw_markers = false;
bool draw_density = false;
explicit
DisplayOption(ControlState& control_state_)
: GUI::NamedContainer("Display Options", GUI::Container::Orientation::Horizontal)
, control_state(control_state_)
{
size_type.y = GUI::Size::FitContent;
auto ants = create<GUI::NamedToggle>("Draw Ants");
watch(ants, [this, ants](){
draw_ants = ants->getState();
notifyChanged();
});
ants->setState(true);
GUI::NamedContainer::addItem(ants);
auto markers = create<GUI::NamedToggle>("Draw Markers");
GUI::NamedContainer::addItem(markers);
auto density = create<GUI::NamedToggle>("Draw Density");
GUI::NamedContainer::addItem(density);
watch(markers, [this, markers, density](){
if (markers->getState()) {
density->setState(false);
}
draw_markers = markers->getState();
draw_density = density->getState();
notifyChanged();
});
watch(density, [this, markers, density](){
if (density->getState()) {
markers->setState(false);
}
draw_markers = markers->getState();
draw_density = density->getState();
notifyChanged();
});
}
};
| 29.727273 | 89 | 0.586544 | riscygeek |
d301e6531e3c9000aa66250cc619740a079a55c2 | 356 | cpp | C++ | Chapter8/L8.5.cpp | flics04/XXXASYBT_CppBase | 0086df68497197f40286889b18f2d8c28eb833bb | [
"MIT"
] | 1 | 2022-02-13T02:22:39.000Z | 2022-02-13T02:22:39.000Z | Chapter8/L8.5.cpp | flics04/XXXASYBT_CppBase | 0086df68497197f40286889b18f2d8c28eb833bb | [
"MIT"
] | null | null | null | Chapter8/L8.5.cpp | flics04/XXXASYBT_CppBase | 0086df68497197f40286889b18f2d8c28eb833bb | [
"MIT"
] | null | null | null | #include <cstdio>
using namespace std;
int main() {
int a[5], i, *pa = a; // 定义整形数组和指针,*pa = a可以在下一行
for (i = 0; i < 5; i++) // 可写成pa + i和&a[i]
scanf("%d", a + i);
for (i = 0; i < 5; i++) // 指针访问数组,可写成*(pa + i)或pa[i]或a[i]
printf("a[%d] = %d\n", i, * (a + i));
return 0;
}
| 27.384615 | 77 | 0.382022 | flics04 |
d302692f9f7a16c33b078ce962cf6a1a59165796 | 1,388 | hpp | C++ | public/anton/type_list.hpp | kociap/atl | a7dc9b35c14453040db82dbbeca3c305bb25c66e | [
"MIT"
] | null | null | null | public/anton/type_list.hpp | kociap/atl | a7dc9b35c14453040db82dbbeca3c305bb25c66e | [
"MIT"
] | null | null | null | public/anton/type_list.hpp | kociap/atl | a7dc9b35c14453040db82dbbeca3c305bb25c66e | [
"MIT"
] | 1 | 2020-12-15T13:51:38.000Z | 2020-12-15T13:51:38.000Z | #pragma once
#include <anton/detail/tuple.hpp>
#include <anton/type_traits/base.hpp>
namespace anton {
template<typename... Ts>
struct Type_List {
public:
using type = Type_List<Ts...>;
};
template<typename... Types>
struct Tuple_Size<Type_List<Types...>>: Integral_Constant<u64, sizeof...(Types)> {};
template<typename... Types>
struct Tuple_Size<Type_List<Types...> const>: Integral_Constant<u64, sizeof...(Types)> {};
namespace detail {
template<u64 N, u64 X, typename>
struct Tuple_Element;
template<u64 N, u64 X, typename T, typename... Types>
struct Tuple_Element<N, X, Type_List<T, Types...>> {
using type = typename Tuple_Element<N, X + 1, Type_List<Types...>>::type;
};
template<u64 N, typename T, typename... Types>
struct Tuple_Element<N, N, Type_List<T, Types...>> {
using type = T;
};
} // namespace detail
template<u64 Index, typename... Types>
struct Tuple_Element<Index, Type_List<Types...>> {
using type = typename detail::Tuple_Element<Index, 0, Type_List<Types...>>::type;
};
template<u64 Index, typename... Types>
struct Tuple_Element<Index, Type_List<Types...> const> {
using type = typename detail::Tuple_Element<Index, 0, Type_List<Types...>>::type const;
};
} // namespace anton
| 31.545455 | 95 | 0.622478 | kociap |
d303b1fc0b6fd4cfd2b48426175b5f4749debda1 | 1,822 | cpp | C++ | DjinnTest/math/math.cpp | grandmaster789/Djinn | cfec71b99be399f76b22200a8afa84875cfb0888 | [
"MIT"
] | 2 | 2019-01-15T14:55:40.000Z | 2021-05-07T05:24:32.000Z | DjinnTest/math/math.cpp | grandmaster789/Djinn | cfec71b99be399f76b22200a8afa84875cfb0888 | [
"MIT"
] | null | null | null | DjinnTest/math/math.cpp | grandmaster789/Djinn | cfec71b99be399f76b22200a8afa84875cfb0888 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CppUnitTest.h"
#include "math/math.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace djinn::math;
/*
constexpr auto max(const T& v0, const U& v1);
constexpr auto max(const T& v0, const Ts&... vs);
constexpr auto min(const T& v0, const U& v1);
constexpr auto min(const T& v0, const Ts&... vs);
*/
namespace DjinnTest {
struct Foo {
int i;
float f;
bool b;
double d;
int j;
};
#pragma pack(push, 1)
struct Bar {
char c[3];
};
#pragma pack(pop)
TEST_CLASS(Math) {
public:
TEST_METHOD(alignment) {
constexpr size_t fooSize = sizeof(Foo); // default alignments is 4, so this ends up being 32 bytes
constexpr size_t barSize = sizeof(Bar); // custom struct layout, 3 bytes
constexpr size_t smaller = alignToSmaller(sizeof(Foo), sizeof(Bar));
constexpr size_t larger = alignToLarger(sizeof(Bar), sizeof(Foo));
Assert::IsTrue(fooSize == 32);
Assert::IsTrue(barSize == 3);
Assert::IsTrue(smaller == 30);
Assert::IsTrue(larger == 32);
}
TEST_METHOD(rounding) {
Assert::IsTrue(roundToInt(0.6) == 1);
Assert::IsTrue(roundToInt(0.5) == 1);
Assert::IsTrue(roundToInt(0) == 0);
Assert::IsTrue(roundToInt(-0.4) == 0);
Assert::IsTrue(roundToInt(-0.5) == -1);
for (int i = -100; i < 100; ++i) {
float f = i * 0.01f - 1.0f;
Assert::IsTrue(roundToInt(f) == static_cast<int>(std::round(f)));
}
}
TEST_METHOD(minmax) {
Assert::IsTrue(max(0, 1, 2, 3, 4, 5) == 5);
Assert::IsTrue(min(0, 1, 2, 3, 4, 5) == 0);
Assert::IsTrue(max(5, 4, 3, 2, 1, 0) == 5);
Assert::IsTrue(min(5, 4, 3, 2, 1, 0) == 0);
Assert::IsTrue(max(-0.5f, -0.4f, -0.3f, -0.2f, -0.1f, 0.0f) == 0.0f);
Assert::IsTrue(min(-0.5f, -0.4f, -0.3f, -0.2f, -0.1f, 0.0f) == -0.5f);
}
};
} | 26.028571 | 101 | 0.607025 | grandmaster789 |
d309f2aa51cb5dd0d78751bf02ca2cc0d280002c | 4,043 | hpp | C++ | includes/stream.hpp | otofoto/polpp | 3fb768f5a4d7c430b1c210b4508cf6ed787ce935 | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2021-11-02T22:52:25.000Z | 2021-11-02T22:52:25.000Z | includes/stream.hpp | otofoto/polepp | 3fb768f5a4d7c430b1c210b4508cf6ed787ce935 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | includes/stream.hpp | otofoto/polepp | 3fb768f5a4d7c430b1c210b4508cf6ed787ce935 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // POLEPP - Portable C++ library to access OLE Storage
// Copyright (C) 2004-2006 Jorge Lodos Vigil
// Copyright (C) 2004 Israel Fernandez Cabrera
// 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 authors nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#ifndef _OLE_STREAM_
#define _OLE_STREAM_
#include "pole/pole.h"
namespace ole
{
// Objects of this class are constructed by the storage.
// Streams allow read/write operations. Allthough not typical for
// streams, they also have a size and may be resized. This
// seemed better than automatically resize on overflow.
// These streams are dual seekable, they have separate heads
// for reading and writing.
// This class is not thread safe.
class stream
{
// Construction
public:
stream(POLE::Stream& str): m_stream(str) {}
stream(const stream& other): m_stream(other.m_stream) {}
// Attributes
public:
// Standard stream attributes.
bool fail() const { return m_stream.fail(); }
bool eof() const { return m_stream.eof(); }
std::streampos tellg() const { return m_stream.tellg(); }
std::streampos tellp() const { return m_stream.tellp(); }
std::streamsize size() const { return m_stream.size(); }
// Operations
public:
// These are standard stream operations. This functions may set or
// reset the eof and fail bits.
std::streamsize read(char* buf, std::streamsize n) { return m_stream.read((unsigned char *)buf, n); }
std::streamsize write(const char* buf, std::streamsize n) { return m_stream.write((unsigned char *)buf, n); }
std::streampos seek(std::streamoff off, std::ios::seekdir way, std::ios::openmode mode) { return m_stream.seek(off, way, mode); }
void seekg(std::streamoff off, std::ios::seekdir way) { m_stream.seekg(off, way); }
void seekp(std::streamoff off, std::ios::seekdir way) { m_stream.seekp(off, way); }
// Increase the stream size. If size is less than the current size no
// action is taken and the function succeeds. The value of new space
// is undefined. Returns true on success.
bool reserve(std::streamsize size) { return m_stream.reserve(size); }
// Set a new size for the stream, making it smaller if size is less
// than the current size. When increasing the size, the value of new
// space is filled with val. Returns true on success.
bool resize(std::streamsize size, char val = 0) { return m_stream.resize(size, val); }
// Implementation
private:
POLE::Stream& m_stream;
stream(); // No default construction
stream& operator=( const stream& other ); // No asignment operator
};
}
#endif // _OLE_STREAM_
| 44.922222 | 131 | 0.722483 | otofoto |
d309ffb61ccef7a6c4640a19dd85e75e5993a217 | 1,954 | cpp | C++ | tests/utility/test_random.cpp | Kriston-SCT/ospcommon | 7a0b4fa47156a4cc7781652c4ed58f188dddefa6 | [
"Apache-2.0"
] | null | null | null | tests/utility/test_random.cpp | Kriston-SCT/ospcommon | 7a0b4fa47156a4cc7781652c4ed58f188dddefa6 | [
"Apache-2.0"
] | null | null | null | tests/utility/test_random.cpp | Kriston-SCT/ospcommon | 7a0b4fa47156a4cc7781652c4ed58f188dddefa6 | [
"Apache-2.0"
] | null | null | null | // ======================================================================== //
// Copyright 2009-2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include <random>
#include "../catch.hpp"
#include "ospcommon/utility/random.h"
using ospcommon::utility::pcg32_biased_float_distribution;
TEST_CASE("random", "[random]")
{
std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_real_distribution<float> dist(-1000, 1000);
for (int iter = 0; iter < 1000; iter++) {
float lower = dist(e1);
float upper = dist(e1);
pcg32_biased_float_distribution osp_dist(iter, iter, lower, upper);
INFO("seed = " << iter << " lower = " << lower << " upper = " << upper);
if (lower > upper)
std::swap(lower, upper);
for (int i = 0; i < 1000; i++) {
float val = osp_dist();
INFO("val = " << val);
REQUIRE(val >= lower);
REQUIRE(val <= upper);
}
}
} | 44.409091 | 78 | 0.467758 | Kriston-SCT |
d30c7f03f1e7f734cf56de15f852d0273ee0a4c7 | 479 | cpp | C++ | 374. Guess Number Higher or Lower.cpp | zhugejunwei/LeetCode | d3eeaaf2655740c924bcd39fcbcd088cd7b320ce | [
"MIT"
] | 2 | 2016-08-30T00:15:15.000Z | 2016-08-30T00:15:35.000Z | 374. Guess Number Higher or Lower.cpp | zhugejunwei/LeetCode | d3eeaaf2655740c924bcd39fcbcd088cd7b320ce | [
"MIT"
] | null | null | null | 374. Guess Number Higher or Lower.cpp | zhugejunwei/LeetCode | d3eeaaf2655740c924bcd39fcbcd088cd7b320ce | [
"MIT"
] | null | null | null | // Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int myNum = (1+n) >> 1;
int step = myNum;
int t = 0;
do {
t = guess(myNum);
step = step >> 1 ? step >> 1 : 1;
myNum += step*t;
}while (t != 0);
return myNum;
}
}; | 23.95 | 81 | 0.498956 | zhugejunwei |
d31ba9cddad028a12b4fc21a064360cd60deabb2 | 17,043 | cpp | C++ | drishti/gilights.cpp | shouhengli/drishti | 46558d12adcc1d365b7e2125d28190e3be2181c3 | [
"MIT"
] | 118 | 2016-11-01T06:01:44.000Z | 2022-03-30T05:20:19.000Z | drishti/gilights.cpp | shouhengli/drishti | 46558d12adcc1d365b7e2125d28190e3be2181c3 | [
"MIT"
] | 56 | 2016-09-30T09:29:36.000Z | 2022-03-31T17:15:32.000Z | drishti/gilights.cpp | shouhengli/drishti | 46558d12adcc1d365b7e2125d28190e3be2181c3 | [
"MIT"
] | 28 | 2016-07-31T23:48:51.000Z | 2021-05-25T05:32:47.000Z | #include "global.h"
#include "gilights.h"
#include "staticfunctions.h"
#include "propertyeditor.h"
#include <QFileDialog>
int GiLights::count() { return m_giLights.count(); }
GiLights::GiLights()
{
m_sameForAll = true;
m_giLights.clear();
}
GiLights::~GiLights()
{
clear();
}
void
GiLights::clear()
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->disconnect();
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->removeFromMouseGrabberPool();
for(int i=0; i<m_giLights.count(); i++)
delete m_giLights[i];
m_giLights.clear();
}
bool
GiLights::isInMouseGrabberPool(int i)
{
if (i < m_giLights.count())
return m_giLights[i]->isInMouseGrabberPool();
else
return false;
}
void
GiLights::addInMouseGrabberPool(int i)
{
if (i < m_giLights.count())
m_giLights[i]->addInMouseGrabberPool();
}
void
GiLights::addInMouseGrabberPool()
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->addInMouseGrabberPool();
}
void
GiLights::removeFromMouseGrabberPool(int i)
{
if (i < m_giLights.count())
m_giLights[i]->removeFromMouseGrabberPool();
}
void
GiLights::removeFromMouseGrabberPool()
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->removeFromMouseGrabberPool();
}
bool
GiLights::grabsMouse()
{
for(int i=0; i<m_giLights.count(); i++)
{
if (m_giLights[i]->grabsMouse())
return true;
}
return false;
}
void
GiLights::addGiPointLight(QList<Vec> pts)
{
GiLightGrabber *pg = new GiLightGrabber();
pg->setPoints(pts);
m_giLights.append(pg);
makeGiLightConnections();
}
void
GiLights::addGiDirectionLight(QList<Vec> pts)
{
GiLightGrabber *pg = new GiLightGrabber();
pg->setPoints(pts);
pg->setLightType(1);
m_giLights.append(pg);
makeGiLightConnections();
}
void
GiLights::addGiLight(GiLightObject po)
{
GiLightGrabber *pg = new GiLightGrabber();
pg->set(po);
m_giLights.append(pg);
makeGiLightConnections();
}
void
GiLights::addGiLight(QString flnm)
{
QFile fpath(flnm);
fpath.open(QFile::ReadOnly);
QTextStream fd(&fpath);
QString line = fd.readLine();
while (! fd.atEnd())
{
QStringList list = line.split(" ", QString::SkipEmptyParts);
if (list.count() == 1)
{
int npts = list[0].toInt();
QList<Vec> pts;
for(int i=0; i<npts; i++)
{
if (fd.atEnd())
break;
else
{
QString line = fd.readLine();
QStringList list = line.split(" ", QString::SkipEmptyParts);
if (list.count() == 3)
{
float x = list[0].toFloat();
float y = list[1].toFloat();
float z = list[2].toFloat();
pts.append(Vec(x,y,z));
}
}
}
if (pts.count() > 0)
{
GiLightGrabber *pg = new GiLightGrabber();
pg->setPoints(pts);
m_giLights.append(pg);
}
}
line = fd.readLine();
}
makeGiLightConnections();
}
QList<GiLightGrabber*> GiLights::giLightsPtr() { return m_giLights; }
QList<GiLightObject>
GiLights::giLights()
{
QList<GiLightObject> po;
for(int i=0; i<m_giLights.count(); i++)
po.append(m_giLights[i]->get());
return po;
}
void
GiLights::setGiLights(QList<GiLightObject> po)
{
clear();
for(int i=0; i<po.count(); i++)
{
GiLightGrabber *pg = new GiLightGrabber();
pg->set(po[i]);
m_giLights.append(pg);
}
makeGiLightConnections();
}
void
GiLights::updateScaling()
{
for(int i=0; i<m_giLights.count();i++)
m_giLights[i]->computePathLength();
}
void
GiLights::draw(QGLViewer *viewer, bool backToFront)
{
for(int i=0; i<m_giLights.count();i++)
m_giLights[i]->draw(viewer,
m_giLights[i]->grabsMouse(),
backToFront);
}
void
GiLights::postdraw(QGLViewer *viewer)
{
for(int i=0; i<m_giLights.count();i++)
{
int x,y;
m_giLights[i]->mousePosition(x,y);
m_giLights[i]->postdraw(viewer,
x, y,
m_giLights[i]->grabsMouse());
}
}
bool
GiLights::keyPressEvent(QKeyEvent *event)
{
for(int i=0; i<m_giLights.count(); i++)
{
if (m_giLights[i]->grabsMouse())
{
if (event->key() == Qt::Key_G)
{
m_giLights[i]->removeFromMouseGrabberPool();
return true;
}
else if (event->key() == Qt::Key_V)
{
setShow(i, false);
return true;
}
else if (event->key() == Qt::Key_P)
{
bool b = m_giLights[i]->showPoints();
m_giLights[i]->setShowPoints(!b);
return true;
}
else if (event->key() == Qt::Key_N)
{
bool b = m_giLights[i]->showPointNumbers();
m_giLights[i]->setShowPointNumbers(!b);
return true;
}
else if (event->key() == Qt::Key_X)
{
m_giLights[i]->setMoveAxis(GiLightGrabber::MoveX);
return true;
}
else if (event->key() == Qt::Key_Y)
{
if (event->modifiers() & Qt::ControlModifier ||
event->modifiers() & Qt::MetaModifier)
m_giLights[i]->redo();
else
m_giLights[i]->setMoveAxis(GiLightGrabber::MoveY);
return true;
}
else if (event->key() == Qt::Key_Z)
{
if (event->modifiers() & Qt::ControlModifier ||
event->modifiers() & Qt::MetaModifier)
m_giLights[i]->undo();
else
m_giLights[i]->setMoveAxis(GiLightGrabber::MoveZ);
return true;
}
else if (event->key() == Qt::Key_W)
{
m_giLights[i]->setMoveAxis(GiLightGrabber::MoveAll);
return true;
}
else if (event->key() == Qt::Key_Delete ||
event->key() == Qt::Key_Backspace ||
event->key() == Qt::Key_Backtab)
{
m_giLights[i]->removeFromMouseGrabberPool();
m_giLights.removeAt(i);
return true;
}
if (event->key() == Qt::Key_Space)
return openPropertyEditor(i);
}
}
return true;
}
bool
GiLights::openPropertyEditor(int i)
{
PropertyEditor propertyEditor;
QMap<QString, QVariantList> plist;
QVariantList vlist;
vlist.clear();
vlist << QVariant("combobox");
vlist << QVariant(m_giLights[i]->lightType());
vlist << QVariant("point");
vlist << QVariant("direction");
plist["light type"] = vlist;
vlist.clear();
vlist << QVariant("color");
Vec pcolor = m_giLights[i]->color();
QColor dcolor = QColor::fromRgbF(pcolor.x,
pcolor.y,
pcolor.z);
vlist << dcolor;
plist["color"] = vlist;
vlist.clear();
vlist << QVariant("double");
vlist << QVariant(m_giLights[i]->opacity());
vlist << QVariant(0.0);
vlist << QVariant(5.0);
vlist << QVariant(0.1); // singlestep
vlist << QVariant(1); // decimals
plist["opmod"] = vlist;
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_giLights[i]->lod());
vlist << QVariant(1);
vlist << QVariant(10);
plist["light buffer size"] = vlist;
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_giLights[i]->smooth());
vlist << QVariant(1);
vlist << QVariant(10);
plist["light buffer smoothing"] = vlist;
if (m_giLights[i]->rad() > 1)
{
vlist.clear();
vlist << QVariant("double");
vlist << QVariant(m_giLights[i]->angle());
vlist << QVariant(10.0);
vlist << QVariant(80.0);
vlist << QVariant(10.0);// singlestep
vlist << QVariant(1); // decimals
plist["collection angle"] = vlist;
}
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_giLights[i]->allowInterpolate());
plist["interpolate"] = vlist;
if (m_giLights[i]->lightType() == 0) // point light
{
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_giLights[i]->rad());
vlist << QVariant(1);
vlist << QVariant(50);
plist["size"] = vlist;
vlist.clear();
vlist << QVariant("double");
vlist << QVariant(m_giLights[i]->decay());
vlist << QVariant(0.1);
vlist << QVariant(1.0);
vlist << QVariant(0.05);// singlestep
vlist << QVariant(3); // decimals
plist["falloff"] = vlist;
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_giLights[i]->segments());
vlist << QVariant(1);
vlist << QVariant(100);
plist["smoothness"] = vlist;
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_giLights[i]->doShadows());
plist["do shadows"] = vlist;
}
vlist.clear();
plist["command"] = vlist;
vlist.clear();
QFile helpFile(":/gilights.help");
if (helpFile.open(QFile::ReadOnly))
{
QTextStream in(&helpFile);
QString line = in.readLine();
while (!line.isNull())
{
if (line == "#begin")
{
QString keyword = in.readLine();
QString helptext;
line = in.readLine();
while (!line.isNull())
{
helptext += line;
helptext += "\n";
line = in.readLine();
if (line == "#end") break;
}
vlist << keyword << helptext;
}
line = in.readLine();
}
}
plist["commandhelp"] = vlist;
QStringList keys;
keys << "light type";
keys << "light buffer size";
keys << "light buffer smoothing";
keys << "gap";
keys << "color";
keys << "opmod";
if (m_giLights[i]->rad() > 1)
keys << "collection angle";
if (m_giLights[i]->lightType() == 0) // point light
{
keys << "size";
keys << "falloff";
if (m_giLights[i]->rad() > 1)
{
keys << "smoothness";
keys << "gap";
keys << "do shadows";
keys << "gap";
}
}
keys << "gap";
keys << "interpolate";
keys << "command";
//keys << "commandhelp";
propertyEditor.set("GI Light Parameters", plist, keys);
propertyEditor.resize(400, 500);
QMap<QString, QPair<QVariant, bool> > vmap;
if (propertyEditor.exec() == QDialog::Accepted)
vmap = propertyEditor.get();
else
return true;
keys = vmap.keys();
for(int ik=0; ik<keys.count(); ik++)
{
QPair<QVariant, bool> pair = vmap.value(keys[ik]);
if (pair.second)
{
if (keys[ik] == "color")
{
QColor color = pair.first.value<QColor>();
float r = color.redF();
float g = color.greenF();
float b = color.blueF();
pcolor = Vec(r,g,b);
m_giLights[i]->setColor(pcolor);
}
else if (keys[ik] == "opmod")
m_giLights[i]->setOpacity(pair.first.toDouble());
else if (keys[ik] == "light buffer size")
m_giLights[i]->setLod(pair.first.toInt());
else if (keys[ik] == "light buffer smoothing")
m_giLights[i]->setSmooth(pair.first.toInt());
else if (keys[ik] == "smoothness")
m_giLights[i]->setSegments(pair.first.toInt());
else if (keys[ik] == "interpolate")
m_giLights[i]->setAllowInterpolate(pair.first.toBool());
else if (keys[ik] == "do shadows")
m_giLights[i]->setDoShadows(pair.first.toBool());
else if (keys[ik] == "light type")
m_giLights[i]->setLightType(pair.first.toInt());
else if (keys[ik] == "size")
m_giLights[i]->setRad(pair.first.toInt());
else if (keys[ik] == "falloff")
m_giLights[i]->setDecay(pair.first.toFloat());
else if (keys[ik] == "collection angle")
m_giLights[i]->setAngle(pair.first.toFloat());
}
}
QString cmd = propertyEditor.getCommandString();
if (!cmd.isEmpty())
processCommand(i, cmd);
emit updateGL();
return true;
}
void
GiLights::makeGiLightConnections()
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->disconnect();
for(int i=0; i<m_giLights.count(); i++)
{
connect(m_giLights[i], SIGNAL(selectForEditing(int, int)),
this, SLOT(selectForEditing(int, int)));
connect(m_giLights[i], SIGNAL(deselectForEditing()),
this, SLOT(deselectForEditing()));
}
}
void
GiLights::deselectForEditing()
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->setPointPressed(-1);
emit updateLightBuffers();
}
void
GiLights::selectForEditing(int mouseButton,
int p0)
{
int idx = -1;
for(int i=0; i<m_giLights.count(); i++)
{
if (m_giLights[i]->grabsMouse())
{
idx = i;
break;
}
}
if (idx == -1)
return;
if (mouseButton == Qt::RightButton)
{
if (m_giLights[idx]->pointPressed() == -1)
emit showMessage("No point selected for removal", true);
else
{
if (m_giLights[idx]->lightType() == 1)
{
QMessageBox::information(0, "", "Press DEL to delete Direction Light");
m_giLights[idx]->setPointPressed(-1);
return;
}
else
m_giLights[idx]->removePoint(m_giLights[idx]->pointPressed());
}
}
else if (mouseButton == Qt::LeftButton && p0 > -1)
m_giLights[idx]->insertPointAfter(p0);
// else
// m_giLights[idx]->setPointPressed(m_giLights[idx]->pointPressed());
}
void
GiLights::processCommand(int idx, QString cmd)
{
bool ok;
QString origCmd = cmd;
cmd = cmd.toLower();
QStringList list = cmd.split(" ", QString::SkipEmptyParts);
int li = 0;
while (li < list.count())
{
if (list[li] == "planar")
{
if (list.count()-li > 3)
{
int v0 = list[li+1].toInt(&ok);
int v1 = list[li+2].toInt(&ok);
int v2 = list[li+3].toInt(&ok);
m_giLights[idx]->makePlanar(v0,v1,v2);
li += 3;
}
else
m_giLights[idx]->makePlanar();
}
else if (list[li] == "circle")
{
m_giLights[idx]->makeCircle();
}
else if (list[li] == "normalize" ||
list[li] == "normalise")
{
m_giLights[idx]->normalize();
}
else if (list[li] == "moves")
{
if (list.size()-li > 1)
{
if (list[li+1] == "-")
m_giLights[idx]->translate(true, false);
else
m_giLights[idx]->translate(true, true);
li++;
}
else
m_giLights[idx]->translate(true, true);
}
else if (list[li] == "movet")
{
if (list.size()-li > 1)
{
if (list[li+1] == "-")
m_giLights[idx]->translate(false, false);
else
m_giLights[idx]->translate(false, true);
li++;
}
else
m_giLights[idx]->translate(false, true);
}
else if (list[li] == "save")
{
QString flnm;
flnm = QFileDialog::getSaveFileName(0,
"Save point lights to text file",
Global::previousDirectory(),
"Files (*.*)");
if (flnm.isEmpty())
return;
QList<Vec> pts = m_giLights[idx]->points();
QFile fpath(flnm);
fpath.open(QFile::WriteOnly | QFile::Text);
QTextStream fd(&fpath);
fd << pts.count() << "\n";
for(int pi=0; pi < pts.count(); pi++)
fd << pts[pi].x << " " << pts[pi].y << " " << pts[pi].z << "\n";
fd.flush();
}
else
QMessageBox::information(0, "GI Light Command Error",
QString("Cannot understand the command : ") +
cmd);
li++;
}
}
GiLightGrabber*
GiLights::checkIfGrabsMouse(int x, int y, Camera *cam)
{
for(int i=0; i<m_giLights.count(); i++)
{
if (m_giLights[i]->isInMouseGrabberPool())
{
m_giLights[i]->checkIfGrabsMouse(x, y, cam);
if (m_giLights[i]->grabsMouse())
return m_giLights[i];
}
}
return NULL;
}
void
GiLights::mousePressEvent(QMouseEvent *e, Camera *c)
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->mousePressEvent(e,c);
}
void
GiLights::mouseMoveEvent(QMouseEvent *e, Camera *c)
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->mouseMoveEvent(e,c);
}
void
GiLights::mouseReleaseEvent(QMouseEvent *e, Camera *c)
{
for(int i=0; i<m_giLights.count(); i++)
m_giLights[i]->mouseReleaseEvent(e,c);
}
void
GiLights::show()
{
for(int i=0; i<m_giLights.count(); i++)
{
m_giLights[i]->setShow(true);
m_giLights[i]->addInMouseGrabberPool();
}
}
void
GiLights::hide()
{
for(int i=0; i<m_giLights.count(); i++)
{
m_giLights[i]->setShow(false);
m_giLights[i]->removeFromMouseGrabberPool();
}
}
bool
GiLights::show(int i)
{
if (i >= 0 && i < m_giLights.count())
return m_giLights[i]->show();
else
return false;
}
void
GiLights::setShow(int i, bool flag)
{
if (i == -1)
{
for(int l=0; l<m_giLights.count(); l++)
{
m_giLights[l]->setShow(flag);
if (flag)
m_giLights[l]->addInMouseGrabberPool();
else
m_giLights[l]->removeFromMouseGrabberPool();
}
}
else if (i >= 0 && i < m_giLights.count())
{
m_giLights[i]->setShow(flag);
if (flag)
m_giLights[i]->addInMouseGrabberPool();
else
m_giLights[i]->removeFromMouseGrabberPool();
}
}
bool
GiLights::setGiLightObjectInfo(QList<GiLightObjectInfo> gloInfo)
{
bool lightsChanged = false;
if (gloInfo.count() != m_giLights.count()) lightsChanged = true;
for(int i=0; i<qMin(gloInfo.count(), m_giLights.count()); i++)
{
if (m_giLights[i]->checkIfNotEqual(gloInfo[i]))
{
lightsChanged = true;
break;
}
}
clear();
for(int i=0; i<gloInfo.count(); i++)
{
GiLightGrabber *pg = new GiLightGrabber();
pg->setGiLightObjectInfo(gloInfo[i]);
m_giLights.append(pg);
}
return lightsChanged;
}
QList<GiLightObjectInfo>
GiLights::giLightObjectInfo()
{
QList<GiLightObjectInfo> glo;
for(int i=0; i<m_giLights.count(); i++)
glo << m_giLights[i]->giLightObjectInfo();
return glo;
}
| 22.047865 | 78 | 0.592443 | shouhengli |
d3227fa87936f97e998c32b583451672842c9ce3 | 13,861 | cpp | C++ | tests/typelist_basic.cpp | surrealwaffle/yymp | 662def34a298bf2992bf429e26bc35605906897b | [
"BSL-1.0"
] | 1 | 2020-04-02T12:37:58.000Z | 2020-04-02T12:37:58.000Z | tests/typelist_basic.cpp | surrealwaffle/yymp | 662def34a298bf2992bf429e26bc35605906897b | [
"BSL-1.0"
] | null | null | null | tests/typelist_basic.cpp | surrealwaffle/yymp | 662def34a298bf2992bf429e26bc35605906897b | [
"BSL-1.0"
] | 1 | 2018-11-22T10:36:37.000Z | 2018-11-22T10:36:37.000Z | // SPDX-License-Identifier: BSL-1.0
#include <cstdint>
#include <concepts>
#include <optional>
#include <type_traits>
#include <yymp/typelist.hpp>
using namespace yymp;
using ::std::same_as;
using ::std::index_sequence;
struct custom;
template< class... > struct Template;
template<typename T>
concept has_nested_type = requires { typename T::type; };
/* **********************
* Categorization traits:
* is_typelist,
* is_empty_typelist,
* is_nonempty_typelist
*/
static_assert(is_typelist_v<typelist<>>);
static_assert(is_empty_typelist_v<typelist<>>);
static_assert(!is_nonempty_typelist_v<typelist<>>);
static_assert(is_typelist_v<typelist<custom>>);
static_assert(!is_empty_typelist_v<typelist<custom>>);
static_assert(is_nonempty_typelist_v<typelist<custom>>);
static_assert(is_typelist_v<typelist<void, custom>>);
static_assert(!is_empty_typelist_v<typelist<void, custom>>);
static_assert(is_nonempty_typelist_v<typelist<void, custom>>);
static_assert(!is_typelist_v<custom>);
static_assert(!is_empty_typelist_v<custom>);
static_assert(!is_nonempty_typelist_v<custom>);
/* **************
* typelist_first
*/
static_assert(!has_nested_type<typelist_first<typelist<>>>);
static_assert(same_as<typelist_first_t<typelist<custom>>, custom>);
static_assert(same_as<typelist_first_t<typelist<custom, void, char>>, custom>);
/* ******************
* retain_as_typelist
*/
static_assert(same_as<retain_as_typelist_t<typelist<>>, typelist<>>);
static_assert(same_as<retain_as_typelist_t<typelist<custom>>, typelist<custom>>);
static_assert(same_as<retain_as_typelist_t<custom>, typelist<custom>>);
/* *************
* typelist_size
*/
static_assert(typelist_size_v<typelist<>> == 0);
static_assert(typelist_size_v<typelist<custom>> == 1);
static_assert(typelist_size_v<typelist<int, void, custom>> == 3);
static_assert(typelist_size_v<typelist<custom, custom, custom>> == 3);
/* ************************
* template_type_parameters
*/
static_assert(same_as<template_type_parameters_t<custom>, typelist<>>);
static_assert(same_as<
template_type_parameters_t<Template<int, char, void>>,
typelist<int, char, void>
>);
/* ************
* typelist_get
*/
static_assert(same_as<typelist_get_t<0, typelist<int, char, custom>>, int>);
static_assert(same_as<typelist_get_t<1, typelist<int, char, custom>>, char>);
static_assert(same_as<typelist_get_t<2, typelist<int, char, custom>>, custom>);
/* ***************
* typelist_select
*/
static_assert(same_as<
typelist_select_t<index_sequence<0, 1, 2>, typelist<int, char, custom>>,
typelist<int, char, custom>
>);
static_assert(same_as<
typelist_select_t<index_sequence<2, 0, 1>, typelist<int, char, custom>>,
typelist<custom, int, char>
>);
static_assert(same_as<
typelist_select_t<index_sequence<1, 2, 0>, typelist<int, char, custom>>,
typelist<char, custom, int>
>);
static_assert(same_as<
typelist_select_t<index_sequence<0, 2, 1>, typelist<int, char, custom>>,
typelist<int, custom, char>
>);
static_assert(same_as<
typelist_select_t<index_sequence<1, 0, 2>, typelist<int, char, custom>>,
typelist<char, int, custom>
>);
static_assert(same_as<
typelist_select_t<index_sequence<2, 1, 0>, typelist<int, char, custom>>,
typelist<custom, char, int>
>);
static_assert(same_as<
typelist_select_t<index_sequence<0, 1>, typelist<int, char, custom>>,
typelist<int, char>
>);
static_assert(same_as<
typelist_select_t<index_sequence<0, 2>, typelist<int, char, custom>>,
typelist<int, custom>
>);
static_assert(same_as<
typelist_select_t<index_sequence<1, 0>, typelist<int, char, custom>>,
typelist<char, int>
>);
static_assert(same_as<
typelist_select_t<index_sequence<1, 2>, typelist<int, char, custom>>,
typelist<char, custom>
>);
static_assert(same_as<
typelist_select_t<index_sequence<2, 0>, typelist<int, char, custom>>,
typelist<custom, int>
>);
static_assert(same_as<
typelist_select_t<index_sequence<2, 1>, typelist<int, char, custom>>,
typelist<custom, char>
>);
static_assert(same_as<
typelist_select_t<index_sequence<0>, typelist<int, char, custom>>,
typelist<int>
>);
static_assert(same_as<
typelist_select_t<index_sequence<1>, typelist<int, char, custom>>,
typelist<char>
>);
static_assert(same_as<
typelist_select_t<index_sequence<2>, typelist<int, char, custom>>,
typelist<custom>
>);
static_assert(same_as<
typelist_select_t<index_sequence<>, typelist<int, char, custom>>,
typelist<>
>);
/* *************
* typelist_join
*/
static_assert(same_as<typelist_join_t<>, typelist<>>);
static_assert(same_as<typelist_join_t<typelist<int>>, typelist<int>>);
static_assert(same_as<
typelist_join_t<typelist<int>, typelist<char>>,
typelist<int, char>
>);
static_assert(same_as<
typelist_join_t<
typelist<int>,
typelist<char>,
typelist<custom>
>, typelist<int, char, custom>
>);
static_assert(same_as<
typelist_join_t<
typelist<>, typelist<>,
typelist<int>, typelist<>, typelist<>,
typelist<char>, typelist<>, typelist<>,
typelist<custom>, typelist<>, typelist<>
>, typelist<int, char, custom>
>);
/* ***************
* typelist_append
*/
static_assert(same_as<typelist_append_t<typelist<>, int>, typelist<int>>);
static_assert(same_as<typelist_append_t<typelist<int>, char>, typelist<int, char>>);
/* ********************************************************
* typelist_transform/typelist_expand/typelist_expand_trait
*/
static_assert(same_as<
typelist_transform_t<std::add_pointer, typelist<int, char, custom>>,
typelist<int*, char*, custom*>
>);
static_assert(same_as<
typelist_expand_t<Template, typelist<int, char, custom>>,
Template<int, char, custom>
>);
static_assert(same_as<
typelist_expand_trait_t<
::std::is_same,
typelist<int, int>
>, ::std::true_type
>);
static_assert(same_as<
typelist_expand_trait_t<
::std::is_same,
typelist<int, void>
>, ::std::false_type
>);
/* ******************************************************************
* typelist_accumulate
*/
static_assert(same_as<
typelist_accumulate_t<
typelist_append,
typelist<>,
typelist<int, char, custom>
>, typelist<int, char, custom>
>);
/* ******************************************************************
* typelist_all_of/typelist_any_of/typelist_none_of/typelist_count_of
*/
static_assert(typelist_all_of_v<custom, typelist<>>);
static_assert(!typelist_all_of_v<custom, typelist<int, char, custom>>);
static_assert(!typelist_all_of_v<void, typelist<int, char, custom>>);
static_assert(!typelist_any_of_v<custom, typelist<>>);
static_assert(typelist_any_of_v<custom, typelist<int, char, custom>>);
static_assert(!typelist_any_of_v<void, typelist<int, char, custom>>);
static_assert(typelist_none_of_v<custom, typelist<>>);
static_assert(!typelist_none_of_v<custom, typelist<int, char, custom>>);
static_assert(typelist_none_of_v<void, typelist<int, char, custom>>);
static_assert(typelist_count_of_v<custom, typelist<>> == 0);
static_assert(typelist_count_of_v<custom, typelist<int, char, custom>> == 1);
static_assert(typelist_count_of_v<custom, typelist<int, custom, custom>> == 2);
static_assert(typelist_count_of_v<void, typelist<int, char, custom>> == 0);
/* ***************
* typelist_all_where/typelist_any_where/typelist_none_where/typelist_count_where
*/
static_assert(typelist_all_where_v<std::is_pointer, typelist<>>);
static_assert(typelist_all_where_v<std::is_pointer, typelist<int*, char*, custom*>>);
static_assert(!typelist_all_where_v<std::is_pointer, typelist<int*, char*, custom>>);
static_assert(!typelist_all_where_v<std::is_pointer, typelist<int, char, custom>>);
static_assert(!typelist_any_where_v<std::is_pointer, typelist<>>);
static_assert(typelist_any_where_v<std::is_pointer, typelist<int*, char*, custom*>>);
static_assert(typelist_any_where_v<std::is_pointer, typelist<int*, char*, custom>>);
static_assert(!typelist_any_where_v<std::is_pointer, typelist<int, char, custom>>);
static_assert(typelist_none_where_v<std::is_pointer, typelist<>>);
static_assert(!typelist_none_where_v<std::is_pointer, typelist<int*, char*, custom*>>);
static_assert(!typelist_none_where_v<std::is_pointer, typelist<int*, char*, custom>>);
static_assert(typelist_none_where_v<std::is_pointer, typelist<int, char, custom>>);
static_assert(typelist_count_where_v<std::is_pointer, typelist<>> == 0);
static_assert(typelist_count_where_v<std::is_pointer, typelist<int*, char*, custom*>> == 3);
static_assert(typelist_count_where_v<std::is_pointer, typelist<int*, char, custom*>> == 2);
static_assert(typelist_count_where_v<std::is_pointer, typelist<int, char, custom>> == 0);
/* *******************
* typelist_indices_of
*/
static_assert(same_as<
typelist_indices_of_t<custom, typelist<>>,
index_sequence<>
>);
static_assert(same_as<
typelist_indices_of_t<custom, typelist<int, char>>,
index_sequence<>
>);
static_assert(same_as<
typelist_indices_of_t<custom, typelist<custom, int, char>>,
index_sequence<0>
>);
static_assert(same_as<
typelist_indices_of_t<custom, typelist<int, custom, char>>,
index_sequence<1>
>);
static_assert(same_as<
typelist_indices_of_t<custom, typelist<int, char, custom>>,
index_sequence<2>
>);
static_assert(same_as<
typelist_indices_of_t<custom, typelist<custom, int, custom>>,
index_sequence<0, 2>
>);
/* **********************
* typelist_indices_where
*/
static_assert(same_as<
typelist_indices_where_t<std::is_pointer, typelist<>>,
index_sequence<>
>);
static_assert(same_as<
typelist_indices_where_t<std::is_pointer, typelist<int, char>>,
index_sequence<>
>);
static_assert(same_as<
typelist_indices_where_t<std::is_pointer, typelist<custom*, int, char>>,
index_sequence<0>
>);
static_assert(same_as<
typelist_indices_where_t<std::is_pointer, typelist<int, custom*, char>>,
index_sequence<1>
>);
static_assert(same_as<
typelist_indices_where_t<std::is_pointer, typelist<int, char, custom*>>,
index_sequence<2>
>);
static_assert(same_as<
typelist_indices_where_t<std::is_pointer, typelist<int*, custom*, char>>,
index_sequence<0, 1>
>);
/* ***************
* typelist_filter
*/
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<>>,
typelist<>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int, char, custom>>,
typelist<>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int*, char, custom>>,
typelist<int*>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int, char*, custom>>,
typelist<char*>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int, char, custom*>>,
typelist<custom*>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int*, char, custom*>>,
typelist<int*, custom*>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int*, char*, custom>>,
typelist<int*, char*>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int, char*, custom*>>,
typelist<char*, custom*>
>);
static_assert(same_as<
typelist_filter_t<std::is_pointer, typelist<int*, char*, custom*>>,
typelist<int*, char*, custom*>
>);
/* **************************
* typelist_filter_duplicates
*/
static_assert(same_as<
typelist_filter_duplicates_t<typelist<>>,
typelist<>
>);
static_assert(same_as<
typelist_filter_duplicates_t<typelist<int, char, custom>>,
typelist<int, char, custom>
>);
static_assert(same_as<
typelist_filter_duplicates_t<typelist<int, int, char, char, custom, custom>>,
typelist<int, char, custom>
>);
static_assert(same_as<
typelist_filter_duplicates_t<typelist<int, char, int, custom, char, custom>>,
typelist<int, char, custom>
>);
/* *****************
* typelist_group_by
*/
static_assert(same_as<
typelist_group_by_t<std::is_pointer, typelist<>>,
typelist<>
>);
static_assert(same_as<
typelist_group_by_t<std::is_pointer, typelist<int, char, custom*>>,
typelist<typelist<int, char>, typelist<custom*>>
>);
static_assert(same_as<
typelist_group_by_t<std::is_pointer, typelist<int*, char, custom>>,
typelist<typelist<int*>, typelist<char, custom>>
>);
/* *******************
* for_each (typelist)
*/
template<::std::size_t I>
class basic_unary_test_function
{
private:
::std::size_t index = 0;
public:
std::optional<::std::size_t> result;
template<typename T>
constexpr auto operator()(type_marker<T>) noexcept
{
if (index == I)
result = std::make_optional(sizeof(T));
++index;
}
};
static_assert(
for_each(
typelist<std::int8_t, std::int16_t, std::int32_t>{},
basic_unary_test_function<0>{}
).result.value() == sizeof(std::int8_t)
);
static_assert(
for_each(
typelist<std::int8_t, std::int16_t, std::int32_t>{},
basic_unary_test_function<1>{}
).result.value() == sizeof(std::int16_t)
);
static_assert(
for_each(
typelist<std::int8_t, std::int16_t, std::int32_t>{},
basic_unary_test_function<2>{}
).result.value() == sizeof(std::int32_t)
);
/* **********************************
* unique_in_typelist/any_in_typelist
*/
static_assert(!unique_among<void>);
static_assert(!unique_among<void, int, char, custom>);
static_assert(!unique_among<void, int, char, custom, void, void>);
static_assert(unique_among<void, int, char, custom, void>);
static_assert(!any_among<void>);
static_assert(!any_among<void, int, char, custom>);
static_assert(any_among<void, int, char, custom, void, void>);
static_assert(any_among<void, int, char, custom, void>);
int main()
{
return 0;
} | 29.366525 | 92 | 0.697136 | surrealwaffle |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.