hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de28e9148aaf22d5872ca93b88d07209e5900495 | 1,727 | cpp | C++ | runtime/mkw/v2.0/bootstrap.cpp | riidefi/Pokey | 0b061312d7b4f8cf38bbe6317254262c646f6c89 | [
"MIT"
] | 10 | 2019-04-30T01:41:47.000Z | 2021-02-16T06:13:24.000Z | runtime/mkw/v2.0/bootstrap.cpp | riidefi/Pokey | 0b061312d7b4f8cf38bbe6317254262c646f6c89 | [
"MIT"
] | null | null | null | runtime/mkw/v2.0/bootstrap.cpp | riidefi/Pokey | 0b061312d7b4f8cf38bbe6317254262c646f6c89 | [
"MIT"
] | 1 | 2020-06-04T12:49:12.000Z | 2020-06-04T12:49:12.000Z | #include "standalone.hpp"
#include <libpokey/hooks.h>
// filepaths from all regions combined
static const char* BootStrapFilePaths[] = {
"/Boot/Strap/jp/jp.szs", // 0
"/Boot/Strap/eu/English.szs", // 1
"/Boot/Strap/eu/German.szs", // 2
"/Boot/Strap/eu/French.szs", // 3
// "/Boot/Strap/eu/Spanish_US.szs"
"/Boot/Strap/eu/Spanish_EU.szs", // 4
"/Boot/Strap/eu/Italian.szs", // 5
"/Boot/Strap/eu/Dutch.szs" // 6
};
const char** getBootStrapFilePaths()
{
return BootStrapFilePaths;
}
u8* bootStrapLoad(System::SystemManager* pManager, char* path, EGG::Heap* heap, bool allocTop, u32* fsizeOutput)
{
DVDFileInfo fInfo;
if (DVDOpen(path, &fInfo))
goto out;
// Support for US Spanish
if (!strcmp(path, BootStrapFilePaths[4]))
{
path = (char*)"/Boot/Strap/us/Spanish_US.szs";
if (DVDOpen(path, &fInfo))
goto out;
}
// Support for US French
if (!strcmp(path, BootStrapFilePaths[3]))
{
path = (char*)"/Boot/Strap/us/French.szs";
if (DVDOpen(path, &fInfo))
goto out;
}
path = (char*)BootStrapFilePaths[1]; // Default to EU English
if (DVDOpen(path, &fInfo))
goto out;
path = (char*)"/Boot/Strap/us/English.szs"; // US english
if (DVDOpen(path, &fInfo))
goto out;
path = (char*)BootStrapFilePaths[0]; // Japan
if (DVDOpen(path, &fInfo))
goto out;
// Fatal: file doesn't exist
{
u32 fg = 0x000000ff, bg = 0xffffffff;
Fatal(&fg, &bg, "Failed to load bootstrap file!\n");
return 0;
}
out:
DVDClose(&fInfo);
return pManager->ripFromDisc((const char*)path, heap, allocTop, fsizeOutput);
}
// Overwrite load to game table.. needs to load to r25 not r3
//PokeyCall(0x80007500, getBootStrapFilePaths);
// Overwrite call to rip file
PokeyCall(0x80007528, bootStrapLoad);
| 23.657534 | 112 | 0.673422 | riidefi |
de2b24b6ab2f9d13be56bca32fa4b38c0e233772 | 698 | cpp | C++ | Manufacture/glass/Glassify-master/include/MotorThread.cpp | ReEn-Neom/ReEn.Neom-source-code- | 11ec834d5eac5a5a63c71f6b41107769dafc591c | [
"MIT"
] | null | null | null | Manufacture/glass/Glassify-master/include/MotorThread.cpp | ReEn-Neom/ReEn.Neom-source-code- | 11ec834d5eac5a5a63c71f6b41107769dafc591c | [
"MIT"
] | null | null | null | Manufacture/glass/Glassify-master/include/MotorThread.cpp | ReEn-Neom/ReEn.Neom-source-code- | 11ec834d5eac5a5a63c71f6b41107769dafc591c | [
"MIT"
] | null | null | null | #include <wiringPi.h>
#include <thread>
//#include <cstdlib>
#include <iostream>
#include "MotorThread.h"
//#include "libServo.h"
//#include "libServo.cpp"
void MotorThread::run()
{
while(true){
m_state=stateptr->getState();
std::cout << "MOTOR GOT STATE >> " << m_state << std::endl;
if(m_state==1)
{
servoptr->moveGreen();
//std::this_thread::sleep_for(std::chrono::milliseconds(m_delay));
}
if (m_state==2)
{
servoptr->moveBrown();
//std::this_thread::sleep_for(std::chrono::milliseconds(m_delay));
}
if (m_state==3)
{
servoptr->moveClear();
//std::this_thread::sleep_for(std::chrono::milliseconds(m_delay));
}
m_state==0;
{
servoptr->moveClear();
}
}
}
| 18.368421 | 68 | 0.65043 | ReEn-Neom |
de2bb30cb5a58184d70f4d07c3c6ca056aeddab0 | 82 | hpp | C++ | src/elona/main.hpp | XrosFade/ElonaFoobar | c33880080e0b475103ae3ea7d546335f9d4abd02 | [
"MIT"
] | 84 | 2018-03-03T02:44:32.000Z | 2019-07-14T16:16:24.000Z | src/elona/main.hpp | XrosFade/ElonaFoobar | c33880080e0b475103ae3ea7d546335f9d4abd02 | [
"MIT"
] | 685 | 2018-02-27T04:31:17.000Z | 2019-07-12T13:43:00.000Z | src/elona/main.hpp | XrosFade/ElonaFoobar | c33880080e0b475103ae3ea7d546335f9d4abd02 | [
"MIT"
] | 23 | 2019-07-26T08:52:38.000Z | 2021-11-09T09:21:58.000Z | #pragma once
namespace elona
{
int run(int argc, const char* const* argv);
}
| 7.454545 | 43 | 0.670732 | XrosFade |
de2fd1c31bfd646a003e2ff649a64c640849904d | 2,754 | cpp | C++ | Miscellaneous/frogthree.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2020-10-16T18:14:30.000Z | 2020-10-16T18:14:30.000Z | Miscellaneous/frogthree.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | null | null | null | Miscellaneous/frogthree.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2021-01-06T04:45:38.000Z | 2021-01-06T04:45:38.000Z | #define __USE_MINGW_ANSI_STDIO 0
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <stack>
#include <deque>
#include <string.h>
#include <sstream>
#include <bitset>
#include <math.h>
#include <assert.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
template <class T>
using ordered_set = __gnu_pbds::tree<T, __gnu_pbds::null_type, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;
template <class T>
using ordered_multiset = __gnu_pbds::tree<T, __gnu_pbds::null_type, less_equal<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;
#define PI atan2(0, -1)
#define epsilon 1e-9
#define INF 5000000000000000000
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
template <typename T, bool isMin>
struct ConvexHullTrick{
using P = pair<T, T>;
deque<P> L;
inline T getY(const P &a,const T &x){ return a.first*x+a.second; }
inline bool check(const P &a,const P &b,const P &c){
return (b.first-a.first)*(c.second-b.second)
>= (b.second-a.second)*(c.first-b.first);
}
void add(T a, T b){
if(!isMin) a *= -1, b*= -1;
P line(a, b);
if(!L.empty() && L.back().first == a){
line.second = min(line.second, L.back().second);
L.pop_back();
}
while(L.size() > 1 && check(L[L.size()-2], L[L.size()-1], line)) L.pop_back();
L.emplace_back(line);
}
T get(T x){
if(L.empty()) return isMin ? INF : -INF;
int lo = -1, hi = L.size()-1;
while(lo+1 < hi){
int mid = (lo+hi)/2;
if(getY(L[mid], x) >= getY(L[mid+1],x)) lo = mid;
else hi = mid;
}
return (!isMin ? -1 : 1)*getY(L[hi], x);
}
};
int N;
long long C, arr [1000010];
ConvexHullTrick<long long, true> cht;
int main(){
//freopen("sort.in", "r", stdin); freopen("sort.out", "w", stdout);
ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(10);
cin >> N >> C;
for(int i = 0; i < N; i++) cin >> arr[i];
cht.add(-2*arr[0], arr[0]*arr[0]);
for(int i = 1; i < N; i++){
long long val = cht.get(arr[i])+arr[i]*arr[i]+C;
if(i == N-1) cout << val << '\n';
else cht.add(-2*arr[i], val+arr[i]*arr[i]);
}
return 0;
}
/******************************
Kateba ii dake no hanashi darou
Success is only a victory away
- No Game No Life Opening
******************************/
| 28.989474 | 155 | 0.595134 | hardik0899 |
de331995ccb829155f588de8da5537d04ddaa885 | 3,694 | hpp | C++ | src/Core/TransactionExtra.hpp | mygirl8893/evo | c90f69ad6132c426042749ff3fe4174d22aa63b2 | [
"MIT"
] | 1 | 2019-05-20T01:00:40.000Z | 2019-05-20T01:00:40.000Z | src/Core/TransactionExtra.hpp | mygirl8893/evo | c90f69ad6132c426042749ff3fe4174d22aa63b2 | [
"MIT"
] | 4 | 2018-05-07T07:15:53.000Z | 2018-06-01T19:35:46.000Z | src/Core/TransactionExtra.hpp | mygirl8893/evo | c90f69ad6132c426042749ff3fe4174d22aa63b2 | [
"MIT"
] | 10 | 2018-05-09T10:45:07.000Z | 2020-01-11T17:21:28.000Z | #pragma once
#include <boost/variant.hpp>
#include <vector>
#include "CryptoNote.hpp"
#include "seria/ISeria.hpp"
namespace cryptonote {
enum { TX_EXTRA_PADDING_MAX_COUNT = 255, TX_EXTRA_NONCE_MAX_COUNT = 255, TX_EXTRA_NONCE_PAYMENT_ID = 0x00 };
struct TransactionExtraPadding {
size_t size = 0;
enum { tag = 0x00 };
};
struct TransactionExtraPublicKey {
crypto::PublicKey public_key;
enum { tag = 0x01 };
};
struct TransactionExtraNonce {
BinaryArray nonce;
enum { tag = 0x02 };
};
struct TransactionExtraMergeMiningTag {
size_t depth = 0;
crypto::Hash merkle_root;
enum { tag = 0x03 };
};
// tx_extra_field format, except tx_extra_padding and tx_extra_pub_key:
// varint tag;
// varint size;
// varint data[];
typedef boost::variant<TransactionExtraPadding, TransactionExtraPublicKey, TransactionExtraNonce,
TransactionExtraMergeMiningTag>
TransactionExtraField;
bool parse_transaction_extra(const BinaryArray &tx_extra, std::vector<TransactionExtraField> &tx_extra_fields);
bool write_transaction_extra(BinaryArray &tx_extra, const std::vector<TransactionExtraField> &tx_extra_fields);
crypto::PublicKey get_transaction_public_key_from_extra(const BinaryArray &tx_extra);
bool add_transaction_public_key_to_extra(BinaryArray &tx_extra, const crypto::PublicKey &tx_pub_key);
bool add_extra_nonce_to_transaction_extra(BinaryArray &tx_extra, const BinaryArray &extra_nonce);
void set_payment_id_to_transaction_extra_nonce(BinaryArray &extra_nonce, const crypto::Hash &payment_id);
bool get_payment_id_from_transaction_extra_nonce(const BinaryArray &extra_nonce, crypto::Hash &payment_id);
bool append_merge_mining_tag_to_extra(BinaryArray &tx_extra, const TransactionExtraMergeMiningTag &mm_tag);
bool get_merge_mining_tag_from_extra(const BinaryArray &tx_extra, TransactionExtraMergeMiningTag &mm_tag);
bool get_payment_id_from_tx_extra(const BinaryArray &extra, crypto::Hash &payment_id);
class TransactionExtra {
public:
TransactionExtra() {}
TransactionExtra(const BinaryArray &extra) { parse(extra); }
bool parse(const BinaryArray &extra) {
m_fields.clear();
return cryptonote::parse_transaction_extra(extra, m_fields);
}
template<typename T>
bool get(T &value) const {
auto it = find(typeid(T));
if (it == m_fields.end()) {
return false;
}
value = boost::get<T>(*it);
return true;
}
template<typename T>
void set(const T &value) {
auto it = find(typeid(T));
if (it != m_fields.end()) {
*it = value;
} else {
m_fields.push_back(value);
}
}
template<typename T>
void append(const T &value) {
m_fields.push_back(value);
}
bool get_public_key(crypto::PublicKey &pk) const {
cryptonote::TransactionExtraPublicKey extra_pk;
if (!get(extra_pk)) {
return false;
}
pk = extra_pk.public_key;
return true;
}
BinaryArray serialize() const {
BinaryArray extra;
write_transaction_extra(extra, m_fields);
return extra;
}
private:
std::vector<cryptonote::TransactionExtraField>::const_iterator find(const std::type_info &t) const {
return std::find_if(
m_fields.begin(), m_fields.end(), [&t](const cryptonote::TransactionExtraField &f) { return t == f.type(); });
}
std::vector<cryptonote::TransactionExtraField>::iterator find(const std::type_info &t) {
return std::find_if(
m_fields.begin(), m_fields.end(), [&t](const cryptonote::TransactionExtraField &f) { return t == f.type(); });
}
std::vector<cryptonote::TransactionExtraField> m_fields;
};
}
namespace seria {
class ISeria;
void ser(cryptonote::TransactionExtraMergeMiningTag &v, ISeria &s);
}
| 30.783333 | 117 | 0.73281 | mygirl8893 |
de337a4c7dc31a4813842329f7ad3796967d3438 | 2,123 | cpp | C++ | Visual Mercutio/zBaseLib/PSS_Splitter.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Visual Mercutio/zBaseLib/PSS_Splitter.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Visual Mercutio/zBaseLib/PSS_Splitter.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /****************************************************************************
* ==> PSS_Splitter --------------------------------------------------------*
****************************************************************************
* Description : Provides a splitter *
* Developer : Processsoft *
****************************************************************************/
#include <StdAfx.h>
#include "PSS_Splitter.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//---------------------------------------------------------------------------
// Message map
//---------------------------------------------------------------------------
#ifdef _WIN32
BEGIN_MESSAGE_MAP(PSS_Splitter, PSS_OutlookSplitterWnd)
#else
// in 16bit there is a bug, therefore do not accept moving splitter
BEGIN_MESSAGE_MAP(PSS_Splitter, CSplitterWnd)
//{{AFX_MSG_MAP(ZISplitter)
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
//}}AFX_MSG_MAP
#endif
END_MESSAGE_MAP()
//---------------------------------------------------------------------------
// PSS_Splitter
//---------------------------------------------------------------------------
PSS_Splitter::PSS_Splitter() :
PSS_OutlookSplitterWnd()
{}
//---------------------------------------------------------------------------
PSS_Splitter::~PSS_Splitter()
{}
//---------------------------------------------------------------------------
#ifndef _WIN32
void PSS_Splitter::OnLButtonDown(UINT nFlags, CPoint point)
{
// in 16bit there is a bug, therefore do not accept moving splitter
//CWnd::OnLButtonDown(nFlags, point);
}
#endif
//---------------------------------------------------------------------------
#ifndef _WIN32
void PSS_Splitter::OnMouseMove(UINT nFlags, CPoint point)
{
// in 16bit there is a bug, therefore do not accept moving splitter
//CWnd::OnMouseMove(nFlags, point);
}
#endif
//---------------------------------------------------------------------------
| 37.910714 | 78 | 0.370231 | Jeanmilost |
de340e9fd170a18b5163c178219e094171ac96ed | 7,769 | cpp | C++ | main/source/cl_dll/util.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 27 | 2015-01-05T19:25:14.000Z | 2022-03-20T00:34:34.000Z | main/source/cl_dll/util.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 9 | 2015-01-14T06:51:46.000Z | 2021-03-19T12:07:18.000Z | main/source/cl_dll/util.cpp | fmoraw/NS | 6c3ae93ca7f929f24da4b8f2d14ea0602184cf08 | [
"Unlicense"
] | 5 | 2015-01-11T10:31:24.000Z | 2021-01-06T01:32:58.000Z | /***
*
* Copyright (c) 1999, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
//
// util.cpp
//
// implementation of class-less helper functions
//
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "hud.h"
#include "cl_util.h"
#include "common/cl_entity.h"
#include <string.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h
#endif
#include "pm_shared/pm_defs.h"
#include "pm_shared/pm_shared.h"
#include "pm_shared/pm_movevars.h"
extern playermove_t *pmove;
extern float HUD_GetFOV( void );
vec3_t vec3_origin( 0, 0, 0 );
extern vec3_t v_angles;
//double sqrt(double x);
//
//float Length(const float *v)
//{
// int i;
// float length;
//
// length = 0;
// for (i=0 ; i< 3 ; i++)
// length += v[i]*v[i];
// length = sqrt (length); // FIXME
//
// return length;
//}
//
//void VectorAngles( const float *forward, float *angles )
//{
// float tmp, yaw, pitch;
//
// if (forward[1] == 0 && forward[0] == 0)
// {
// yaw = 0;
// if (forward[2] > 0)
// pitch = 90;
// else
// pitch = 270;
// }
// else
// {
// yaw = (atan2(forward[1], forward[0]) * 180 / M_PI);
// if (yaw < 0)
// yaw += 360;
//
// tmp = sqrt (forward[0]*forward[0] + forward[1]*forward[1]);
// pitch = (atan2(forward[2], tmp) * 180 / M_PI);
// if (pitch < 0)
// pitch += 360;
// }
//
// angles[0] = pitch;
// angles[1] = yaw;
// angles[2] = 0;
//}
//
//float VectorNormalize (float *v)
//{
// float length, ilength;
//
// length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
// length = sqrt (length); // FIXME
//
// if (length)
// {
// ilength = 1/length;
// v[0] *= ilength;
// v[1] *= ilength;
// v[2] *= ilength;
// }
//
// return length;
//
//}
//
//void VectorInverse ( float *v )
//{
// v[0] = -v[0];
// v[1] = -v[1];
// v[2] = -v[2];
//}
//
//void VectorScale (const float *in, float scale, float *out)
//{
// out[0] = in[0]*scale;
// out[1] = in[1]*scale;
// out[2] = in[2]*scale;
//}
//
//void VectorMA (const float *veca, float scale, const float *vecb, float *vecc)
//{
// vecc[0] = veca[0] + scale*vecb[0];
// vecc[1] = veca[1] + scale*vecb[1];
// vecc[2] = veca[2] + scale*vecb[2];
//}
int ScreenHeight()
{
// CGC: Replace code when ready to fix overview map
//int theViewport[4];
//gHUD.GetViewport(theViewport);
//return theViewport[3];
return gHUD.m_scrinfo.iHeight;
}
// ScreenWidth returns the width of the screen, in pixels
//#define ScreenWidth ( int theViewport[4]; gHUD.GetViewport(theViewport); return theViewport[2]; )
int ScreenWidth()
{
//int theViewport[4];
//gHUD.GetViewport(theViewport);
//return theViewport[2];
return gHUD.m_scrinfo.iWidth;
}
/*
HSPRITE SPR_Load(const char* inSpriteName)
{
HSPRITE theSpriteHandle = gEngfuncs.pfnSPR_Load(inSpriteName);
// Check for "Can't allocate 128 HUD sprites" crash
ASSERT(theSpriteHandle < 128);
return theSpriteHandle;
}*/
//-----------------------------------------------------------------------------
// Purpose:
// Given a field of view and mouse/screen positions as well as the current
// render origin and angles, returns a unit vector through the mouse position
// that can be used to trace into the world under the mouse click pixel.
// Input : fov -
// mousex -
// mousey -
// screenwidth -
// screenheight -
// vecRenderAngles -
// c_x -
// vpn -
// vup -
// 360.0 -
//-----------------------------------------------------------------------------
void CreatePickingRay( int mousex, int mousey, Vector& outVecPickingRay )
{
float dx, dy;
float c_x, c_y;
float dist;
Vector vpn, vup, vright;
// char gDebugMessage[256];
float fovDegrees = gHUD.m_iFOV;
//cl_entity_s* theLocalEntity = gEngfuncs.GetLocalPlayer();
//Vector vecRenderOrigin = theLocalEntity->origin;
//Vector vecRenderAngles = theLocalEntity->angles;
//Vector vecRenderAngles;
vec3_t vecRenderAngles;
//gEngfuncs.GetViewAngles((float*)vecRenderAngles);
VectorCopy(v_angles, vecRenderAngles);
//vec3_t theForward, theRight, theUp;
//AngleVectors(v_angles, theForward, theRight, theUp);
//ASSERT(v_angles.x == vecRenderAngles.x);
//ASSERT(v_angles.y == vecRenderAngles.y);
//ASSERT(v_angles.z == vecRenderAngles.z);
c_x = ScreenWidth() / 2;
c_y = ScreenHeight() / 2;
dx = (float)mousex - c_x;
// Invert Y
dy = c_y - (float)mousey;
// sprintf(gDebugMessage, "inMouseX/Y: %d/%d, dx/dy = %d/%d", (int)mousex, (int)mousey, (int)dx, (int)dy);
// CenterPrint(gDebugMessage);
// Convert view plane distance
dist = c_x / tan( M_PI * fovDegrees / 360.0 );
// Decompose view angles
AngleVectors( vecRenderAngles, vpn, vright, vup );
// Offset forward by view plane distance, and then by pixel offsets
outVecPickingRay = vpn * dist + vright * ( dx ) + vup * ( dy );
//sprintf(gDebugMessage, "outVecPickingRay: %.0f, %.0f, %.0f", outVecPickingRay.x, outVecPickingRay.y, outVecPickingRay.z);
//CenterPrint(gDebugMessage);
// Convert to unit vector
VectorNormalize( outVecPickingRay );
}
void FillRGBAClipped(vgui::Panel* inPanel, int inStartX, int inStartY, int inWidth, int inHeight, int r, int g, int b, int a)
{
int thePanelXPos, thePanelYPos;
inPanel->getPos(thePanelXPos, thePanelYPos);
int thePanelWidth, thePanelHeight;
inPanel->getSize(thePanelWidth, thePanelHeight);
// Clip starting point
inStartX = min(max(0, inStartX), thePanelWidth-1);
inStartY = min(max(0, inStartY), thePanelHeight-1);
// Clip width if it goes too far
ASSERT(inWidth >= 0);
ASSERT(inHeight >= 0);
if(inStartX + inWidth >= thePanelWidth)
{
inWidth = max(0, thePanelWidth - inStartX);
}
if(inStartY + inHeight >= thePanelHeight)
{
inHeight = max(0, thePanelHeight - inStartY);
}
// Now we can draw
FillRGBA(inStartX, inStartY, inWidth, inHeight, r, g, b, a);
}
HSPRITE LoadSprite(const char *pszName)
{
int i;
char sz[256];
if (ScreenWidth() < 640)
i = 320;
else
i = 640;
sprintf(sz, pszName, i);
return SPR_Load(sz);
}
bool LocalizeString(const char* inMessage, string& outputString)
{
#define kMaxLocalizedStringLength 1024
bool theSuccess = false;
char theInputString[kMaxLocalizedStringLength];
char theOutputString[kMaxLocalizedStringLength];
// Don't localize empty strings
if(strcmp(inMessage, ""))
{
if(*inMessage != '#')
{
sprintf(theInputString, "#%s", inMessage);
}
else
{
sprintf(theInputString, "%s", inMessage);
}
if((CHudTextMessage::LocaliseTextString(theInputString, theOutputString, kMaxLocalizedStringLength) != NULL))
{
outputString = theOutputString;
if(theOutputString[0] != '#')
{
theSuccess = true;
}
else
{
string theTempString = theOutputString;
theTempString = theTempString.substr(1, theTempString.length());
outputString = theTempString;
}
}
else
{
outputString = string("err: ") + theInputString;
}
}
return theSuccess;
}
| 24.663492 | 126 | 0.604582 | fmoraw |
de3593ab1508ac91eba7bd889caff87e1e6a0703 | 2,088 | cpp | C++ | json_rest_test/Client.cpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | 1 | 2020-05-22T08:47:00.000Z | 2020-05-22T08:47:00.000Z | json_rest_test/Client.cpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | null | null | null | json_rest_test/Client.cpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | null | null | null | #include <tm_kit/infra/RealTimeApp.hpp>
#include <tm_kit/infra/Environments.hpp>
#include <tm_kit/infra/TerminationController.hpp>
#include <tm_kit/infra/DeclarativeGraph.hpp>
#include <tm_kit/basic/real_time_clock/ClockComponent.hpp>
#include <tm_kit/basic/SpdLoggingComponent.hpp>
#include <tm_kit/transport/CrossGuidComponent.hpp>
#include <tm_kit/transport/TLSConfigurationComponent.hpp>
#include <tm_kit/transport/MultiTransportRemoteFacilityManagingUtils.hpp>
#include <tm_kit/transport/SimpleIdentityCheckerComponent.hpp>
#include "Data.hpp"
using namespace dev::cd606::tm;
using Env = infra::Environment<
infra::CheckTimeComponent<false>
, infra::TrivialExitControlComponent
, basic::TimeComponentEnhancedWithSpdLogging<
basic::real_time_clock::ClockComponent
, false
>
, transport::CrossGuidComponent
, transport::TLSClientConfigurationComponent
, transport::AllNetworkTransportComponents
, transport::ClientSideSimpleIdentityAttacherComponent<
std::string, Req
>
>;
int main(int argc, char **argv) {
Env env;
bool useSsl = (argc>=2 && std::string_view(argv[1]) == "ssl");
if (useSsl) {
env.transport::TLSClientConfigurationComponent::setConfigurationItem(
transport::TLSClientInfoKey {
"localhost", 34567
}
, transport::TLSClientInfo {
"../grpc_interop_test/DotNetServer/server.crt"
, ""
, ""
}
);
}
for (int ii=0; ii<10; ++ii) {
Req req {
{"abc", "def"}
, 2.0
, decltype(req.tChoice) {std::in_place_index<0>, 1}
};
auto resp = transport::OneShotMultiTransportRemoteFacilityCall<Env>
::callWithProtocol<std::void_t, Req, Resp>
(
&env
, "json_rest://localhost:34567:user2:abcde:/test_facility"
, std::move(req)
, std::nullopt
, false
).get();
std::cout << resp << '\n';
}
} | 31.164179 | 77 | 0.621169 | cd606 |
de37255f5b9a56dec1a112ec3c95d5d573ec19e0 | 10,212 | cpp | C++ | videodecodethread.cpp | Whatchado/storyrecorder | a442ebf2f5f5920f965ec5c07fddeec38a2a7aab | [
"Zlib"
] | null | null | null | videodecodethread.cpp | Whatchado/storyrecorder | a442ebf2f5f5920f965ec5c07fddeec38a2a7aab | [
"Zlib"
] | null | null | null | videodecodethread.cpp | Whatchado/storyrecorder | a442ebf2f5f5920f965ec5c07fddeec38a2a7aab | [
"Zlib"
] | null | null | null | #include "videodecodethread.h"
#include <QTime>
#include <QElapsedTimer>
#include "video_image.h"
#include "log.h"
VideoDecodeThread::VideoDecodeThread(QObject *parent) :
QThread(parent)
{
is_Running=false;
doStop=false;
isPaused=false;
doPause=false;
vbuffer=NULL;
doSeek=-1;
got_audioframe=false;
got_videoframe=false;
}
void VideoDecodeThread::setFile(QString const &_filename)
{
filename=_filename;
play_start=0.0;
}
void VideoDecodeThread::setVideoBuffer(VideoBuffer *_videobuffer)
{
vbuffer=_videobuffer;
}
void VideoDecodeThread::seek(double _pos)
{
//log("VIDEODECODE","**************** seek %f\n",_pos);
if(_pos==-1) return;
if(!is_Running)
{
start();
}
doPause=true;
while(is_Running&&(!isPaused))
usleep(100);
while(is_Running&&(doSeek!=-1)) // wait if other seek in progress
usleep(100);
doSeek=_pos;
vbuffer->clear();
doPause=false;
while((doSeek!=-1)&&(is_Running))
usleep(100);
//log("VIDEODECODE","*END************ seek %f\n",_pos);
return;
}
void VideoDecodeThread::stop()
{
doStop=true;
}
void VideoDecodeThread::pause()
{
doPause=true;
while((!isPaused)&&(is_Running))
{
usleep(1000);
}
}
void VideoDecodeThread::waitTillStopped()
{
while(is_Running)
{
usleep(1000);
}
return;
}
void VideoDecodeThread::run()
{
log("VIDEODECODE","play_start=%f",play_start);
if(play_start)
{
doSeek=play_start;
}
else
doSeek=-1;
doStop=false;
doPause=false;
is_Running=true;
double current_time_offset=-1;
double seek_pos=0;
int errcode=0;
QTime t_start=QTime::currentTime();
char *filenameSrc=strdup(filename.toLocal8Bit().data());
AVCodecContext *pCodecCtx=NULL,*pCodecCtx_audio=NULL;
AVFormatContext *pFormatCtx = avformat_alloc_context();
AVCodec *pCodec=NULL,*pCodec_audio=NULL;
/*#ifdef __unix__
AVInputFormat *iformat = av_find_input_format("video4linux2");
#else
AVInputFormat *iformat = av_find_input_format("dshow");
#endif*/
AVInputFormat *iformat =NULL;
AVFrame *frame_audio = av_frame_alloc();
//AVDictionary *options=NULL;
//av_dict_set(&options, "framerate", "25", 0);
log("VIDEODECODE","--------------------------------OPEN------------------------------------------");
if(avformat_open_input(&pFormatCtx,filenameSrc,iformat,NULL) != 0) {errcode=-12;is_Running=false;return;};
//av_dict_free(&options);
if(avformat_find_stream_info(pFormatCtx,NULL) < 0) {errcode=-13;is_Running=false;return;};
av_dump_format(pFormatCtx, 0, filenameSrc, 0);
int videoStream = -1;
int audioStream = -1;
log("VIDEODECODE","numstreams:%i----------------------------",pFormatCtx->nb_streams);
for(int i=0; i < pFormatCtx->nb_streams; i++)
{
log("VIDEODECODE","coder_type=%i",(int)pFormatCtx->streams[i]->codec->codec_type);
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoStream = i;
}
else if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO)
{
audioStream = i;
}
}
log("VIDEODECODE","-------------------------------videostream found %i audio=%i ------------------------------",videoStream,audioStream);
if(videoStream == -1) {errcode=-14;is_Running=false;return;};
// video codec
pCodecCtx = pFormatCtx->streams[videoStream]->codec;
log("VIDEODECODE","codecid=%i",pCodecCtx);
pCodec =avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL) {printf("codec not found\n");errcode=-15;is_Running=false;return;}; //codec not found
if(avcodec_open2(pCodecCtx,pCodec,NULL) < 0) {errcode=-16;is_Running=false;return;};
// audio codec
if(audioStream>=0)
{
pCodecCtx_audio = pFormatCtx->streams[audioStream]->codec;
log("VIDEODECODE","audio codecid=%i",pCodecCtx_audio);
pCodec_audio =avcodec_find_decoder(pCodecCtx_audio->codec_id);
}
if(pCodec_audio==NULL) {printf("audio codec not found");}
else
{
log("VIDEODECODE","open audio codec");
if(avcodec_open2(pCodecCtx_audio,pCodec_audio,NULL) < 0) {errcode=-16;is_Running=false;return;};
}
uint8_t *buffer;
int numBytes;
VIDEOIMAGE frame(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt);
VIDEOIMAGE frameResize(640,360,AV_PIX_FMT_BGR24);
int res;
AVPacket packet;
//av_seek_frame(pFormatCtx,-1,pos_start*AV_TIME_BASE,AVSEEK_FLAG_BACKWARD);
t_start=QTime::currentTime();
QElapsedTimer timer;
timer.start();
double video_duration=double(pFormatCtx->duration)/AV_TIME_BASE;
if(video_duration)
{
emit durationChanged(video_duration);
log("VIDEODECODE","duration=%f",video_duration);
}
if(doSeek!=-1)
{
av_seek_frame(pFormatCtx,-1,doSeek*AV_TIME_BASE,AVSEEK_FLAG_BACKWARD);
seek_pos=doSeek;
doSeek=-1;
}
log("VIDEODECODE","************************* DECODING seek_pos=%f duration=%f*************************",seek_pos,video_duration);
while((res = av_read_frame(pFormatCtx,&packet))>=0)
{
double pts=0.0;
if(packet.dts != AV_NOPTS_VALUE) pts = packet.dts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base);
if(current_time_offset==-1) current_time_offset=pts;
double current_time=pts-current_time_offset;
// log("VIDEODECODE","frame[%i] %f (pts=%f dts=%f) (offset=%f)",packet.stream_index,current_time,
// packet.pts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base),
// packet.dts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base),current_time_offset);
//while(pts>double(timer.elapsed())/1000.0)
//{usleep(1000);};
if(packet.stream_index == videoStream)
{
int frameFinished=1;
avcodec_decode_video2(pCodecCtx,frame.data,&frameFinished,&packet);
//log("VIDEODECODE","%i",frameFinished);
if(frameFinished)
{
double pts2 = av_frame_get_best_effort_timestamp ( frame.data )*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base);
// TODO test for AV_NOPTS_VALUE
log("VIDEODECODE","- decoded video frame %f (pts=%f dts=%f) pts2=%f",current_time,
packet.pts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base),
packet.dts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base),pts2
);
if(pts2>=seek_pos)
{
int h=frame.width*9/16;
if(h>frame.height) h=frame.height;
frame.scale(frameResize,h);
char *ibuffer=NULL;
//QImage *img=frameResize.getQImage(&ibuffer);
Frame bframe(pts2,frameResize.getRawImage(),frameResize.width,frameResize.height);
vbuffer->addVideo(bframe);
if(doSeek!=-1) got_videoframe=true;
}
else log("VIDEODECODE","frame video skipped for seek");
av_free_packet(&packet);
}
}
else if(packet.stream_index == audioStream)
{
/* decode audio frame */
int decoded = packet.size;
int got_audio_frame = 0;
int ret = avcodec_decode_audio4(pCodecCtx_audio, frame_audio, &got_audio_frame, &packet);
if (ret < 0)
printf("Error decoding audio frame\n");
decoded = FFMIN(ret, packet.size);
if (got_audio_frame)
{
double packet_t = av_frame_get_best_effort_timestamp ( frame_audio )*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base);
log("VIDEODECODE","decoded audio frame t=%f",packet_t);
int samplesize=av_get_bytes_per_sample((AVSampleFormat )frame_audio->format);
size_t unpadded_linesize = frame_audio->nb_samples * samplesize;
int16_t *d16=(int16_t *)malloc(frame_audio->nb_samples*sizeof(int16_t));
if(samplesize==4)
{
for(int a=0;a<frame_audio->nb_samples;a++)
{
float* decoded_audio_data = reinterpret_cast<float*>(frame_audio->data[0]);
d16[a]=(32768)*decoded_audio_data[a];
}
}else if(samplesize==2)
{
for(int a=0;a<frame_audio->nb_samples;a++)
{
int16_t* decoded_audio_data = reinterpret_cast<int16_t*>(frame_audio->data[0]);
d16[a]=decoded_audio_data[a];
}
}
vbuffer->addAudio(packet_t,d16,frame_audio->nb_samples);
free(d16);
if(doSeek!=-1) got_audioframe=true;
}
}
while(vbuffer->isFull()&&(!doStop)&&(!doPause)&&(doSeek==-1))
{
usleep(1000);
}
while(doPause&&(!doStop)&&(doSeek==-1))
{
isPaused=true;
usleep(100);
}
isPaused=false;
if(doSeek!=-1)
{
got_audioframe=false;
got_videoframe=false;
log("VIDEODECODE","seek to %f",doSeek);
av_seek_frame(pFormatCtx,-1,doSeek*AV_TIME_BASE,AVSEEK_FLAG_BACKWARD);
avcodec_flush_buffers(pCodecCtx);
avcodec_flush_buffers(pCodecCtx_audio);
seek_pos=doSeek;
vbuffer->clear();
doSeek=-1;
}
if (doStop) break;
}
log("VIDEODECODE","videoplayer thread end rc=%i",res);
// set stop frame
Frame stopFrame;stopFrame.t=0.0;
vbuffer->addVideo(stopFrame);
av_free_packet(&packet);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
log("VIDEODECODE","videoplayer thread end doStop=%i",doStop);
doStop=false;
is_Running=false;
return;
}
| 33.592105 | 145 | 0.588915 | Whatchado |
de389052eedac016319f90c5a7060645048a6065 | 505 | cpp | C++ | cilkforrange/hi.cpp | sualehasif/llvmurop | 954f789c0fd4e2efe7dd385b26e92e880695dd94 | [
"MIT"
] | null | null | null | cilkforrange/hi.cpp | sualehasif/llvmurop | 954f789c0fd4e2efe7dd385b26e92e880695dd94 | [
"MIT"
] | null | null | null | cilkforrange/hi.cpp | sualehasif/llvmurop | 954f789c0fd4e2efe7dd385b26e92e880695dd94 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <cilk/cilk.h>
int functionwithuniquename(std::vector<int> v) {
int sum = 0;
cilk_for (auto x : v) {
sum += x;
std::cout << x << "\n";
}
/*
cilk_for (int i = 0; i < v.size(); i++) {
std::cout << v[i] << '\n';
}
*/
return sum;
}
int main()
{
std::vector<int> v;
for(int i = 0; i<100; i++){
v.push_back(i);
}
int x = functionwithuniquename(v);
std::cout << x << std::endl;
return 0;
}
| 16.290323 | 48 | 0.491089 | sualehasif |
de3c4c6c328d2f6f66cddaf09aadd757796f46b3 | 4,486 | hh | C++ | src/kinetics/SyntheticMomentSource.i.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/kinetics/SyntheticMomentSource.i.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/kinetics/SyntheticMomentSource.i.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*----------------------------------//
/**
* @file SyntheticMomentSource.i.hh
* @brief SyntheticMomentSource inline member definitions
* @author Jeremy Roberts
* @date Nov 15, 2012
*/
//---------------------------------------------------------------------------//
#ifndef detran_SYNTHETICMOMENTSOURCE_I_HH_
#define detran_SYNTHETICMOMENTSOURCE_I_HH_
namespace detran
{
//---------------------------------------------------------------------------//
inline double SyntheticMomentSource::source(const size_t cell,
const size_t group)
{
// Preconditions
Require(group < d_source.size());
Require(cell < d_source[0].size());
return d_source[group][cell];
}
//---------------------------------------------------------------------------//
inline double SyntheticMomentSource::source(const size_t cell,
const size_t group,
const size_t angle)
{
// Preconditions
Require(group < d_source.size());
Require(cell < d_source[0].size());
// Norm is 1/4pi or 1/2
return d_source[group][cell] * d_norm;
}
//---------------------------------------------------------------------------//
inline void SyntheticMomentSource::build(const double dt,
const vec_states &states,
const vec_precursors &precursors,
const size_t order)
{
// Preconditions
Require(order > 0);
Require(order <= 6);
// Ensure the state size is consistent with the order requested
size_t size_state = states.size();
Require(states.size() > 0);
Require(states.size() >= order);
// If the precursors are present, they must be the same size as the state
size_t size_precursor = precursors.size();
Require((size_precursor == size_state) || (size_precursor == 0));
// Number of precursors
size_t np = 0;
if (size_precursor) np = precursors[0]->number_precursor_groups();
// Material map
const detran_utilities::vec_int &mt = d_mesh->mesh_map("MATERIAL");
// Leading coefficient
double a_0 = bdf_coefs[order-1][0];
// Clear the source
for (size_t g = 0; g < d_material->number_groups(); ++g)
for (size_t cell = 0; cell < d_mesh->number_cells(); ++cell)
d_source[g][cell] = 0.0;
// Add all backward terms
for (size_t j = 0; j < order; ++j)
{
Assert(states[j]);
if (size_precursor)
{
Assert(precursors[j]);
}
// Skip the first entry, which is for the (n+1) term
double a_j = bdf_coefs[order-1][j + 1];
for (size_t g = 0; g < d_material->number_groups(); ++g)
{
// Add the flux term
double phi_factor = a_j / dt / d_material->velocity(g);
for (size_t cell = 0; cell < d_mesh->number_cells(); ++cell)
{
// std::cout << " phi factor=" << phi_factor
// << " phi = " << states[j]->phi(g)[cell]
// << " source = " << d_source[g][cell] << std::endl;
d_source[g][cell] += phi_factor * states[j]->phi(g)[cell];
}
// Add the precursor concentration, if applicable
if (size_precursor)
{
for (size_t i = 0; i < np; ++i)
{
double C_factor = a_j * d_material->lambda(i) /
(a_0 + dt * d_material->lambda(i));
for (size_t cell = 0; cell < d_mesh->number_cells(); ++cell)
{
d_source[g][cell] += C_factor *
d_material->chi_d(mt[cell], i, g) *
precursors[j]->C(i)[cell];
// std::cout << " C=" << precursors[j]->C(i)[cell]
// << " chid = " << d_material->chi_d(mt[cell], i, g)
// << " q= " << d_source[g][cell]
// << std::endl;
}
}
}
} // end groups
} // end backward terms
// std::cout << " source = " << this->source(0, 0) << " " << this->source(1, 0) << std::endl;
// std::cout << " source = " << this->source(0, 0, 0) << " " << this->source(1, 0, 0) << " " << dt << std::endl;
}
} // end namespace detran
#endif // detran_SYNTHETICMOMENTSOURCE_I_HH_
//---------------------------------------------------------------------------//
// end of file SyntheticMomentSource.i.hh
//---------------------------------------------------------------------------//
| 34.244275 | 114 | 0.476371 | RLReed |
de3f0e25654f5c1a369c26c7b6896c2122a2fc29 | 252 | hpp | C++ | src/EventListener.hpp | OMKE/TalesOfAlester | 20ce17cf68ad956fc9d6f7cc3ac73a11c61f1118 | [
"MIT"
] | null | null | null | src/EventListener.hpp | OMKE/TalesOfAlester | 20ce17cf68ad956fc9d6f7cc3ac73a11c61f1118 | [
"MIT"
] | 1 | 2019-06-23T00:09:39.000Z | 2019-06-24T19:15:13.000Z | src/EventListener.hpp | OMKE/TalesOfAlester | 20ce17cf68ad956fc9d6f7cc3ac73a11c61f1118 | [
"MIT"
] | null | null | null | #ifndef EVENT_LISTENER_H
#define EVENT_LISTENER_H
#include "SDL2/SDL.h"
/*
** INTERFACE **
desc:
Interface that listens for events
*/
class EventListener {
public:
virtual void listen(SDL_Event &e) = 0;
};
#endif // EVENT_LISTENER_H | 14.823529 | 46 | 0.690476 | OMKE |
de3ffbb91f35912b778bef0b688156e258045e0f | 13,301 | cpp | C++ | net.ssa/xr_3da/xrGame/MainUI.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | xr_3da/xrGame/MainUI.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | xr_3da/xrGame/MainUI.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | #include "stdafx.h"
#include "MainUI.h"
#include "UI/UIDialogWnd.h"
#include "ui/UIMessageBoxEx.h"
#include "UICursor.h"
#include "HUDManager.h"
#include "../xr_IOConsole.h"
#include "../IGame_Level.h"
#include "../CameraManager.h"
#include "xr_Level_controller.h"
#include "ui\UITextureMaster.h"
#include "ui\UIXmlInit.h"
#include <dinput.h>
#include "ui\UIBtnHint.h"
extern CUICursor* GetUICursor(){return UI()->GetUICursor();};
extern CMainUI* UI(){return (CMainUI*)(g_pGamePersistent->m_pMainUI);};
//----------------------------------------------------------------------------------
void S2DVert::rotate_pt(const Fvector2& pivot, float cosA, float sinA)
{
Fvector2 t = pt;
t.sub (pivot);
pt.x = t.x*cosA+t.y*sinA;
pt.y = t.y*cosA-t.x*sinA;
pt.add (pivot);
}
void C2DFrustum::CreateFromRect (const Frect& rect)
{
m_rect.set(float(rect.x1), float(rect.y1), float(rect.x2), float(rect.y2) );
planes.resize (4);
planes[0].build (rect.lt, Fvector2().set(-1, 0));
planes[1].build (rect.lt, Fvector2().set( 0,-1));
planes[2].build (rect.rb, Fvector2().set(+1, 0));
planes[3].build (rect.rb, Fvector2().set( 0,+1));
}
sPoly2D* C2DFrustum::ClipPoly (sPoly2D& S, sPoly2D& D) const
{
bool bFullTest = false;
for (u32 j=0; j<S.size(); j++)
{
if( !m_rect.in(S[j].pt) ) {
bFullTest = true;
break ;
}
}
sPoly2D* src = &D;
sPoly2D* dest = &S;
if(!bFullTest) return dest;
for (u32 i=0; i<planes.size(); i++)
{
// cache plane and swap lists
const Fplane2 &P = planes[i] ;
std::swap (src,dest) ;
dest->clear () ;
// classify all points relative to plane #i
float cls[UI_FRUSTUM_SAFE] ;
for (u32 j=0; j<src->size(); j++) cls[j]=P.classify((*src)[j].pt);
// clip everything to this plane
cls[src->size()] = cls[0] ;
src->push_back((*src)[0]) ;
Fvector2 dir_pt,dir_uv; float denum,t;
for (j=0; j<src->size()-1; j++) {
if ((*src)[j].pt.similar((*src)[j+1].pt,EPS_S)) continue;
if (negative(cls[j])) {
dest->push_back((*src)[j]) ;
if (positive(cls[j+1])) {
// segment intersects plane
dir_pt.sub((*src)[j+1].pt,(*src)[j].pt);
dir_uv.sub((*src)[j+1].uv,(*src)[j].uv);
denum = P.n.dotproduct(dir_pt);
if (denum!=0) {
t = -cls[j]/denum ; //VERIFY(t<=1.f && t>=0);
dest->last().pt.mad ((*src)[j].pt,dir_pt,t);
dest->last().uv.mad ((*src)[j].uv,dir_uv,t);
dest->inc();
}
}
} else {
// J - outside
if (negative(cls[j+1])) {
// J+1 - inside
// segment intersects plane
dir_pt.sub((*src)[j+1].pt,(*src)[j].pt);
dir_uv.sub((*src)[j+1].uv,(*src)[j].uv);
denum = P.n.dotproduct(dir_pt);
if (denum!=0) {
t = -cls[j]/denum ; //VERIFY(t<=1.f && t>=0);
dest->last().pt.mad ((*src)[j].pt,dir_pt,t);
dest->last().uv.mad ((*src)[j].uv,dir_uv,t);
dest->inc();
}
}
}
}
// here we end up with complete polygon in 'dest' which is inside plane #i
if (dest->size()<3) return 0;
}
return dest;
}
//----------------------------------------------------------------------------------
CMainUI::CMainUI ()
{
m_Flags.zero ();
m_startDialog = NULL;
m_pUICursor = xr_new<CUICursor>();
m_pFontManager = xr_new<CFontManager>();
g_pGamePersistent->m_pMainUI= this;
if (Device.bReady) OnDeviceCreate();
ReadTextureInfo ();
CUIXmlInit::InitColorDefs ();
g_btnHint = xr_new<CUIButtonHint>();
m_bPostprocess = false;
m_pMessageBox = NULL;
//m_pMessageInvalidPass = NULL;
//m_pMessageSessionFull = NULL;
}
CMainUI::~CMainUI ()
{
xr_delete (g_btnHint);
xr_delete (m_startDialog);
xr_delete (m_pFontManager);
xr_delete (m_pUICursor);
xr_delete (m_pMessageBox);
//xr_delete (m_pMessageInvalidPass);
//xr_delete (m_pMessageSessionFull);
g_pGamePersistent->m_pMainUI = NULL;
CUITextureMaster::WriteLog ();
}
void CMainUI::ReadTextureInfo(){
if (pSettings->section_exist("texture_desc"))
{
xr_string itemsList;
string256 single_item;
itemsList = pSettings->r_string("texture_desc", "files");
int itemsCount = _GetItemCount(itemsList.c_str());
for (int i = 0; i < itemsCount; i++)
{
_GetItem(itemsList.c_str(), i, single_item);
strcat(single_item,".xml");
CUITextureMaster::ParseShTexInfo(single_item);
}
}
}
void CMainUI::Activate (bool bActivate)
{
if(!!m_Flags.is(flActive) == bActivate) return;
if(bActivate){
m_Flags.set (flActive|flNeedChangeCapture,TRUE);
DLL_Pure* dlg = NEW_INSTANCE (TEXT2CLSID("MAIN_MNU"));
if(!dlg) {
m_Flags.set (flActive|flNeedChangeCapture,FALSE);
return;
}
xr_delete(m_startDialog);
m_startDialog = smart_cast<CUIDialogWnd*>(dlg);
VERIFY(m_startDialog);
m_Flags.set (flRestoreConsole,Console->bVisible);
m_Flags.set (flRestorePause,Device.Pause());
Console->Hide ();
m_Flags.set (flRestoreCursor,GetUICursor()->IsVisible());
if(!m_Flags.is(flRestorePause))
Device.Pause (TRUE);
::Sound->set_volume (1.0f);// pause set to 0
StartStopMenu (m_startDialog,true);
if(g_pGameLevel){
Device.seqFrame.Remove (g_pGameLevel);
Device.seqRender.Remove (g_pGameLevel);
CCameraManager::ResetPP ();
};
Device.seqRender.Add (this, 3); // 1-console 2-cursor
}else{
m_Flags.set (flActive, FALSE);
m_Flags.set (flNeedChangeCapture, TRUE);
Device.seqRender.Remove (this);
bool b = !!Console->bVisible;
if(b){
Console->Hide ();
}
IR_Release ();
if(b){
Console->Show ();
}
CleanInternals ();
if(g_pGameLevel){
Device.seqFrame.Add (g_pGameLevel);
Device.seqRender.Add (g_pGameLevel);
};
if(m_Flags.is(flRestoreConsole))
Console->Show ();
if(!m_Flags.is(flRestorePause))
Device.Pause(FALSE);
if(m_Flags.is(flRestoreCursor))
GetUICursor()->Show();
}
}
bool CMainUI::IsActive ()
{
return !!m_Flags.is(flActive);
}
//IInputReceiver
static int mouse_button_2_key [] = {MOUSE_1,MOUSE_2,MOUSE_3};
void CMainUI::IR_OnMousePress (int btn)
{
if(!IsActive()) return;
IR_OnKeyboardPress(mouse_button_2_key[btn]);
};
void CMainUI::IR_OnMouseRelease (int btn)
{
if(!IsActive()) return;
IR_OnKeyboardRelease(mouse_button_2_key[btn]);
};
void CMainUI::IR_OnMouseHold (int btn)
{
if(!IsActive()) return;
IR_OnKeyboardHold(mouse_button_2_key[btn]);
};
void CMainUI::IR_OnMouseMove (int x, int y)
{
if(!IsActive()) return;
MainInputReceiver()->IR_OnMouseMove(x, y);
};
void CMainUI::IR_OnMouseStop (int x, int y)
{
if(!IsActive()) return;
};
void CMainUI::IR_OnKeyboardPress (int dik)
{
if(!IsActive()) return;
if(key_binding[dik]== kCONSOLE){
Console->Show();
return;
}
if (DIK_F12 == dik){
Render->Screenshot();
return;
}
MainInputReceiver()->IR_OnKeyboardPress( dik);
};
void CMainUI::IR_OnKeyboardRelease (int dik)
{
if(!IsActive()) return;
MainInputReceiver()->IR_OnKeyboardRelease(dik);
};
void CMainUI::IR_OnKeyboardHold (int dik)
{
if(!IsActive()) return;
};
void CMainUI::IR_OnMouseWheel(int direction)
{
if(!IsActive()) return;
MainInputReceiver()->IR_OnMouseWheel(direction);
}
bool CMainUI::OnRenderPPUI_query()
{
return IsActive() && !m_Flags.is(flGameSaveScreenshot);
}
void CMainUI::OnRender ()
{
if(m_Flags.is(flGameSaveScreenshot))
return;
Render->Render ();
}
void CMainUI::OnRenderPPUI_main ()
{
if(!IsActive()) return;
if(m_Flags.is(flGameSaveScreenshot)){
return;
};
m_bPostprocess = true;
m_2DFrustum2.CreateFromRect (Frect().set( 0.0f,
0.0f,
ClientToScreenScaledX(UI_BASE_WIDTH),
ClientToScreenScaledY(UI_BASE_HEIGHT)
));
DoRenderDialogs();
m_pFontManager->Render();
m_bPostprocess = false;
}
void CMainUI::OnRenderPPUI_PP ()
{
if(!IsActive()) return;
m_bPostprocess = true;
xr_vector<CUIWindow*>::iterator it = m_pp_draw_wnds.begin();
for(; it!=m_pp_draw_wnds.end();++it){
(*it)->Draw();
}
m_bPostprocess = false;
}
//pureFrame
void CMainUI::OnFrame (void)
{
m_2DFrustum.CreateFromRect (Frect().set( 0.0f,
0.0f,
ClientToScreenScaledX(UI_BASE_WIDTH),
ClientToScreenScaledY(UI_BASE_HEIGHT)
));
if(!IsActive() && m_startDialog){
xr_delete (m_startDialog);
}
if (m_Flags.is(flNeedChangeCapture)){
m_Flags.set (flNeedChangeCapture,FALSE);
if (m_Flags.is(flActive)) IR_Capture();
else IR_Release();
}
CDialogHolder::OnFrame ();
//screenshot stuff
if(m_Flags.is(flGameSaveScreenshot) && Device.dwFrame > m_screenshotFrame ){
m_Flags.set (flGameSaveScreenshot,FALSE);
::Render->Screenshot (IRender_interface::SM_FOR_GAMESAVE, m_screenshot_name);
if(g_pGameLevel && m_Flags.is(flActive)){
Device.seqFrame.Remove (g_pGameLevel);
Device.seqRender.Remove (g_pGameLevel);
};
if(m_Flags.is(flRestoreConsole))
Console->Show ();
}
}
void CMainUI::OnDeviceCreate()
{
}
void CMainUI::ClientToScreenScaled(Fvector2& dest, float left, float top)
{
dest.set(ClientToScreenScaledX(left), ClientToScreenScaledY(top));
}
float CMainUI::ClientToScreenScaledX(float left)
{
return left * GetScaleX();
}
float CMainUI::ClientToScreenScaledY(float top)
{
return top * GetScaleY();
}
void CMainUI::OutText(CGameFont *pFont, Frect r, float x, float y, LPCSTR fmt, ...)
{
if (r.in(x, y))
{
R_ASSERT(pFont);
va_list lst;
static string512 buf;
::ZeroMemory(buf, 512);
xr_string str;
va_start(lst, fmt);
vsprintf(buf, fmt, lst);
str += buf;
va_end(lst);
// Rescale position in lower resolution
if (x >= 1.0f && y >= 1.0f)
{
x *= GetScaleX();
y *= GetScaleY();
}
pFont->Out(x, y, "%s", str.c_str());
}
}
Frect CMainUI::ScreenRect()
{
static Frect R={0.0f, 0.0f, UI_BASE_WIDTH, UI_BASE_HEIGHT};
return R;
}
void CMainUI::PushScissor(const Frect& r_tgt, bool overlapped)
{
// return;
Frect r_top = ScreenRect();
Frect result = r_tgt;
if (!m_Scissors.empty()&&!overlapped){
r_top = m_Scissors.top();
}
if (!result.intersection(r_top,r_tgt))
result.set (0.0f,0.0f,0.0f,0.0f);
VERIFY(result.x1>=0&&result.y1>=0&&result.x2<=UI_BASE_WIDTH&&result.y2<=UI_BASE_HEIGHT);
m_Scissors.push (result);
result.lt.x = ClientToScreenScaledX(result.lt.x);
result.lt.y = ClientToScreenScaledY(result.lt.y);
result.rb.x = ClientToScreenScaledX(result.rb.x);
result.rb.y = ClientToScreenScaledY(result.rb.y);
Irect r;
r.x1 = iFloor(result.x1);
r.x2 = iFloor(result.x2+0.5f);
r.y1 = iFloor(result.y1);
r.y2 = iFloor(result.y2+0.5f);
VERIFY(r.x1>=0&&r.y1>=0&&(r.x2<=UI_BASE_WIDTH*GetScaleX())&&(r.y2<=UI_BASE_HEIGHT*GetScaleY()));
RCache.set_Scissor (&r);
}
void CMainUI::PopScissor()
{
// return;
VERIFY(!m_Scissors.empty());
m_Scissors.pop ();
if(m_Scissors.empty())
RCache.set_Scissor(NULL);
else{
const Frect& top= m_Scissors.top();
Irect tgt;
tgt.lt.x = iFloor(ClientToScreenScaledX(top.lt.x));
tgt.lt.y = iFloor(ClientToScreenScaledY(top.lt.y));
tgt.rb.x = iFloor(ClientToScreenScaledX(top.rb.x));
tgt.rb.y = iFloor(ClientToScreenScaledY(top.rb.y));
RCache.set_Scissor(&tgt);
}
}
void CMainUI::Screenshot (IRender_interface::ScreenshotMode mode, LPCSTR name)
{
if(mode != IRender_interface::SM_FOR_GAMESAVE){
::Render->Screenshot (mode,name);
}else{
m_Flags.set (flGameSaveScreenshot, TRUE);
strcpy(m_screenshot_name,name);
if(g_pGameLevel && m_Flags.is(flActive)){
Device.seqFrame.Add (g_pGameLevel);
Device.seqRender.Add (g_pGameLevel);
};
m_screenshotFrame = Device.dwFrame+1;
m_Flags.set (flRestoreConsole, Console->bVisible);
Console->Hide ();
}
}
void CMainUI::RegisterPPDraw (CUIWindow* w)
{
UnregisterPPDraw (w);
m_pp_draw_wnds.push_back (w);
}
void CMainUI::UnregisterPPDraw (CUIWindow* w)
{
xr_vector<CUIWindow*>::iterator it = remove( m_pp_draw_wnds.begin(), m_pp_draw_wnds.end(), w);
m_pp_draw_wnds.erase(it, m_pp_draw_wnds.end());
}
void CMainUI::OnInvalidHost(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_invalid_host");
StartStopMenu(m_pMessageBox, false);
}
void CMainUI::OnInvalidPass(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_invalid_pass");
StartStopMenu(m_pMessageBox, false);
}
void CMainUI::OnSessionFull(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_session_full");
StartStopMenu(m_pMessageBox, false);
}
void CMainUI::OnServerReject(){
if (!m_pMessageBox)
{
m_pMessageBox = xr_new<CUIMessageBoxEx>();
}
m_pMessageBox->Init("message_box_server_reject");
StartStopMenu(m_pMessageBox, false);
} | 24.495396 | 98 | 0.62469 | ixray-team |
de4224e4307f30cf5295d56be1e578b5f2e27acc | 879 | cpp | C++ | chap10/Page386_predicate.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 50 | 2016-01-08T14:28:53.000Z | 2022-01-21T12:55:00.000Z | chap10/Page386_predicate.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 2 | 2017-06-05T16:45:20.000Z | 2021-04-17T13:39:24.000Z | chap10/Page386_predicate.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 18 | 2016-08-17T15:23:51.000Z | 2022-03-26T18:08:43.000Z | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
}
int main()
{
vector<string> story = { "the", "quick", "red", "fox", "jump", "over", "the", "slow", "red", "turtle" };
elimDups(story);
for(const auto &s : story)
cout << s << " ";
cout << endl;
// we cannot put isShorter into sort, or the first order will be length rather than alphabet
stable_sort(story.begin(), story.end(), isShorter);
for(const auto &s : story)
cout << s << " ";
cout << endl;
return 0;
}
| 26.636364 | 108 | 0.612059 | sjbarigye |
de44d8873b4bd0425df24b1db6e97e6e2c4c982c | 5,204 | cpp | C++ | main.cpp | maltsevda/FakeD3D9 | 9d14b19cef9a9795847961101aa5378491624af5 | [
"MIT"
] | 12 | 2019-05-14T04:50:06.000Z | 2022-03-22T09:28:54.000Z | main.cpp | maltsevda/FakeD3D9 | 9d14b19cef9a9795847961101aa5378491624af5 | [
"MIT"
] | null | null | null | main.cpp | maltsevda/FakeD3D9 | 9d14b19cef9a9795847961101aa5378491624af5 | [
"MIT"
] | 2 | 2020-07-06T18:45:38.000Z | 2022-02-06T23:40:49.000Z | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "FakeDirect3D9.h"
struct OriginalLibrary
{
HMODULE hDll;
FARPROC D3DPERF_BeginEvent;
FARPROC D3DPERF_EndEvent;
FARPROC D3DPERF_GetStatus;
FARPROC D3DPERF_QueryRepeatFrame;
FARPROC D3DPERF_SetMarker;
FARPROC D3DPERF_SetOptions;
FARPROC D3DPERF_SetRegion;
FARPROC DebugSetLevel;
FARPROC DebugSetMute;
FARPROC Direct3D9EnableMaximizedWindowedModeShim;
FARPROC Direct3DCreate9;
FARPROC Direct3DCreate9Ex;
FARPROC Direct3DShaderValidatorCreate9;
FARPROC PSGPError;
FARPROC PSGPSampleTexture;
} d3d9dll;
extern "C" __declspec(naked) void Fake_D3DPERF_BeginEvent() { _asm { jmp[d3d9dll.D3DPERF_BeginEvent] } }
extern "C" __declspec(naked) void Fake_D3DPERF_EndEvent() { _asm { jmp[d3d9dll.D3DPERF_EndEvent] } }
extern "C" __declspec(naked) void Fake_D3DPERF_GetStatus() { _asm { jmp[d3d9dll.D3DPERF_GetStatus] } }
extern "C" __declspec(naked) void Fake_D3DPERF_QueryRepeatFrame() { _asm { jmp[d3d9dll.D3DPERF_QueryRepeatFrame] } }
extern "C" __declspec(naked) void Fake_D3DPERF_SetMarker() { _asm { jmp[d3d9dll.D3DPERF_SetMarker] } }
extern "C" __declspec(naked) void Fake_D3DPERF_SetOptions() { _asm { jmp[d3d9dll.D3DPERF_SetOptions] } }
extern "C" __declspec(naked) void Fake_D3DPERF_SetRegion() { _asm { jmp[d3d9dll.D3DPERF_SetRegion] } }
extern "C" __declspec(naked) void Fake_DebugSetLevel() { _asm { jmp[d3d9dll.DebugSetLevel] } }
extern "C" __declspec(naked) void Fake_DebugSetMute() { _asm { jmp[d3d9dll.DebugSetMute] } }
extern "C" __declspec(naked) void Fake_Direct3D9EnableMaximizedWindowedModeShim() { _asm { jmp[d3d9dll.Direct3D9EnableMaximizedWindowedModeShim] } }
// extern "C" __declspec(naked) void Fake_Direct3DCreate9() { _asm { jmp[d3d9dll.Direct3DCreate9] } }
extern "C" __declspec(naked) void Fake_Direct3DCreate9Ex() { _asm { jmp[d3d9dll.Direct3DCreate9Ex] } }
extern "C" __declspec(naked) void Fake_Direct3DShaderValidatorCreate9() { _asm { jmp[d3d9dll.Direct3DShaderValidatorCreate9] } }
extern "C" __declspec(naked) void Fake_PSGPError() { _asm { jmp[d3d9dll.PSGPError] } }
extern "C" __declspec(naked) void Fake_PSGPSampleTexture() { _asm { jmp[d3d9dll.PSGPSampleTexture] } }
extern "C" IDirect3D9* WINAPI Fake_Direct3DCreate9(UINT SDKVersion)
{
typedef IDirect3D9* (WINAPI * DIRECT3DCREATEPROC)(UINT SDKVersion);
DIRECT3DCREATEPROC Direct3DCreate9Proc = (DIRECT3DCREATEPROC)d3d9dll.Direct3DCreate9;
IDirect3D9* pRealDirect3D9 = Direct3DCreate9Proc(SDKVersion);
return new FakeDirect3D9(pRealDirect3D9);
}
// error LNK2019: unresolved external symbol _memcpy referenced in function _DllMain@12
void MyCopyMemory(void* pDst, const void* pSrc, size_t uiSize)
{
BYTE* pDstB = (BYTE*)pDst;
const BYTE* pSrcB = (const BYTE*)pSrc;
for (UINT i = 0; i < uiSize; ++i)
pDstB[i] = pSrcB[i];
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
WCHAR path[MAX_PATH];
UINT length = GetSystemDirectoryW(path, MAX_PATH - 10);
MyCopyMemory(path + length, L"\\d3d9.dll", sizeof(WCHAR) * 10);
d3d9dll.hDll = LoadLibraryW(path);
if (!d3d9dll.hDll)
{
MessageBoxW(0, L"Cannot load original d3d9.dll library", L"d3d9.dll proxy", MB_ICONERROR);
ExitProcess(0);
}
d3d9dll.D3DPERF_BeginEvent = GetProcAddress(d3d9dll.hDll, "D3DPERF_BeginEvent");
d3d9dll.D3DPERF_EndEvent = GetProcAddress(d3d9dll.hDll, "D3DPERF_EndEvent");
d3d9dll.D3DPERF_GetStatus = GetProcAddress(d3d9dll.hDll, "D3DPERF_GetStatus");
d3d9dll.D3DPERF_QueryRepeatFrame = GetProcAddress(d3d9dll.hDll, "D3DPERF_QueryRepeatFrame");
d3d9dll.D3DPERF_SetMarker = GetProcAddress(d3d9dll.hDll, "D3DPERF_SetMarker");
d3d9dll.D3DPERF_SetOptions = GetProcAddress(d3d9dll.hDll, "D3DPERF_SetOptions");
d3d9dll.D3DPERF_SetRegion = GetProcAddress(d3d9dll.hDll, "D3DPERF_SetRegion");
d3d9dll.DebugSetLevel = GetProcAddress(d3d9dll.hDll, "DebugSetLevel");
d3d9dll.DebugSetMute = GetProcAddress(d3d9dll.hDll, "DebugSetMute");
d3d9dll.Direct3D9EnableMaximizedWindowedModeShim = GetProcAddress(d3d9dll.hDll, "Direct3D9EnableMaximizedWindowedModeShim");
d3d9dll.Direct3DCreate9 = GetProcAddress(d3d9dll.hDll, "Direct3DCreate9");
d3d9dll.Direct3DCreate9Ex = GetProcAddress(d3d9dll.hDll, "Direct3DCreate9Ex");
d3d9dll.Direct3DShaderValidatorCreate9 = GetProcAddress(d3d9dll.hDll, "Direct3DShaderValidatorCreate9");
d3d9dll.PSGPError = GetProcAddress(d3d9dll.hDll, "PSGPError");
d3d9dll.PSGPSampleTexture = GetProcAddress(d3d9dll.hDll, "PSGPSampleTexture");
break;
}
case DLL_PROCESS_DETACH:
FreeLibrary(d3d9dll.hDll);
break;
}
return TRUE;
}
// error LNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z)
void* __cdecl operator new(unsigned int size)
{
return HeapAlloc(GetProcessHeap(), 0, size);
}
// error LNK2001: unresolved external symbol "void __cdecl operator delete(void *,unsigned int)" (??3@YAXPAXI@Z)
void __cdecl operator delete(void* ptr, unsigned int)
{
HeapFree(GetProcessHeap(), 0, ptr);
}
// error LNK2001: unresolved external symbol __fltused
// it should be a single underscore since the double one is the mangled name
extern "C" int _fltused = 0;
| 46.464286 | 148 | 0.777479 | maltsevda |
de45fd8e13721025c0260f18a9ea663fd118b777 | 1,068 | cpp | C++ | src/Maximum.cpp | LLNL/STREAMSTAT | 5097155390df59ed7803929b4fb867063d12ae2a | [
"BSD-3-Clause"
] | null | null | null | src/Maximum.cpp | LLNL/STREAMSTAT | 5097155390df59ed7803929b4fb867063d12ae2a | [
"BSD-3-Clause"
] | null | null | null | src/Maximum.cpp | LLNL/STREAMSTAT | 5097155390df59ed7803929b4fb867063d12ae2a | [
"BSD-3-Clause"
] | null | null | null | #include <fstream>
#include "Maximum.h"
#include <algorithm>
namespace Statistics {
//template <typename FunctionType>
Maximum::Maximum(const Maximum& val) :
StreamingStatistic(val)
{
mMax = val.mMax;
}
void Maximum::add(double f)
{
mMax = std::max(f,mMax);
}
void Maximum::add(const StreamingStatistic* seg)
{
sterror(type() != seg->type(), "Can only aggregate statistics of idenical type.");
mMax = std::max(mMax,seg->value());
}
void Maximum::serialize(int32_t& buff_sz, char*& buff_ptr, bool create_buff) const
{
buff_sz = sizeof(double);
assert( !(buff_ptr && create_buff) );
if( !buff_ptr && !create_buff )
return;
if( create_buff )
buff_ptr = new char[buff_sz];
memcpy( buff_ptr, (const char*)&mMax, buff_sz );
}
void Maximum::deserialize(int32_t buff_sz, const char* buff_ptr)
{
assert( buff_sz == sizeof(double) );
memcpy( &mMax, buff_ptr, buff_sz );
}
void Maximum::writeASCII(std::ofstream& output) const
{
output << mMax << " ";
}
void Maximum::readASCII(std::ifstream& input)
{
input >> mMax;
}
}
| 17.225806 | 84 | 0.670412 | LLNL |
de4b9b0c96f9648057d5d578f6104890301b0ab5 | 32,686 | cpp | C++ | src/z_zodiacreader.cpp | SpehleonLP/Zodiac | 19ec600c269afda4ef15dead9ed614320fecb14a | [
"MIT"
] | null | null | null | src/z_zodiacreader.cpp | SpehleonLP/Zodiac | 19ec600c269afda4ef15dead9ed614320fecb14a | [
"MIT"
] | null | null | null | src/z_zodiacreader.cpp | SpehleonLP/Zodiac | 19ec600c269afda4ef15dead9ed614320fecb14a | [
"MIT"
] | null | null | null | #include "z_zodiacreader.h"
#ifdef HAVE_ZODIAC
#include "z_zodiacwriter.h"
#include "z_zodiac.h"
#include "z_zodiaccontext.h"
#include "z_zodiacexception.h"
#include <stdexcept>
#include <cstring>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include "add_on/scriptdictionary/scriptdictionary.h"
namespace Zodiac
{
zCZodiacReader::zCZodiacReader(zCZodiac * parent, zIFileDescriptor * file, std::atomic<int> & progress, std::atomic<int> & total_steps) :
m_parent(parent),
m_file(file),
m_mmap(file),
m_progress(progress),
m_totalSteps(total_steps)
{
m_header = (zCHeader const*)(m_mmap.GetAddress() + (m_mmap.GetLength() - sizeof(zCHeader)));
m_stringTable = (char const *)(m_mmap.GetAddress() + m_header->stringTableOffset);
m_entries = (zCEntry const*)(m_mmap.GetAddress() + m_header->addressTableOffset);
m_modules = (zCModule const*)(m_mmap.GetAddress() + m_header->moduleDataOffset);
m_typeInfo = (zCTypeInfo const*)(m_mmap.GetAddress() + m_header->typeInfoOffset);
m_globals = (zCGlobalInfo const*)(m_mmap.GetAddress() + m_header->globalsOffset);
Verify();
m_loadedObjects.reset(new LoadedInfo[addressTableLength()]);
memset(&m_loadedObjects[0], 0, addressTableLength() * sizeof(LoadedInfo));
m_progress = 0;
m_totalSteps = addressTableLength();
}
zCZodiacReader::~zCZodiacReader()
{
//return;
if(m_loadedObjects != nullptr)
{
auto engine = GetEngine();
for(uint32_t i = 0; i < addressTableLength(); ++i)
{
if(!m_loadedObjects[i].needRelease) continue;
auto typeInfo = engine->GetTypeInfoById(m_loadedObjects[i].asTypeId);
while(m_loadedObjects[i].needRelease-- > 0)
{
engine->ReleaseScriptObject(m_loadedObjects[i].ptr, typeInfo);
}
}
}
}
void zCZodiacReader::Verify() const
{
void * end = (void*)(m_mmap.GetAddress() + m_mmap.GetLength());
zCHeader check;
if(strncmp(check.magic, m_header->magic, sizeof(check.magic)) != 0)
throw Exception("Not a zodiac file.", zE_BadFileType);
if(m_header->saveDataByteOffset + saveDataByteLength() > m_mmap.GetLength())
throw Exception("save data", zE_BufferOverrun);
//-----------------------
// CHECK STRINGS
//----------------------
if(GetStringAddresses() + stringAddressCount() > end)
throw Exception("string entry", zE_BufferOverrun);
if(m_stringTable + stringTableLength() > end)
throw Exception("string table", zE_BufferOverrun);
for(uint32_t i = 0; i < stringAddressCount(); ++i)
{
if(GetStringAddresses()[i] > stringTableLength())
{
throw Exception("string address", zE_BufferOverrun);
}
}
//-----------------------
// CHECK ENTRIES
//----------------------
if(m_entries + addressTableLength() > end)
throw Exception("address table", zE_BufferOverrun);
for(uint32_t i = 0; i < addressTableLength(); ++i)
{
if(m_header->savedObjectOffset > m_entries[i].offset)
{
throw Exception("entry save location", zE_BufferOverrun);
}
uint32_t entry_end = (m_entries[i].offset + m_entries[i].byteLength) - m_header->savedObjectOffset;
if(entry_end > m_header->savedObjectLength)
{
throw Exception("entry save size", zE_BufferOverrun);
}
}
//-----------------------
// CHECK MODULES
//----------------------
if(m_modules + moduleDataLength() > end)
throw Exception("module table", zE_BufferOverrun);
for(uint32_t i = 0; i < moduleDataLength(); ++i)
{
if(m_modules[i].name > stringTableLength())
{
throw Exception("name in module", zE_BufferOverrun);
}
if(m_header->byteCodeOffset > m_modules[i].byteCodeOffset || m_modules[i].byteCodeOffset + m_modules[i].byteCodeLength > m_header->byteCodeOffset + m_header->byteCodeByteLength)
{
throw Exception("byte code in module", zE_BufferOverrun);
}
if(m_modules[i].beginTypeInfo + m_modules[i].typeInfoLength > typeInfoLength())
{
throw Exception("asTypeInfo in module", zE_BufferOverrun);
}
if(m_modules[i].beginGlobalInfo + m_modules[i].globalsLength > globalsLength())
{
throw Exception("global variables in module", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Functions
//----------------------
if(GetFunctions() + functionTableLength() > end)
throw Exception("function table", zE_BufferOverrun);
for(uint32_t i = 0; i < functionTableLength(); ++i)
{
auto & function = GetFunctions()[i];
if(function.delegateAddress > addressTableLength())
{
throw Exception("entry id in function", zE_BufferOverrun);
}
if(function.delegateTypeId > typeInfoLength())
{
throw Exception("delegate id in function", zE_BufferOverrun);
}
if(function.module > stringTableLength())
{
throw Exception("module id in function", zE_BufferOverrun);
}
if(function.objectType > typeTableLength())
{
throw Exception("typeId in function", zE_BufferOverrun);
}
if(function.declaration > stringTableLength())
{
throw Exception("declaration in function", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Globals
//----------------------
if(m_globals + globalsLength() > end)
throw Exception("global variables", zE_BufferOverrun);
for(uint32_t i = 0; i < globalsLength(); ++i)
{
if(m_globals[i].name > stringTableLength())
{
throw Exception("name in global", zE_BufferOverrun);
}
if(m_globals[i].nameSpace > stringTableLength())
{
throw Exception("namespace in global", zE_BufferOverrun);
}
if(m_globals[i].address > addressTableLength())
{
throw Exception("entry id in global", zE_BufferOverrun);
}
}
//-----------------------
// CHECK TypeInfo
//----------------------
if(m_typeInfo + typeInfoLength() > end)
throw Exception("type info", zE_BufferOverrun);
for(uint32_t i = 0; i < typeInfoLength(); ++i)
{
auto & typeInfo = m_typeInfo[i];
if(typeInfo.name > stringTableLength())
{
throw Exception("name in typeInfo", zE_BufferOverrun);
}
if(typeInfo.nameSpace > stringTableLength())
{
throw Exception("namespace in typeInfo", zE_BufferOverrun);
}
if(typeInfo.propertiesBegin + typeInfo.propertiesLength > propertiesLength())
{
throw Exception("properties in typeInfo", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Properties
//----------------------
zCProperty const* pBegin, * pEnd;
GetProperties(-1, pBegin, pEnd);
for(auto p = pBegin; p < pEnd; ++p)
{
if(p->name > stringTableLength())
{
throw Exception("name in property", zE_BufferOverrun);
}
if( p->typeId & asTYPEID_MASK_OBJECT
&& (p->typeId & asTYPEID_MASK_SEQNBR) > typeTableLength())
{
throw Exception("typeId in property", zE_BufferOverrun);
}
}
//-----------------------
// CHECK Templates
//----------------------
if(GetTemplates() + templatesLength() > end)
throw Exception("templates", zE_BufferOverrun);
for(uint32_t i = 0; i < templatesLength(); ++i)
{
auto & _template = GetTemplates()[i];
if(_template.name > stringTableLength())
{
throw Exception("name in template", zE_BufferOverrun);
}
if(_template.nameSpace > stringTableLength())
{
throw Exception("namespace in template", zE_BufferOverrun);
}
if(_template.module > stringTableLength())
{
throw Exception("module in template", zE_BufferOverrun);
}
if(_template.declaration > stringTableLength())
{
throw Exception("declaration in template", zE_BufferOverrun);
}
}
}
void zCZodiacReader::ReadSaveData(zREADER_FUNC_t func, void * userData)
{
if(func)
{
zIFileDescriptor::ReadSubFile sub_file(m_file, m_header->saveDataByteOffset, m_header->saveDataByteLength);
func(this, userData);
}
}
void zCZodiacReader::DocumentGlobalVariables(asIScriptEngine * engine)
{
int typeId;
const char *name, *nameSpace;
uint32_t noModules = engine->GetModuleCount();
for(uint32_t i = 0; i < noModules; ++i)
{
auto mod = engine->GetModuleByIndex(i);
int index = GetModuleIndex(mod->GetName(), i);
if(index < 0) continue;
uint32_t varCount = mod->GetGlobalVarCount();
for(uint32_t j = 0; j < varCount; j++ )
{
mod->GetGlobalVar(j, &name, &nameSpace, &typeId);
zCGlobalInfo const* global = GetGlobalVar(index, name, nameSpace, j);
PopulateTable( mod->GetAddressOfGlobalVar(j), global->address, typeId);
}
}
}
void zCZodiacReader::RestoreGlobalVariables(asIScriptEngine * engine)
{
int typeId;
const char *name, *nameSpace;
uint32_t noModules = engine->GetModuleCount();
for(uint32_t i = 0; i < noModules; ++i)
{
auto mod = engine->GetModuleByIndex(i);
int index = GetModuleIndex(mod->GetName(), i);
if(index < 0) continue;
uint32_t varCount = mod->GetGlobalVarCount();
for(uint32_t j = 0; j < varCount; j++ )
{
mod->GetGlobalVar(j, &name, &nameSpace, &typeId);
zCGlobalInfo const* global = GetGlobalVar(index, name, nameSpace, j);
if(global)
LoadScriptObject(mod->GetAddressOfGlobalVar(j), global->address, typeId);
}
}
}
template<typename T>
static asITypeInfo * GetEnumByIndex(T * t, int i) { return t->GetEnumByIndex(i); }
template<typename T>
static asITypeInfo * GetObjectTypeByIndex(T * t, int i) { return t->GetObjectTypeByIndex(i); }
template<typename T>
static asITypeInfo * GetTypedefByIndex(T * t, int i) { return t->GetTypedefByIndex(i); }
static asITypeInfo * GetFuncdefByIndex(asIScriptEngine * t, int i) { return t->GetFuncdefByIndex(i); }
template<typename T>
inline void zCZodiacReader::SolveTypeInfo(T * op, int i, uint32_t & quickCheck, asITypeInfo* (GetterFunc)(T*, int), uint32_t N)
{
for(uint32_t j = 0; j < N; ++j)
{
auto typeInfo = GetterFunc(op, j);
auto type = GetTypeInfo(i, typeInfo->GetName(), typeInfo->GetNamespace(), &quickCheck);
if(type != nullptr)
{
assert(m_asTypeIdFromStored[type - m_typeInfo] == 0);
m_asTypeIdFromStored[type - m_typeInfo] = typeInfo->GetTypeId();
}
}
}
template<typename T>
inline void zCZodiacReader::SolveTypeInfo(T * op, int i)
{
uint32_t quickCheck{};
SolveTypeInfo(op, i, quickCheck, &GetObjectTypeByIndex<T>, op->GetObjectTypeCount());
SolveTypeInfo(op, i, quickCheck, &GetEnumByIndex<T>, op->GetEnumCount());
}
bool zCZodiacReader::LoadByteCode(asIScriptEngine * engine)
{
bool loadedByteCode;
for(uint32_t i = 0; i < moduleDataLength() - 1; ++i)
{
// bool created = false;
auto moduleName = LoadString(m_modules[i].name);
asIScriptModule * module = engine->GetModule(moduleName, asGM_ONLY_IF_EXISTS);
if(!module && m_modules[i].byteCodeLength != 0)
{
module = engine->GetModule(moduleName, asGM_ALWAYS_CREATE);
zIFileDescriptor::ReadSubFile sub_file(m_file, m_modules[i].byteCodeOffset, m_modules[i].byteCodeLength);
module->LoadByteCode(m_file, nullptr);
loadedByteCode = true;
}
}
//bind imports
if(loadedByteCode)
{
auto noModules = engine->GetModuleCount();
for(uint32_t i = 0; i < noModules; ++i)
{
engine->GetModuleByIndex(i)->BindAllImportedFunctions();
}
}
return loadedByteCode;
}
void zCZodiacReader::ProcessModules(asIScriptEngine * engine, bool loadedByteCode)
{
(void)loadedByteCode;
m_asTypeIdFromStored.resize(typeTableLength());
for(int i = 0; i <= asTYPEID_DOUBLE; ++i)
m_asTypeIdFromStored[i] = i;
//solve typeinfo
for(uint32_t i = 0; i < moduleDataLength() - 1; ++i)
{
asIScriptModule * module = engine->GetModule(LoadString(m_modules[i].name), asGM_ONLY_IF_EXISTS);
if(!module) throw Exception(zE_ModuleDoesNotExist);
SolveTypeInfo(module, i);
}
SolveTypeInfo(engine, moduleDataLength()-1);
uint32_t quickCheck{};
SolveTypeInfo(engine, moduleDataLength()-1, quickCheck, &GetFuncdefByIndex, engine->GetFuncdefCount());
SolveTemplates(engine);
zCProperty const* pBegin{}, * pEnd{};
GetProperties(-1, pBegin, pEnd);
m_properties.resize(pEnd-pBegin);
//create property conversion table
void const* end = m_typeInfo + typeInfoLength();
for(auto ti = m_typeInfo; ti < end; ++ti)
{
if(ti->typeId <= asTYPEID_DOUBLE) continue;
auto typeInfo = engine->GetTypeInfoById(m_asTypeIdFromStored[ti - m_typeInfo]);
if(typeInfo == nullptr) throw Exception(zE_BadTypeId);
int asTypeId{};
auto N = ti->propertiesBegin + ti->propertiesLength;
uint32_t start{};
for(uint32_t i = ti->propertiesBegin; i < N; ++i)
{
if(m_properties[i].propertyId != ~0u)
throw Exception(zE_DuplicatePropertyAddress);
auto prop = asGetProperty(typeInfo,LoadString(pBegin[i].name), &asTypeId, start);
if(prop == -1)
throw Exception(zE_UnableToRestoreProperty);
start = prop+1;
m_properties[i].propertyId = prop;
m_properties[i].readOffset = pBegin[i].offset;
m_properties[i].readType = LoadTypeId(pBegin[i].typeId);
m_properties[i].writeType = asTypeId;
assert(!loadedByteCode || (m_properties[i].readType&zTYPEID_OBJECT) == (m_properties[i].writeType&zTYPEID_OBJECT));
}
}
DocumentGlobalVariables(engine);
}
void zCZodiacReader::SolveTemplates(asIScriptEngine * engine)
{
int index = typeInfoLength();
void const* end = GetTemplates() + templatesLength();
for(auto ti = GetTemplates(); ti < end; ++ti, ++index)
{
asITypeInfo * typeInfo{};
if(!ti->module)
typeInfo = engine->GetTypeInfoByDecl(LoadString(ti->declaration));
else
{
asIScriptModule * module = engine->GetModule(LoadString(ti->module), asGM_ONLY_IF_EXISTS);
if(!module) throw Exception(zE_ModuleDoesNotExist);
typeInfo = module->GetTypeInfoByDecl(LoadString(ti->declaration));
}
if(!typeInfo)
throw Exception(zE_BadTypeId);
m_asTypeIdFromStored[index] = typeInfo->GetTypeId();
}
}
int zCZodiacReader::asGetProperty(asITypeInfo * typeInfo, const char * pName, int * typeId, int from) const
{
const char * name;
int propertyCount = typeInfo->GetPropertyCount();
//most likely to be 1 after the last thing we found so try this.....
for(int j = from; j < propertyCount; ++j)
{
typeInfo->GetProperty(j, &name, typeId);
if(strcmp(pName, name) == 0)
{
return j;
}
}
for(int j = 0; j < from; ++j)
{
typeInfo->GetProperty(j, &name, typeId);
if(strcmp(pName, name) == 0)
{
return j;
}
}
return -1;
}
int zCZodiacReader::GetModuleIndex(const char * name, uint32_t quickCheck) const
{
if(quickCheck < moduleDataLength())
{
if(strcmp(LoadString(m_modules[quickCheck].name), name) == 0)
return quickCheck;
}
for(uint32_t i = 0; i < moduleDataLength(); ++i)
{
if(strcmp(LoadString(m_modules[i].name), name) == 0)
return i;
}
return -1;
}
zCGlobalInfo const* zCZodiacReader::GetGlobalVar(uint32_t module, const char * name, const char * nameSpace, uint32_t quickCheck) const
{
auto globals = (zCGlobalInfo const*)(m_globals + m_modules[module].beginGlobalInfo);
auto global_end = globals + m_modules[module].globalsLength;
if(quickCheck < m_modules[module].globalsLength)
{
if(strcmp(LoadString(globals[quickCheck].name), name) == 0
&& strcmp(LoadString(globals[quickCheck].nameSpace), nameSpace) == 0)
{
return &globals[quickCheck];
}
}
for(auto p = globals; p < global_end; ++p)
{
if(strcmp(LoadString(p->name), name) == 0
&& strcmp(LoadString(p->nameSpace), nameSpace) == 0)
{
return p;
}
}
return nullptr;
}
zCTypeInfo const* zCZodiacReader::GetTypeInfo(uint32_t module, const char * name, const char * nameSpace, uint32_t * quickCheck) const
{
auto typeInfo = (m_typeInfo + m_modules[module].beginTypeInfo);
auto End = typeInfo + m_modules[module].typeInfoLength;
if(nameSpace == nullptr) nameSpace = "";
if(quickCheck && *quickCheck < m_modules[module].typeInfoLength)
{
auto p = &typeInfo[*quickCheck];
auto _name = LoadString(p->name);
auto _nameSpace = LoadString(p->nameSpace);
if(strcmp(_name, name) == 0
&& strcmp(_nameSpace, nameSpace) == 0)
{
*quickCheck += 1;
return p;
}
}
for(auto p = typeInfo; p < End; ++p)
{
auto _name = LoadString(p->name);
auto _nameSpace = LoadString(p->nameSpace);
if(strcmp(_name, name) == 0
&& strcmp(_nameSpace, nameSpace) == 0)
{
if(quickCheck) *quickCheck = (p - typeInfo) + 1;
return p;
}
}
return nullptr;
}
void zCZodiacReader::GetProperties(int typeId, zCProperty const*& begin, zCProperty const*& end) const
{
if((uint32_t)typeId > typeInfoLength())
{
begin = (zCProperty const*)(m_mmap.GetAddress() + m_header->propertiesOffset);
end = begin + m_header->propertiesLength;
}
else
{
auto & typeInfo = m_typeInfo[typeId];
begin = (zCProperty const*)(m_mmap.GetAddress() + m_header->propertiesOffset) + typeInfo.propertiesLength;
end = begin + typeInfo.propertiesLength;
}
}
bool zCZodiacReader::RestoreAppObject(void * dst, int address, int asTypeId)
{
if(!(asTypeId & asTYPEID_APPOBJECT || asTypeId & asTYPEID_TEMPLATE))
return false;
auto typeInfo = GetEngine()->GetTypeInfoById(asTypeId);
if(RestoreFunction((void**)dst, address, typeInfo))
return true;
///registered thing?
auto entry = m_parent->GetTypeEntryFromAsTypeId(asTypeId);
if(!entry)
throw Exception(zE_UnknownEncodingProtocol);
void const* src = m_mmap.GetAddress() + m_entries[address].offset;
//POD
if(!entry->onLoad)
memcpy(dst, src, entry->byteLength);
else if(typeInfo->GetFlags() & asOBJ_VALUE)
{
assert(LoadTypeId(m_entries[address].typeId) == asTypeId);
assert(entry->isValueType);
zIFileDescriptor::ReadSubFile sub_file(m_file, m_entries[address].offset, m_entries[address].byteLength);
(entry->onLoad)(this, dst, m_loadedObjects[address].zTypeId, asTypeId & asTYPEID_OBJHANDLE);
}
else
{
auto stored_id = LoadTypeId(m_entries[address].typeId);
assert((stored_id & asTYPEID_TEMPLATE) == (asTypeId & asTYPEID_TEMPLATE));
assert(((asTypeId&zTYPEID_OBJECT) == stored_id));
assert(!entry->isValueType);
assert(!m_loadedObjects[address].beingLoaded);
m_loadedObjects[address].zTypeId = entry->zTypeId;
m_loadedObjects[address].asTypeId = stored_id;
m_loadedObjects[address].beingLoaded = true;
m_loadedObjects[address].needRelease = 0;
zIFileDescriptor::ReadSubFile sub_file(m_file, m_entries[address].offset, m_entries[address].byteLength);
try
{
if(asTypeId & asTYPEID_OBJHANDLE)
{
(entry->onLoad)(this, &m_loadedObjects[address].ptr, m_loadedObjects[address].zTypeId, asTypeId & asTYPEID_OBJHANDLE);
*((void**)dst) = m_loadedObjects[address].ptr;
}
else
{
(entry->onLoad)(this, &dst, m_loadedObjects[address].zTypeId, asTypeId & asTYPEID_OBJHANDLE);
m_loadedObjects[address].ptr = dst;
}
}
catch(Code & c)
{
throw Exception(c);
}
m_loadedObjects[address].beingLoaded = false;
assert(m_loadedObjects[address].zTypeId == entry->zTypeId);
assert(m_loadedObjects[address].asTypeId = stored_id);
}
return true;
}
void zCZodiacReader::PopulateTable(void * dst, uint32_t address, int typeId)
{
if(!(typeId & asTYPEID_SCRIPTOBJECT) || (typeId & asTYPEID_OBJHANDLE))
{
return;
}
if(address > addressTableLength())
throw Exception(zE_BadObjectAddress);
if(m_loadedObjects[address].ptr)
{
if(m_loadedObjects[address].ptr == dst)
return;
throw Exception(zE_DoubleLoad);
}
m_loadedObjects[address].ptr = dst;
m_loadedObjects[address].zTypeId = zIZodiac::GetTypeId<asIScriptObject>();
m_loadedObjects[address].asTypeId = typeId;
++m_progress;
if(!(typeId & asTYPEID_SCRIPTOBJECT))
return;
void const* src = m_mmap.GetAddress() + m_entries[address].offset;
auto & zTypeInfo = m_typeInfo[m_entries[address].typeId];
asIScriptObject * ref = (asIScriptObject*)dst;
const auto begin = &m_properties[zTypeInfo.propertiesBegin];
const auto end = begin + zTypeInfo.propertiesLength;
//first loop populate lookup table
for(auto p = begin; p < end; ++p)
{
auto typeId = p->writeType;
auto offset = ref->GetAddressOfProperty(p->propertyId);
uint32_t read = *(uint32_t*)((uint8_t*)src + p->readOffset);
assert(p->writeType == ref->GetPropertyTypeId(p->propertyId));
//app objects don't have an owner so it shouldn't cause an infinite loop
if((typeId & asTYPEID_SCRIPTOBJECT) && !(typeId & asTYPEID_OBJHANDLE))
{
PopulateTable(offset, read, p->writeType);
}
}
}
void zCZodiacReader::LoadScriptObject(void * dst, int address, int asTypeId, bool isWeak)
{
//object address 0 is nullptr so negative values aren't considered
if((uint32_t)address >= addressTableLength())
throw Exception(zE_BadObjectAddress);
//if the owner is non-zero restore the owner
if(m_entries[address].owner && asTypeId > asTYPEID_DOUBLE)
{
void * ptr{};
auto ownr = m_entries[address].owner;
auto ownrTypeId = LoadTypeId(m_entries[ownr].typeId);
//load owner if it isn't loaded (check to avoid addreffing it i guess)
if(!m_loadedObjects[ownr].ptr && !m_loadedObjects[ownr].beingLoaded)
{
LoadScriptObject(&ptr, ownr, ownrTypeId | asTYPEID_OBJHANDLE, false);
}
}
auto & loaded = m_loadedObjects[address];
//it is a handle i suppose
if(loaded.ptr && dst != loaded.ptr)
{
assert(dst && *(void**)dst == nullptr);
assert(loaded.asTypeId & (asTYPEID_MASK_OBJECT));
auto engine = GetEngine();
auto from_type = engine->GetTypeInfoById(loaded.asTypeId);
auto to_type = engine->GetTypeInfoById(asTypeId);
if(to_type->GetFuncdefSignature())
{
if(RestoreAppObject(dst, address, asTypeId))
return;
}
assert(to_type != nullptr);
if(asTypeId == loaded.asTypeId && asTypeId & asTYPEID_SCRIPTOBJECT)
{
assert(m_loadedObjects[address].zTypeId == zIZodiac::GetTypeId<asIScriptObject>());
auto obj = (asIScriptObject *)m_loadedObjects[address].ptr;
*(asIScriptObject**)dst = obj;
if(!isWeak) obj->AddRef();
}
else
{
engine->RefCastObject(m_loadedObjects[address].ptr, from_type, to_type, (void**)dst);
m_loadedObjects[address].needRelease += isWeak;
}
if(*(void**)dst == nullptr)
throw Exception(zE_ObjectRestoreTypeMismatch);
return;
}
//it loaded as nullptr
else if(loaded.asTypeId & asTYPEID_OBJHANDLE && (asTypeId & asTYPEID_OBJHANDLE))
{
*(void**)dst = nullptr;
return;
}
void const* src = m_mmap.GetAddress() + m_entries[address].offset;
if(RestoreAppObject(dst, address, asTypeId))
return;
else if(asTypeId <= asTYPEID_DOUBLE && m_entries[address].typeId <= asTYPEID_DOUBLE)
{
RestorePrimitive(dst, asTypeId, src, m_entries[address].typeId);
return;
}
//should always be a script object by this point
assert(asTypeId & asTYPEID_SCRIPTOBJECT);
//---------------------------------------------------------
// Script Object
//---------------------------------------------------------
auto _typeId = LoadTypeId(m_entries[address].typeId);
auto _typeInfo = GetEngine()->GetTypeInfoById(_typeId);
auto typeInfo = _typeId == asTypeId? _typeInfo : GetEngine()->GetTypeInfoById(asTypeId);
if(asTypeId & asTYPEID_OBJHANDLE || *(void**)dst == nullptr)
{
//impossible??
// assert(typeInfo->GetFactoryCount() != 0);
assert(asTypeId & asTYPEID_SCRIPTOBJECT);
if(address == 0)
{
*(void**)dst = nullptr;
return;
}
m_loadedObjects[address].asTypeId = _typeId & ~zTYPEID_OBJHANDLE;
m_loadedObjects[address].zTypeId = zIZodiac::GetTypeId<asIScriptObject>();
m_loadedObjects[address].ptr = GetEngine()->CreateUninitializedScriptObject(_typeInfo);
m_loadedObjects[address].needRelease = 1 + isWeak;
++m_progress;
GetEngine()->RefCastObject(m_loadedObjects[address].ptr, _typeInfo, typeInfo, (void**)dst);
if(*(void**)dst == nullptr)
throw Exception(zE_ObjectRestoreTypeMismatch);
//dereference to set up script object...
dst = *(void**)dst;
}
else if(loaded.ptr)
assert(loaded.ptr == dst);
else
{
//assure table is populated
m_loadedObjects[address].asTypeId = _typeId & ~zTYPEID_OBJHANDLE;
m_loadedObjects[address].zTypeId = zIZodiac::GetTypeId<asIScriptObject>();
m_loadedObjects[address].ptr = dst;
++m_progress;
}
//---------------------------------------------------------
// set up script object
//---------------------------------------------------------
auto & zTypeInfo = m_typeInfo[m_entries[address].typeId];
asIScriptObject * ref = (asIScriptObject*)dst;
const auto begin = &m_properties[zTypeInfo.propertiesBegin];
const auto end = begin + zTypeInfo.propertiesLength;
//first loop populate lookup table
for(auto p = begin; p < end; ++p)
{
#ifndef NDEBUG
auto name = ref->GetPropertyName(p->propertyId);
#endif
auto typeId = p->writeType;
auto offset = ref->GetAddressOfProperty(p->propertyId);
uint32_t read = *(uint32_t*)((uint8_t*)src + p->readOffset);
assert(p->writeType == ref->GetPropertyTypeId(p->propertyId));
//app objects don't have an owner so it shouldn't cause an infinite loop
PopulateTable(offset, read, typeId);
}
//Restore object contents
for(auto p = begin; p < end; ++p)
{
#ifndef NDEBUG
auto name = ref->GetPropertyName(p->propertyId);
#endif
auto offset = ref->GetAddressOfProperty(p->propertyId);
auto typeId = ref->GetPropertyTypeId(p->propertyId);
void * read = ((uint8_t*)src + p->readOffset);
assert(p->writeType == typeId);
if(*(uint32_t*)read == 31)
{
int break_point = 0;
++break_point;
}
//app objects don't have an owner so it shouldn't cause an infinite loop
RestoreScriptObject(offset, read, typeId);
}
}
bool zCZodiacReader::RestoreFunction(void ** dst, uint32_t handle, asITypeInfo * typeInfo)
{
assert(handle != 0);
if(!(typeInfo && typeInfo->GetFuncdefSignature()))
return false;
asIScriptFunction * delegate = LoadFunction(handle);
if(!delegate->IsCompatibleWithTypeId(typeInfo->GetTypeId()))
throw Exception(zE_ObjectRestoreTypeMismatch);
*dst = delegate;
return true;
}
void zCZodiacReader::RestoreScriptObject(void * dst, void const* src, uint asTypeId)
{
if(asTypeId <= asTYPEID_DOUBLE)
{
memcpy(dst, src, GetEngine()->GetSizeOfPrimitiveType(asTypeId));
return;
}
else if((asTypeId & asTYPEID_OBJHANDLE) || (asTypeId & asTYPEID_SCRIPTOBJECT))
{
LoadScriptObject(dst, *(uint32_t*)src, asTypeId);
}
else
{
auto typeInfo = GetEngine()->GetTypeInfoById(asTypeId);
//funcdef, next thing is an address
if(typeInfo && typeInfo->GetFuncdefSignature())
{
RestoreFunction((void**)dst, *(uint32_t*)src, typeInfo);
return;
}
auto entry = m_parent->GetTypeEntryFromAsTypeId(asTypeId);
if(!entry) throw Exception(zE_UnknownEncodingProtocol);
if(!entry->onLoad)
{
memcpy(dst, src, entry->byteLength);
}
else
{
LoadScriptObject(dst, *(uint32_t*)src, asTypeId);
}
}
}
asITypeInfo * zCZodiacReader::LoadTypeInfo(int id, bool RefCount)
{
if(id < 0) return nullptr;
auto typeId = LoadTypeId(id);
auto typeInfo = GetEngine()->GetTypeInfoById(typeId);
if(typeInfo && RefCount)
typeInfo->AddRef();
return typeInfo;
}
int zCZodiacReader::LoadTypeId(int id)
{
if(id <= asTYPEID_DOUBLE) return id;
if((uint32_t)id >= typeTableLength())
throw Exception(zE_BadTypeId);
return m_asTypeIdFromStored[id];
}
asIScriptFunction * zCZodiacReader::LoadFunction(int id)
{
if(id <= 0) return nullptr;
if((uint)id > functionTableLength())
throw Exception(zE_BadObjectAddress);
auto & function = GetFunctions()[id];
auto declaration = LoadString(function.declaration);
if(m_loadedFunctions == nullptr)
{
m_loadedFunctions.reset(new void*[functionTableLength()]);
memset(&m_loadedFunctions[0], 0, sizeof(m_loadedFunctions[0]) * functionTableLength());
}
if(m_loadedFunctions[id] != nullptr)
{
asIScriptFunction * func = reinterpret_cast<asIScriptFunction*>(m_loadedFunctions[id]);
func->AddRef();
return func;
}
asIScriptFunction * func = nullptr;
asITypeInfo * typeInfo = LoadTypeInfo(function.objectType, false);
if(typeInfo)
{
//should it be virtual???
func = typeInfo->GetMethodByDecl(declaration);
}
else if(function.module)
{
auto moduleName = LoadString(function.module);
auto module = GetEngine()->GetModule(moduleName, asGM_ONLY_IF_EXISTS);
if(!module)
throw Exception(zE_ModuleDoesNotExist);
func = module->GetFunctionByDecl(declaration);
}
else
{
func = GetEngine()->GetGlobalFunctionByDecl(declaration);
}
if(func == nullptr)
throw Exception(zE_BadObjectAddress);
//is it a delegate?
if(!function.delegateAddress)
func->AddRef();
else
{
void * delegateObject{};
LoadScriptObject(&delegateObject, function.delegateAddress, LoadTypeId(function.delegateTypeId) | asTYPEID_OBJHANDLE);
asIScriptFunction * delegate = GetEngine()->CreateDelegate(func, delegateObject);
if(!delegate)
throw Exception(zE_BadFunctionInfo);
func = delegate;
}
m_loadedFunctions[id] = func;
++m_progress;
return func;
}
asIScriptContext * zCZodiacReader::LoadContext(int id)
{
if(id <= 0)
return nullptr;
//object address 0 is nullptr so negative values aren't considered
if((uint32_t)id >= addressTableLength())
throw Exception(zE_BadObjectAddress);
if(m_loadedObjects[id].ptr != nullptr)
{
if(m_loadedObjects[id].zTypeId != zIZodiac::GetTypeId<asIScriptContext>())
throw Exception(zE_ObjectRestoreTypeMismatch);
asIScriptContext * context = reinterpret_cast<asIScriptContext*>(m_loadedObjects[id].ptr);
context->AddRef();
return context;
}
asIScriptContext * context{};
zCEntry const* entry = &m_entries[id];
zIFileDescriptor::ReadSubFile sub_file(m_file, entry->offset, entry->byteLength);
int real_type{};
ZodiacLoad(this, &context, real_type);
++m_progress;
m_loadedObjects[id].ptr = context;
m_loadedObjects[id].zTypeId = zIZodiac::GetTypeId<asIScriptContext>();
return context;
}
void * zCZodiacReader::LoadObject(int id, zLOAD_FUNC_t load_func, int & actualType)
{
if(id <= 0)
return nullptr;
//object address 0 is nullptr so negative values aren't considered
if((uint32_t)id >= addressTableLength())
throw Exception(zE_BadObjectAddress);
if(m_loadedObjects[id].ptr == nullptr && m_loadedObjects[id].zTypeId == 0)
{
zCEntry const* entry = &m_entries[id];
zIFileDescriptor::ReadSubFile sub_file(m_file, entry->offset, entry->byteLength);
//ensure stack corruption if something goes wrong, (fail quickly if behavior is undefined)
void * dst{};
load_func(this, &dst, actualType, false);
m_loadedObjects[id].ptr = dst;
m_loadedObjects[id].zTypeId = actualType;
m_loadedObjects[id].asTypeId = -1;
++m_progress;
}
actualType = m_loadedObjects[id].zTypeId;
return m_loadedObjects[id].ptr;
}
void zCZodiacReader::LoadObject(int id, void * dst, zLOAD_FUNC_t load_func, int & actualType, bool isHandle)
{
//object address 0 is nullptr so negative values aren't considered
if(id == 0 || (uint32_t)id >= addressTableLength())
throw Exception(zE_BadObjectAddress);
zCEntry const* entry = &m_entries[id];
zIFileDescriptor::ReadSubFile sub_file(m_file, entry->offset, entry->byteLength);
load_func(this, dst, actualType, isHandle);
}
template<typename T>
static T ReadPrimitive2(void const* address, int asTypeId)
{
assert(asTypeId <= asTYPEID_DOUBLE);
switch(asTypeId)
{
case asTYPEID_VOID: return 0L;
case asTYPEID_BOOL: return *(uint8_t*)address;
case asTYPEID_INT8: return *(asINT8*)address;
case asTYPEID_INT16: return *(asINT16*)address;
case asTYPEID_INT32: return *(int32_t*)address;
case asTYPEID_INT64: return *(asINT64*)address;
case asTYPEID_UINT8: return *(asBYTE*)address;
case asTYPEID_UINT16: return *(asWORD*)address;
case asTYPEID_UINT32: return *(asDWORD*)address;
case asTYPEID_UINT64: return *(asQWORD*)address;
case asTYPEID_FLOAT: return *(float*)address;
case asTYPEID_DOUBLE: return *(double*)address;
default:break;
};
return 0;
}
template<typename T>
static T ReadPrimitive(void const* address, int asTypeId)
{
auto eax = ReadPrimitive2<T>(address, asTypeId);
return eax;
}
//hopefully this gets optimized a lot
void zCZodiacReader::RestorePrimitive(void * dst, int dstTypeId, void const* address, int srcTypeId)
{
assert(dstTypeId <= asTYPEID_DOUBLE);
switch(dstTypeId)
{
case asTYPEID_VOID: break;
case asTYPEID_BOOL: *(bool *)dst = ReadPrimitive<bool> (address, srcTypeId); break;
case asTYPEID_INT8: *(asINT8 *)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_INT16: *(asINT16*)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_INT32: *(int32_t*)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_INT64: *(asINT64*)dst = ReadPrimitive<asINT64>(address, srcTypeId); break;
case asTYPEID_UINT8: *(asBYTE *)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_UINT16: *(asWORD *)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_UINT32: *(asDWORD*)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_UINT64: *(asQWORD*)dst = ReadPrimitive<asQWORD>(address, srcTypeId); break;
case asTYPEID_FLOAT: *(float *)dst = ReadPrimitive<double> (address, srcTypeId); break;
case asTYPEID_DOUBLE: *(double *)dst = ReadPrimitive<double> (address, srcTypeId); break;
};
}
}
#endif
| 27.329431 | 180 | 0.701615 | SpehleonLP |
de4dabbd4fe6fafb74938d19ad038a5db6820ce6 | 788 | cpp | C++ | src/geometry.cpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | src/geometry.cpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | src/geometry.cpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | #include "gold/geometry.hpp"
namespace au {
bool within_closed_bounds(SDL_Point const & p, SDL_Rect const & rect)
{
return p.x >= rect.x and p.x <= rect.x + rect.w
and p.y >= rect.y and p.y <= rect.y + rect.h;
}
double scale_by_height(SDL_Rect const & from, SDL_Rect const & to)
{
// scale width by normalizing the rect height to the max height
return to.h / static_cast<double>(from.h);
}
SDL_Rect clip_width(SDL_Rect const & rect, SDL_Rect const & max)
{
SDL_Rect clipped{rect};
// scale the rect to be clipped into the space of the max bounds
double const scale = scale_by_height(rect, max);
// clip the width if it's too wide
if (clipped.w * scale > max.w) {
clipped.w = static_cast<int>(max.w/scale);
}
return clipped;
}
}
| 27.172414 | 69 | 0.659898 | josiest |
de4eeb154a95d899df52b4bf82c4437fa6b5a8eb | 661 | cpp | C++ | TestProject1/TestProject1.cpp | halterman/318_F19 | fd04d3bf9168485947fae86d5d2d7af1752f61af | [
"MIT"
] | null | null | null | TestProject1/TestProject1.cpp | halterman/318_F19 | fd04d3bf9168485947fae86d5d2d7af1752f61af | [
"MIT"
] | null | null | null | TestProject1/TestProject1.cpp | halterman/318_F19 | fd04d3bf9168485947fae86d5d2d7af1752f61af | [
"MIT"
] | null | null | null | #include <iostream>
class Int {
int value;
public:
Int(int value) {
this->value = value;
}
int get() const {
return value;
}
};
class NotCopyable {
Int value;
public:
NotCopyable() = default;
NotCopyable(int value) : value(value) {}
NotCopyable(const NotCopyable& other) = delete;
NotCopyable& operator=(const NotCopyable& other) = delete;
int get() const {
return value.get();
}
};
void f(NotCopyable nc) {
std::cout << nc.get() << '\n';
}
int main() {
NotCopyable x{ 45 };
std::cout << x.get() << '\n';
//NotCopyable y;
//std::cout << y.get() << '\n';
std::cout << "----------\n";
//f(x);
}
| 16.948718 | 60 | 0.556732 | halterman |
de4f722bfad1a47ec05bdd63c172786cbdf95f9d | 6,568 | cpp | C++ | src/jni/OpenSSLJavaInterface/Hmac.cpp | muelli/scapi | c37d7b2594b234e177fcb8be69e25ca7caccab65 | [
"MIT"
] | 3 | 2018-09-26T02:56:45.000Z | 2021-04-09T02:30:05.000Z | src/jni/OpenSSLJavaInterface/Hmac.cpp | muelli/scapi | c37d7b2594b234e177fcb8be69e25ca7caccab65 | [
"MIT"
] | null | null | null | src/jni/OpenSSLJavaInterface/Hmac.cpp | muelli/scapi | c37d7b2594b234e177fcb8be69e25ca7caccab65 | [
"MIT"
] | 7 | 2018-09-26T03:08:48.000Z | 2022-01-26T16:44:32.000Z | /**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2012 - SCAPI (http://crypto.biu.ac.il/scapi)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* SCAPI uses Crypto++, Miracl, NTL and Bouncy Castle. Please see these projects for any further licensing issues.
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/
#include "StdAfx.h"
#include <jni.h>
#include "Hmac.h"
#include <openssl/hmac.h>
#include <iostream>
using namespace std;
/*
* function createHMAC : Create a native hmac object.
* param hashName : The name of the underlying hash to use.
* return : Pointer to the created hmac.
*/
JNIEXPORT jlong JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_createHMAC
(JNIEnv *env, jobject, jstring hashName){
HMAC_CTX *ctx = new HMAC_CTX;
OpenSSL_add_all_digests();
//get the hash name from java.
const char* name = env->GetStringUTFChars(hashName, NULL);
//Get the underlying hash function.
const EVP_MD *md = EVP_get_digestbyname(name);
//Release the allocated memory.
env->ReleaseStringUTFChars(hashName, name);
//Create an Hmac object and initialize it with the created hash.
HMAC_CTX_init(ctx);
if (0 == (HMAC_Init_ex(ctx, NULL, 0, md, NULL))) return 0;
return (long) ctx;
}
/*
* function setKey : Sets the given key to the given Hmac.
* param hmac : Pointer to the native Hmac object.
* param key : The key that should be set.
*/
JNIEXPORT void JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_setKey
(JNIEnv *env, jobject, jlong hmac, jbyteArray key){
//Convert the given key into c++ notation.
jbyte* keyBytes = (jbyte*) env->GetByteArrayElements(key, 0);
//Initialize the Hmac object with the given key.
HMAC_Init_ex((HMAC_CTX *)hmac, keyBytes, env->GetArrayLength(key), NULL, NULL);
//Make sure to release the memory created in c++. The JVM will not release it automatically.
env->ReleaseByteArrayElements(key, keyBytes, 0);
}
/*
* function getNativeBlockSize : Returns the length of the underlying hash's result.
*/
JNIEXPORT jint JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_getNativeBlockSize
(JNIEnv *, jobject, jlong hmac){
//Get the size of the hashed message.
return EVP_MD_size(((HMAC_CTX *)hmac)->md);
}
/*
* function getName : Returns the name of the underlying hash.
*/
JNIEXPORT jstring JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_getName
(JNIEnv *env, jobject, jlong hmac){
//Get the type of the hash.
int type = EVP_MD_type(((HMAC_CTX *)hmac)->md);
//Convert the type to a name.
const char* name = OBJ_nid2sn(type);
//Return a string that Java can understand with the name of the hash.
return env->NewStringUTF(name);
}
/*
* function updateNative : Update teh Hmac object with the given in array
* param hmac : Pointer to the native Hmac object.
* param in : Input array that should be updated to the Hmac function.
* param inOffset : The offset within the input array that the update should take place from.
* param len : The length of the input array.
*/
JNIEXPORT void JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_updateNative
(JNIEnv *env, jobject, jlong hmac, jbyteArray in, jint inOffset, jint len){
//Convert the given data into c++ notation.
jbyte* input = (jbyte*) env->GetByteArrayElements(in, 0);
//Update the Hmac object.
HMAC_Update((HMAC_CTX*)hmac, (const unsigned char*)(input+inOffset), len);
//Release the allocated memory.
env->ReleaseByteArrayElements(in, input, 0);
}
/*
* function updateFinal : Finalize the Hmac operation
* param hmac : Pointer to the native Hmac object.
* param out : Output array that should hols the Hmac's result.
* param outOffset : The offset within the output array that the reHmac result should start from.
*/
JNIEXPORT void JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_updateFinal
(JNIEnv *env, jobject, jlong hmac, jbyteArray out, jint outOffset){
int size = EVP_MD_size(((HMAC_CTX *)hmac)->md); //Get the size of the hash output.
unsigned char* output = new unsigned char[size];//Create a char array to hold the result.
//Compute the final function and copy the output the the given output array
if (0 == (HMAC_Final((HMAC_CTX *)hmac, output, NULL))){
delete output;
}
env->SetByteArrayRegion(out, outOffset, size, (jbyte*)output);
//initialize the Hmac again in order to enable repeated calls.
const EVP_MD *md = ((HMAC_CTX *)hmac)->md;
unsigned char* key = ((HMAC_CTX *)hmac)->key;
int keyLen = ((HMAC_CTX *)hmac)->key_length;
if (0 == (HMAC_Init_ex((HMAC_CTX *)hmac, key, keyLen, md, NULL))){
delete(output);
}
//Release the allocated memory.
delete output;
}
/*
* function deleteNative : Deletes the Hmac object.
*/
JNIEXPORT void JNICALL Java_edu_biu_scapi_primitives_prf_openSSL_OpenSSLHMAC_deleteNative
(JNIEnv *, jobject, jlong hmac){
HMAC_CTX_cleanup((HMAC_CTX*)hmac);
}
| 41.834395 | 158 | 0.695341 | muelli |
de51e0065e9eb226edf02e5b7532b2daec70f6f2 | 15,881 | cc | C++ | lib/flyMS/FlightCore.cc | msardonini/flyMS | ea1127a3313fb52a8fe789222ba654e05583e06c | [
"MIT"
] | null | null | null | lib/flyMS/FlightCore.cc | msardonini/flyMS | ea1127a3313fb52a8fe789222ba654e05583e06c | [
"MIT"
] | null | null | null | lib/flyMS/FlightCore.cc | msardonini/flyMS | ea1127a3313fb52a8fe789222ba654e05583e06c | [
"MIT"
] | null | null | null | /**
* @file FlightCore.cc
* @brief Main control loop for the flyMS program
*
* @author Mike Sardonini
* @date 10/15/2018
*/
#include "flyMS/FlightCore.h"
#include <sys/stat.h>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include "spdlog/fmt/ostr.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"
namespace flyMS {
void FlightCore::zero_pids() {
roll_outer_PID_.zero_values();
roll_inner_PID_.zero_values();
pitch_outer_PID_.zero_values();
pitch_inner_PID_.zero_values();
yaw_PID_.zero_values();
}
FlightCore::FlightCore(const YAML::Node &config_params)
: imu_module_(Imu::getInstance()),
ulog_(),
setpoint_module_(config_params),
mavlink_interface_(config_params),
position_controller_(config_params),
gps_module_(config_params),
config_params_(config_params) {
flight_mode_ = static_cast<FlightMode>(config_params["flight_mode"].as<uint32_t>());
is_debug_mode_ = config_params["debug_mode"].as<bool>();
log_filepath_ = config_params["log_filepath"].as<std::string>();
YAML::Node controller = config_params["controller"];
max_control_effort_ = controller["max_control_effort"].as<std::array<float, 3>>();
}
int FlightCore::flight_core(StateData &imu_data_body) {
if (mavlink_interface_) {
mavlink_interface_.SendImuMessage(imu_data_body);
}
/************************************************************************
* Check the Mavlink Interface for New Visual Odometry Data
************************************************************************/
Eigen::Vector3f setpoint_orientation;
if (mavlink_interface_) {
VioData vio;
float vio_yaw;
if (mavlink_interface_.GetVioData(&vio)) {
position_controller_.ReceiveVio(vio);
position_controller_.GetSetpoint(setpoint_orientation, vio_yaw);
float log_setpoint[4] = {setpoint_orientation(0), setpoint_orientation(1), vio_yaw, setpoint_orientation(2)};
float quat_setpoint[4] = {vio.quat.w(), vio.quat.x(), vio.quat.y(), vio.quat.z()};
// Log the VIO Data
ULogPosCntrlMsg vio_log_msg(imu_data_body.timestamp_us, vio.position.data(), vio.velocity.data(), quat_setpoint,
log_setpoint);
ulog_.WriteFlightData<ULogPosCntrlMsg>(vio_log_msg, ULogPosCntrlMsg::ID());
flyStereo_streaming_data_ = true;
}
}
/************************************************************************
* Get Setpoint Data *
************************************************************************/
auto setpoint = setpoint_module_.get_setpoint_data();
// If we have commanded a switch in Aux, activate the perception system
if (mavlink_interface_) {
if (setpoint.Aux[0] < 0.1 && setpoint.Aux[1] > 0.9) {
// Transition to start flyStereo
mavlink_interface_.SendStartCommand();
// Assume that the current throttle value will be an average value to keep
// altitude
standing_throttle_ = setpoint.throttle;
initial_yaw_ = imu_data_body.euler[2];
// Make sure our first setpoint is zero
flyStereo_running_ = true;
} else if (setpoint.Aux[0] > 0.9 && setpoint.Aux[1] < 0.1) {
flyStereo_running_ = false;
flyStereo_streaming_data_ = false;
mavlink_interface_.SendShutdownCommand();
// Reset the filters in the Position controller
position_controller_.ResetController();
setpoint_orientation = Eigen::Vector3f::Zero();
position_generator_.ResetCounter();
}
}
// Apply orientation commands from the position controller if running
if (flyStereo_running_ && flyStereo_streaming_data_) {
setpoint.euler_ref[0] = setpoint_orientation(0);
setpoint.euler_ref[1] = setpoint_orientation(1);
setpoint.throttle = setpoint_orientation(2) + standing_throttle_;
// setpoint.euler[2] = vio_yaw - imu_data_body.euler[2] + initial_yaw_;
// Apply the position setpoint
Eigen::Vector3f pos_ref;
position_generator_.GetPosition(&pos_ref);
position_controller_.SetReferencePosition(pos_ref);
}
std::array<float, 3> u_euler; //< The amount of controller effort (-1 to 1) to give in each euler angle [RPY]
/************************************************************************
* Roll Controller *
************************************************************************/
float droll_setpoint;
if (flight_mode_ == FlightMode::STABILIZED) {
droll_setpoint = roll_outer_PID_.update_filter(setpoint.euler_ref[0] - imu_data_body.euler[0]);
} else if (flight_mode_ == FlightMode::ACRO) { // Acro mode
droll_setpoint = setpoint.euler_ref[0];
} else {
throw std::runtime_error("[FlightCore] Error! Invalid flight mode. Shutting down now");
}
imu_data_body.eulerRate[0] = gyro_lpf_roll_.update_filter(imu_data_body.eulerRate[0]);
u_euler[0] = roll_inner_PID_.update_filter(droll_setpoint - imu_data_body.eulerRate[0]);
u_euler[0] = std::clamp(u_euler[0], -max_control_effort_[0], max_control_effort_[0]);
/************************************************************************
* Pitch Controller *
************************************************************************/
float dpitch_setpoint;
if (flight_mode_ == FlightMode::STABILIZED) { // Stabilized Flight Mode
dpitch_setpoint = pitch_outer_PID_.update_filter(setpoint.euler_ref[1] - imu_data_body.euler[1]);
} else if (flight_mode_ == FlightMode::ACRO) { // Acro mode
dpitch_setpoint = setpoint.euler_ref[1];
} else {
throw std::runtime_error("[FlightCore] Error! Invalid flight mode. Shutting down now");
}
imu_data_body.eulerRate[1] = gyro_lpf_pitch_.update_filter(imu_data_body.eulerRate[1]);
u_euler[1] = pitch_inner_PID_.update_filter(dpitch_setpoint - imu_data_body.eulerRate[1]);
u_euler[1] = std::clamp(u_euler[1], -max_control_effort_[1], max_control_effort_[1]);
/************************************************************************
* Yaw Controller *
************************************************************************/
imu_data_body.eulerRate[2] = gyro_lpf_yaw_.update_filter(imu_data_body.eulerRate[2]);
u_euler[2] = yaw_PID_.update_filter(setpoint.euler_ref[2] - imu_data_body.euler[2]);
// Apply a saturation filter
u_euler[2] = std::clamp(u_euler[2], -max_control_effort_[2], max_control_effort_[2]);
/************************************************************************
* Reset the Integrators if Landed *
************************************************************************/
if (setpoint.throttle < setpoint_module_.get_min_throttle() + .01) {
integrator_reset_++;
} else {
integrator_reset_ = 0;
}
// if landed for 2 seconds, reset integrators and Yaw error
if (integrator_reset_ > 2 / LOOP_DELTA_T) {
setpoint.euler_ref[2] = imu_data_body.euler[2];
setpoint_module_.set_yaw_ref(imu_data_body.euler[2]);
zero_pids();
}
/************************************************************************
* Mixing
*
* CCW 1 2 CW Body Frame:
* \ / X
* / \ Y_|
* CW 3 4 CCW Z UP
*
************************************************************************/
// The amount of power (0 - 1) to give to each motor
std::array<float, 4> u;
u[0] = setpoint.throttle + u_euler[0] - u_euler[1] - u_euler[2];
u[1] = setpoint.throttle - u_euler[0] - u_euler[1] + u_euler[2];
u[2] = setpoint.throttle + u_euler[0] + u_euler[1] + u_euler[2];
u[3] = setpoint.throttle - u_euler[0] + u_euler[1] - u_euler[2];
/************************************************************************
* Check Output Ranges, if outside, adjust *
************************************************************************/
static constexpr float smallest_value = 0.f;
float largest_value = 1.f;
for (int i = 0; i < 4; i++) {
if (u[i] > largest_value) {
largest_value = u[i];
}
if (u[i] < smallest_value) u[i] = 0;
}
// if upper saturation would have occurred, reduce all outputs evenly
if (largest_value > 1) {
float offset = largest_value - 1;
for (int i = 0; i < 4; i++) u[i] -= offset;
}
/************************************************************************
* Send Commands to ESCs *
************************************************************************/
if (!is_debug_mode_) {
pru_client_.setSendData(u);
}
/************************************************************************
* Check the kill Switch and Shutdown if set *
************************************************************************/
if (setpoint.kill_switch < 0.5 && !is_debug_mode_) {
spdlog::info("\nKill Switch Hit! Shutting Down\n");
rc_set_state(EXITING);
}
// Print some stuff to the console in debug mode
if (is_debug_mode_) {
console_print(imu_data_body, setpoint);
}
/************************************************************************
* Check for GPS Data and Handle Accordingly *
************************************************************************/
gps_module_.getGpsData(&gps_);
/************************************************************************
* Log Important Flight Data For Analysis *
************************************************************************/
struct ULogFlightMsg flight_msg {
imu_data_body.timestamp_us, imu_data_body, setpoint, u, u_euler
};
ulog_.WriteFlightData<struct ULogFlightMsg>(flight_msg, ULogFlightMsg::ID());
return 0;
}
int FlightCore::console_print(const StateData &imu_data_body, const SetpointData &setpoint) {
// spdlog::info("time {:3.3f} ", control->time);
// spdlog::info("Alt_ref {:3.1f} ",control->alt_ref);
// spdlog::info("U1: {:2.2f}, U2: {:2.2f}, U3: {:2.2f}, U4: {:2.2f} ", u[0],
// u[1], u[2], u[3]); spdlog::info("Aux {:2.1f} ", setpoint.Aux[0]);
// spdlog::info("function: {}",rc_get_dsm_ch_normalized(6));
// spdlog::info("num wraps {} ",control->num_wraps);
// spdlog::info(" Throt {:2.2f}, Roll_ref {:2.2f}, Pitch_ref {:2.2f}, Yaw_ref {:2.2f} KS {:2.2f} ", setpoint.throttle,
// setpoint.euler_ref[0], setpoint.euler_ref[1], setpoint.euler_ref[2], setpoint.kill_switch);
// spdlog::info("Roll {:1.2f}, Pitch {:1.2f}, Yaw {:2.3f}", imu_data_body.euler[0], imu_data_body.euler[1],
// imu_data_body.euler[2]);
spdlog::info("droll {:1.2f}, dpitch {:1.2f}, dyaw {:2.3f}", imu_data_body.eulerRate[0], imu_data_body.eulerRate[1],
imu_data_body.eulerRate[2]);
// spdlog::info(" Mag X {:4.2f}",control->mag[0]);
// spdlog::info(" Mag Y {:4.2f}",control->mag[1]);
// spdlog::info(" Mag Z {:4.2f}",control->mag[2]);
// spdlog::info(" Accel X {:4.2f}",control->accel[0]);
// spdlog::info(" Accel Y {:4.2f}",control->accel[1]);
// spdlog::info(" Accel Z {:4.2f}",control->accel[2]);
// spdlog::info(" Pos N {:2.3f} ", control->ekf_filter.output.ned_pos[0]);
// spdlog::info(" Pos E {:2.3f} ", control->ekf_filter.output.ned_pos[1]);
// spdlog::info(" Pos D {:2.3f} ", control->ekf_filter.output.ned_pos[2]);
// spdlog::info(" DRoll {:1.2f}, DPitch {:1.2f}, DYaw {:2.3f}",
// imu_data_body.eulerRate[0],
// imu_data_body.eulerRate[1], imu_data_body.eulerRate[2]);
// spdlog::info("uroll {:2.3f}, upitch {:2.3f}, uyaw {:2.3f}", u_euler[0],
// u_euler[1],
// u_euler[2]);
// spdlog::info(" GPS pos lat: {:2.2f}", control->GPS_data.pos_lat);
// spdlog::info(" GPS pos lon: {:2.2f}", control->GPS_data.pos_lon);
// spdlog::info(" HDOP: {}", control->GPS_data.HDOP);
// spdlog::info("Baro Alt: {} ",control->baro_alt);
return 0;
}
void FlightCore::init_logging(const std::string &log_location) {
int run_number = 1;
std::stringstream run_str;
run_str << std::internal << std::setfill('0') << std::setw(3) << run_number;
std::string log_dir(log_location + std::string("/run") + run_str.str());
// Find the next run number folder that isn't in use
struct stat st = {0};
while (!stat(log_dir.c_str(), &st)) {
run_str.str(std::string());
run_str << std::internal << std::setfill('0') << std::setw(3) << ++run_number;
log_dir = (log_location + std::string("/run") + run_str.str());
}
// Make a new folder to hold the logged data
mkdir(log_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
// Initialize spdlog
std::vector<spdlog::sink_ptr> sinks;
// Only use the console sink if we are in debug mode
if (is_debug_mode_) {
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
}
int max_bytes = 1048576 * 20; // Max 20 MB
int max_files = 20;
sinks.push_back(
std::make_shared<spdlog::sinks::rotating_file_sink_mt>(log_dir + "/console_log.txt", max_bytes, max_files));
auto flyMS_log = std::make_shared<spdlog::logger>("flyMS_log", std::begin(sinks), std::end(sinks));
// Register loggers to be global logger
flyMS_log->set_level(spdlog::level::trace);
spdlog::register_logger(flyMS_log);
spdlog::set_default_logger(flyMS_log);
flyMS_log->flush_on(spdlog::level::trace); // TODO REMOVE
// Initialize Ulog
ulog_.init(log_dir);
}
int FlightCore::init() {
// Create a file for logging and initialize our file logger
init_logging(log_filepath_);
std::cout << "hi\n";
if (config_params_["mavlink_interface"]["enable"].as<bool>()) {
mavlink_interface_.Init();
}
// Initialize the remote controller through the setpoint object
setpoint_module_.init();
// Blocks execution until a packet is received
if (!is_debug_mode_) {
setpoint_module_.wait_for_data_packet();
}
// Tell the system that we are running if we are in the predicted UNINITIALIZED state. Else shutdown
if (rc_get_state() == UNINITIALIZED) {
rc_set_state(RUNNING);
} else {
rc_set_state(EXITING);
}
// Generate the PID controllers and low-pass filters
YAML::Node controller = config_params_["controller"];
YAML::Node filters = config_params_["filters"];
double pid_lpf_const = controller["pid_LPF_const_sec"].as<double>();
roll_inner_PID_ = generate_pid(controller["roll_PID_inner"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
roll_outer_PID_ = generate_pid(controller["roll_PID_outer"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
pitch_outer_PID_ =
generate_pid(controller["pitch_PID_outer"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
pitch_inner_PID_ =
generate_pid(controller["pitch_PID_inner"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
yaw_PID_ = generate_pid(controller["yaw_PID"].as<std::array<double, 3>>(), pid_lpf_const, LOOP_DELTA_T);
auto lpf_num = filters["imu_lpf_num"].as<std::vector<double>>();
auto lpf_den = filters["imu_lpf_den"].as<std::vector<double>>();
gyro_lpf_roll_ = DigitalFilter(lpf_num, lpf_den);
gyro_lpf_pitch_ = DigitalFilter(lpf_num, lpf_den);
gyro_lpf_yaw_ = DigitalFilter(lpf_num, lpf_den);
// Initialize the client to connect to the PRU handler
pru_client_.startPruClient();
// Start the flight program
std::function<int(StateData &)> f = std::bind(&FlightCore::flight_core, this, std::placeholders::_1);
imu_module_.init(config_params_["imu_params"], f);
return 0;
}
} // namespace flyMS
| 42.349333 | 120 | 0.581575 | msardonini |
de54a78f41108e308a7b40ee164cfc22cebd0e21 | 2,276 | cpp | C++ | cpp_10/parallel_algorithms/spinlock_vs_atomic/test.cpp | eshernan/parallel_course | 37528e0c19e1524f948138bcc7a6ccdc6a3aa0dd | [
"MIT"
] | 3 | 2021-01-18T18:15:51.000Z | 2021-05-21T07:04:31.000Z | spinlock_vs_atomic/test.cpp | andy-thomason/parallel_algorithms | c7ca071dd87dd8044d16d41d61efb1d07b9fbca3 | [
"MIT"
] | null | null | null | spinlock_vs_atomic/test.cpp | andy-thomason/parallel_algorithms | c7ca071dd87dd8044d16d41d61efb1d07b9fbca3 | [
"MIT"
] | 1 | 2021-05-21T07:04:44.000Z | 2021-05-21T07:04:44.000Z |
#include <chrono>
#include <atomic>
#include <future>
#include <array>
#include <mutex>
class nolock {
public:
void lock() {
}
void unlock() {
}
};
class spinlock {
std::atomic_flag flag_{false};
public:
void lock() {
while (flag_.test_and_set(std::memory_order_acquire)) ;
}
void unlock() {
flag_.clear(std::memory_order_release);
}
};
template <class LockType>
class locker {
LockType &lock_;
public:
locker(LockType &lock) : lock_(lock) { lock_.lock(); }
~locker() { lock_.unlock(); }
};
auto now() { return std::chrono::high_resolution_clock::now(); }
// crude growable array
// see http://www.stroustrup.com/lock-free-vector.pdf for an elegant growable array.
template< typename Type, typename SizeType, typename LockType >
class vector {
static const int capacity_ = 0x100000;
Type *values_ = nullptr;
SizeType size_{0};
LockType lock_;
public:
vector() : values_(new Type[capacity_]) {}
~vector() { delete[] values_; }
void push_back(const Type &x) {
locker<LockType> lck(lock_);
int dest = size_++;
if (dest < capacity_) values_[dest] = x;
}
const Type &operator[](int idx) { return values_[idx]; }
int size() const { return size_; };
};
template <class Fn>
void time(Fn fn, const char *text) {
auto start = now();
{
std::array<std::future<void>, 8 > futures;
for ( auto &f: futures ) f = std::async(std::launch::async, fn);
}
int ns = (int)std::chrono::nanoseconds(now() - start).count();
printf("%20s: t=%dns\n", text, ns);
}
int main() {
vector<int, std::atomic<int>, nolock> vec1;
time([&vec1] {
for (int i = 0; i != 0x100000 / 8; ++i) {
vec1.push_back(i);
}
}, "atomic");
printf("atomic version: size=%x\n", vec1.size());
vector<int, int, spinlock> vec2;
time([&vec2] {
for (int i = 0; i != 0x100000 / 8; ++i) {
vec2.push_back(i);
}
}, "spinlock");
printf("spinlock version: size=%x\n", vec2.size());
vector<int, volatile int, nolock> vec3;
time([&vec3] {
for (int i = 0; i != 0x100000 / 8; ++i) {
vec3.push_back(i);
}
}, "single thread");
printf("single thread version: size=%x\n", vec2.size());
}
| 22.76 | 85 | 0.588313 | eshernan |
de58bb811e689c91b09f785c404790bf07b48bdb | 6,424 | cpp | C++ | src/io_worker.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | src/io_worker.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | src/io_worker.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2014 DataStax
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 "io_worker.hpp"
#include "pool.hpp"
namespace cass {
IOWorker::IOWorker(Session* session, Logger* logger, const Config& config)
: session_(session)
, logger_(logger)
, ssl_context_(nullptr)
, is_closing_(false)
, pending_request_count_(0)
, config_(config)
, request_queue_(config.queue_size_io()) {
prepare_.data = this;
}
IOWorker::~IOWorker() {
cleanup();
}
int IOWorker::init() {
int rc = EventThread::init(config_.queue_size_event());
if (rc != 0) return rc;
rc = request_queue_.init(loop(), this, &IOWorker::on_execute);
if (rc != 0) return rc;
rc = uv_prepare_init(loop(), &prepare_);
if (rc != 0) return rc;
rc = uv_prepare_start(&prepare_, on_prepare);
return rc;
}
bool IOWorker::add_pool_async(Host host) {
IOWorkerEvent event;
event.type = IOWorkerEvent::ADD_POOL;
event.host = host;
return send_event_async(event);
}
bool IOWorker::remove_pool_async(Host host) {
IOWorkerEvent event;
event.type = IOWorkerEvent::REMOVE_POOL;
event.host = host;
return send_event_async(event);
}
void IOWorker::close_async() {
is_closing_ = true;
while (!request_queue_.enqueue(nullptr)) {
// Keep trying
}
}
void IOWorker::add_pool(Host host) {
if (!is_closing_ && pools.count(host) == 0) {
Pool* pool = new Pool(host, loop(), ssl_context_, logger_, config_);
pool->set_ready_callback(
std::bind(&IOWorker::on_pool_ready, this, std::placeholders::_1));
pool->set_closed_callback(
std::bind(&IOWorker::on_pool_closed, this, std::placeholders::_1));
pool->set_keyspace_callback(
std::bind(&IOWorker::on_set_keyspace, this, std::placeholders::_1));
pool->connect(session_->keyspace());
pools[host] = pool;
}
}
bool IOWorker::execute(RequestHandler* request_handler) {
if (is_closing_) {
return false;
}
return request_queue_.enqueue(request_handler);
}
void IOWorker::on_set_keyspace(const std::string& keyspace) {
session_->set_keyspace(keyspace);
}
void IOWorker::maybe_close() {
if (is_closing_ && pending_request_count_ <= 0) {
for (auto& entry : pools) {
entry.second->close();
}
maybe_notify_closed();
}
}
void IOWorker::maybe_notify_closed() {
if (pools.empty()) {
session_->notify_closed_async();
close_handles();
}
}
void IOWorker::cleanup() {
auto it = pending_delete_.begin();
while (it != pending_delete_.end()) {
delete *it;
it = pending_delete_.erase(it);
}
}
void IOWorker::close_handles() {
EventThread::close_handles();
request_queue_.close_handles();
uv_prepare_stop(&prepare_);
logger_->debug("IO worker active handles %d", loop()->active_handles);
}
void IOWorker::on_pool_ready(Pool* pool) {
session_->notify_ready_async();
}
void IOWorker::on_pool_closed(Pool* pool) {
Host host = pool->host();
logger_->info("Pool for '%s' closed", host.address.to_string().c_str());
pending_delete_.push_back(pool);
pools.erase(host);
if (is_closing_) {
maybe_notify_closed();
} else {
ReconnectRequest* reconnect_request = new ReconnectRequest(this, host);
Timer::start(loop(), config_.reconnect_wait(), reconnect_request,
IOWorker::on_pool_reconnect);
}
}
void IOWorker::on_retry(RequestHandler* request_handler, RetryType retry_type) {
Host host;
if (retry_type == RETRY_WITH_NEXT_HOST) {
request_handler->next_host();
}
if (!request_handler->get_current_host(&host)) {
request_handler->on_error(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE,
"No hosts available");
delete request_handler;
return;
}
auto it = pools.find(host);
if (it != pools.end()) {
auto pool = it->second;
Connection* connection = pool->borrow_connection(request_handler->keyspace);
if (connection != nullptr) {
if (!pool->execute(connection, request_handler)) {
on_retry(request_handler, RETRY_WITH_NEXT_HOST);
}
} else { // Too busy, or no connections
if (!pool->wait_for_connection(request_handler)) {
on_retry(request_handler, RETRY_WITH_NEXT_HOST);
}
}
} else {
on_retry(request_handler, RETRY_WITH_NEXT_HOST);
}
}
void IOWorker::on_request_finished(RequestHandler* request_handler) {
pending_request_count_--;
maybe_close();
}
void IOWorker::on_event(const IOWorkerEvent& event) {
if (event.type == IOWorkerEvent::ADD_POOL) {
add_pool(event.host);
} else if (event.type == IOWorkerEvent::REMOVE_POOL) {
// TODO(mpenick):
}
}
void IOWorker::on_pool_reconnect(Timer* timer) {
ReconnectRequest* reconnect_request =
static_cast<ReconnectRequest*>(timer->data());
IOWorker* io_worker = reconnect_request->io_worker;
if (!io_worker->is_closing_) {
io_worker->logger_->info(
"Attempting to reconnect to '%s'",
reconnect_request->host.address.to_string().c_str());
io_worker->add_pool(reconnect_request->host);
}
delete reconnect_request;
}
void IOWorker::on_execute(uv_async_t* async, int status) {
IOWorker* io_worker = reinterpret_cast<IOWorker*>(async->data);
RequestHandler* request_handler = nullptr;
while (io_worker->request_queue_.dequeue(request_handler)) {
if (request_handler != nullptr) {
io_worker->pending_request_count_++;
request_handler->set_retry_callback(
std::bind(&IOWorker::on_retry, io_worker, std::placeholders::_1,
std::placeholders::_2));
request_handler->set_finished_callback(std::bind(
&IOWorker::on_request_finished, io_worker, std::placeholders::_1));
request_handler->retry(RETRY_WITH_CURRENT_HOST);
}
}
io_worker->maybe_close();
}
void IOWorker::on_prepare(uv_prepare_t* prepare, int status) {
IOWorker* io_worker = reinterpret_cast<IOWorker*>(prepare->data);
io_worker->cleanup();
}
} // namespace cass
| 28.175439 | 80 | 0.693337 | Paycasso |
de5a2a360613b4f97ca9dc28208b296e0d9d8c88 | 1,721 | cpp | C++ | LeetCode/100/1847.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | 1 | 2021-03-05T14:16:46.000Z | 2021-03-05T14:16:46.000Z | LeetCode/100/1847.cpp | K-ona/CPP-Training | aa312970505f67c270257c8a5816e89c10f2d1ce | [
"Apache-2.0"
] | null | null | null | LeetCode/100/1847.cpp | K-ona/CPP-Training | aa312970505f67c270257c8a5816e89c10f2d1ce | [
"Apache-2.0"
] | null | null | null | // created by Kona @VSCode
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define LOCAL_TEST
typedef long long ll;
using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::queue;
using std::set;
using std::string;
using std::vector;
class Solution {
public:
vector<int> closestRoom(vector<vector<int>>& rooms,
vector<vector<int>>& queries) {
std::sort(rooms.begin(), rooms.end(),
[&](vector<int> &first, vector<int> &second) -> bool {
return first[1] > second[1];
});
for (int i = 0; i < queries.size(); ++i) {
queries[i].push_back(i);
}
std::sort(queries.begin(), queries.end(),
[&](vector<int> &first, vector<int> &second) -> bool {
return first[1] > second[1];
});
vector<int> res(queries.size(), 0);
set<int> Sup;
for (int i = 0, l = 0; i < queries.size(); ++i) {
// cout << queries[i][1] << endl;
while (l < rooms.size() && rooms[l][1] >= queries[i][1])
Sup.insert(rooms[l++][0]);
auto pos = Sup.lower_bound(queries[i][0]);
if (Sup.empty())
res[queries[i][2]] = -1;
else if (pos == Sup.begin())
res[queries[i][2]] = *pos;
else if (abs(*pos - queries[i][0]) >= abs(*(--pos) - queries[i][0])) {
res[queries[i][2]] = *pos;
} else {
res[queries[i][2]] = *(++pos);
}
}
return res;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
#ifdef LOCAL_TEST
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* code */
return 0;
} | 24.942029 | 76 | 0.531087 | K-ona |
de5baaef664e1b5ea845d6166be70d38c0830770 | 454 | cpp | C++ | Olympiad Programs/Helli Programming Training/Codeforces 189A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | 1 | 2020-12-08T11:21:34.000Z | 2020-12-08T11:21:34.000Z | Olympiad Programs/Helli Programming Training/Codeforces 189A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | Olympiad Programs/Helli Programming Training/Codeforces 189A.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
const int Maxn=4*1E4+25;
int N,a,b,c;
//bool can[Maxn];
int num[Maxn];
int main()
{
cin >> N >> a >> b >> c;
num[a]=1;
num[b]=1;
num[c]=1;
for (int i=1;i<=N;i++)
if(num[i]!=0)
{
num[i+a]=max(num[i+a],num[i]+1);
num[i+b]=max(num[i+b],num[i]+1);
num[i+c]=max(num[i+c],num[i]+1);
}
cout << num[N] << endl;
}
| 17.461538 | 44 | 0.455947 | mirtaba |
de6081cdb76d6ad83b0f3733e23a463a59c18229 | 9,473 | cpp | C++ | Data Structures Final C++/CIS22C-Final-Group3/CIS22C-Final-Group3/FileIO.cpp | LEmilio14/Projects_in_C_PlusPlus | 3c004b0a7c958163243752a4903329d2e40517d4 | [
"MIT"
] | 2 | 2019-09-21T05:48:53.000Z | 2020-03-30T00:29:42.000Z | Data Structures Final C++/CIS22C-Final-Group3/CIS22C-Final-Group3/FileIO.cpp | LEmilio14/Projects_in_C_PlusPlus | 3c004b0a7c958163243752a4903329d2e40517d4 | [
"MIT"
] | null | null | null | Data Structures Final C++/CIS22C-Final-Group3/CIS22C-Final-Group3/FileIO.cpp | LEmilio14/Projects_in_C_PlusPlus | 3c004b0a7c958163243752a4903329d2e40517d4 | [
"MIT"
] | 1 | 2019-09-21T05:47:20.000Z | 2019-09-21T05:47:20.000Z | #include "FileIO.h"
#include <fstream>
namespace FileIO
{
namespace
{
const std::string DELIM_ITEM = "item";
const std::string DELIM_UID = "UID";
const std::string DELIM_UPC = "UPC";
const std::string DELIM_NAME = "name";
const std::string DELIM_SIZE = "size";
const std::string DELIM_CATEGORY = "category";
const std::string DELIM_WHOLESALE = "wholesale";
const std::string DELIM_RETAIL = "retail";
const std::string DELIM_QUANTITY = "quantity";
/**
* @author Olivier Chan
*
* @brief Returns a substring of the passed string starting at the (skip + 1)th instance of "<delimiter>" and ending after the subsequent instance of "</delimiter>".
* The angle brackets and delimiters are removed from the substring.
* If skip is greater than the number of delimiters in the string, an empty string is returned.
*
* @detail Example: parseString("<txt>Foo</txt> <txt>Bar</txt>", "txt", 0) will return "Foo".
*
* @param str The string to parse. The string should contain "<delimiter>" and "</delimiter>" tags.
*
* @param delimiter The string to act as a delimiter. This function adds angle brackets around the delimiter, so they should not be included in the passed delimiter.
*
* @param skip The number of times to skip an instance of the delimiter.
*
* @return A substring of the passed string starting at the (skip + 1)th instance of "<delimiter>" and ending after the subsequent instance of "</delimiter>".
* The angle brackets and delimiters are removed from the substring.
* If skip is greater than the number of delimiters in the string, an empty string is returned.
*/
std::string parseString(const std::string& str, const std::string& delimiter, const int skip)
{
const std::string delimitBeg = "<" + delimiter + ">";
const std::string delimitEnd = "</" + delimiter + ">";
//Set the starting position to after the (skip)th delimiter
size_t startingPos = 0;
for (int i = 0; i < skip; i++)
{
const size_t delimiterPos = str.find(delimitEnd, startingPos);
if (delimiterPos != std::string::npos)
{
startingPos = str.find(delimitEnd, startingPos) + delimitEnd.length();
}
else
{
//The starting position is after the last delimiter, return an empty string
throw std::invalid_argument("Passed end of string.");
}
}
//From the starting position, find the positions of the first instances of the beginning and ending delimiters
const size_t delimitBegPos = str.find(delimitBeg, startingPos);
const size_t delimitEndPos = str.find(delimitEnd, startingPos);
//Return the substring between the beginning and ending delimiters
return str.substr(delimitBegPos + delimitBeg.length(), delimitEndPos - delimitBegPos - delimitBeg.length());
}
std::string parseString(const std::string& str, const std::string& delimiter)
{
const std::string delimitBeg = "<" + delimiter + ">";
const std::string delimitEnd = "</" + delimiter + ">";
//Find the positions of the first instances of the beginning and ending delimiters
const size_t delimitBegPos = str.find(delimitBeg);
const size_t delimitEndPos = str.find(delimitEnd);
if (delimitBegPos != std::string::npos)
{
return str.substr(delimitBegPos + delimitBeg.length(), delimitEndPos - delimitBegPos - delimitBeg.length());
}
else
{
//The delimiter doesn't exist in the string, return an empty string
return std::string();
}
}
/**
* @author Olivier Chan
*
* @brief Returns the contents of the file located at path as a string. If the file at path doesn't exist, returns an empty string.
*
* @param path The path of the file to convert contents to a string.
*
* @return The contents of the file from path as a string. If the file at path doesn't exist, returns an empty string.
*/
std::string fileToString(const std::string& path)
{
std::ifstream in(path, std::ios::ate);
if (in)
{
std::string str;
//Reserve space in the string to store the entire file, not strictly required
str.reserve(static_cast<size_t>(in.tellg()));
in.seekg(0, std::ios::beg);
//Store the entire file in the string by iterating from beginning to end
str.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
return str;
}
else
{
//If the file doesn't exist or isn't openable, throw an exception
throw std::invalid_argument("ERROR: File doesn't exist or is unopenable.");
}
}
/**
* getNumBooksInString
*
* @brief Returns the number of books in the string based on the book delimiter.
*
* @param str The string to search for books. In almost every case this should be the inventory string.
*
* @return Number of books in the string.
*/
int getNumItemsInString(const std::string& str)
{
int count = 0;
size_t pos = 0;
const std::string delimiter = "<" + DELIM_ITEM + ">";
pos = str.find(delimiter, pos);
while (pos != std::string::npos)
{
count++;
pos = str.find(delimiter, pos + delimiter.length());
}
return count;
}
/**
* @brief Turns an item into a string, formatted into the form used in the inventory file.
*
* @param item The item to turn into a string.
*
* @return The item as a database formatted string.
*/
std::string itemToString(const Item& item)
{
std::string wholesaleString = std::to_string(item.wholesale);
wholesaleString = wholesaleString.substr(0, wholesaleString.find('.') + 3);
std::string retailString = std::to_string(item.retail);
retailString = retailString.substr(0, retailString.find('.') + 3);
std::string itemString =
"<" + DELIM_ITEM + ">" + "\n"
+ "\t" + "<" + DELIM_UID + ">" + std::to_string(item.uid) + "</" + DELIM_UID + ">" + "\n"
+ "\t" + "<" + DELIM_UPC + ">" + item.upc + "</" + DELIM_UPC + ">" + "\n"
+ "\t" + "<" + DELIM_NAME + ">" + item.name + "</" + DELIM_NAME + ">" + "\n"
+ "\t" + "<" + DELIM_SIZE + ">" + item.size + "</" + DELIM_SIZE + ">" + "\n"
+ "\t" + "<" + DELIM_CATEGORY + ">" + std::to_string(item.category) + "</" + DELIM_CATEGORY + ">" + "\n"
+ "\t" + "<" + DELIM_WHOLESALE + ">" + wholesaleString + "</" + DELIM_WHOLESALE + ">" + "\n"
+ "\t" + "<" + DELIM_RETAIL + ">" + retailString + "</" + DELIM_RETAIL + ">" + "\n"
+ "\t" + "<" + DELIM_QUANTITY + ">" + std::to_string(item.quantity) + "</" + DELIM_QUANTITY + ">" "\n"
"</" + DELIM_ITEM + ">" + "\n";
return itemString;
}
}
void loadFileIntoArray(Array<Item>& arr, const std::string& filePath)
{
if (arr.getSize() > 0)
{
throw std::invalid_argument("ERROR: Array is not empty.");
}
const std::string itemsString = fileToString(filePath);
const int numItems = getNumItemsInString(itemsString);
for (int i = 0; i < numItems; i++)
{
const std::string itemString = parseString(itemsString, DELIM_ITEM, i);
int uid;
std::string upc;
std::string name;
std::string size;
int category;
double wholesale;
double retail;
int quantity;
//UID - must be validated
const std::string uidString = parseString(itemString, DELIM_UID);
if (uidString.empty())
{
throw std::runtime_error("ERROR: Database file corrupted - UID missing.");
}
else
{
try
{
uid = std::stoi(uidString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - UID corrupted.");
}
}
//UPC
upc = parseString(itemString, DELIM_UPC);
//Name
name = parseString(itemString, DELIM_NAME);
//Size
size = parseString(itemString, DELIM_SIZE);
//Category
const std::string categoryString = parseString(itemString, DELIM_CATEGORY);
if (categoryString.empty())
{
category = 0;
}
else
{
try
{
category = std::stoi(categoryString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Category corrupted.");
}
}
//Wholesale
const std::string wholesaleString = parseString(itemString, DELIM_WHOLESALE);
if (wholesaleString.empty())
{
wholesale = 0;
}
else
{
try
{
wholesale = std::stod(wholesaleString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Wholesale price corrupted.");
}
}
//Retail
const std::string retailString = parseString(itemString, DELIM_RETAIL);
if (retailString.empty())
{
retail = 0;
}
else
{
try
{
retail = std::stod(retailString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Retail price corrupted.");
}
}
//Quantity
const std::string quantityString = parseString(itemString, DELIM_QUANTITY);
if (quantityString.empty())
{
quantity = 0;
}
else
{
try
{
quantity = std::stoi(quantityString);
}
catch (...)
{
throw std::runtime_error("ERROR: Database file corrupted - Quantity corrupted.");
}
}
arr.append(Item(std::move(uid), std::move(upc), std::move(name), std::move(size), std::move(category), std::move(wholesale), std::move(retail), std::move(quantity)));
}
}
void saveListIntoFile(List<Item>& list, const std::string& filePath)
{
std::string itemsString = std::string();
for (int i = 0; i < list.getCount(); i++)
{
itemsString.append(itemToString(list[i]));
}
std::ofstream os;
os.open(filePath);
os << itemsString;
os.close();
}
} | 30.957516 | 169 | 0.642141 | LEmilio14 |
de63176edfd38e0490bd86abb93f4fd8d314789d | 2,822 | cpp | C++ | semester2/prog-basics/Lab3a SortComparison/src/DemoMode.cpp | gardenappl/uni | 5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8 | [
"WTFPL"
] | null | null | null | semester2/prog-basics/Lab3a SortComparison/src/DemoMode.cpp | gardenappl/uni | 5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8 | [
"WTFPL"
] | null | null | null | semester2/prog-basics/Lab3a SortComparison/src/DemoMode.cpp | gardenappl/uni | 5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8 | [
"WTFPL"
] | null | null | null | #include <iostream>
#include "DemoMode.h"
#include "Point.h"
#include "Sort.h"
#include <algorithm>
#include <iterator>
namespace sort
{
void DemoMode::run()
{
char input = 0;
while(input != 'd' && input != 'c')
{
std::cout << "Print out coordinates for points (c) or only print the distance from origin (d)?" << std::endl;
std::cin >> input;
}
if(input == 'd')
sort::Point::print_distance = true;
std::cout << "Enter array size: ";
int array_size;
std::cin >> array_size;
Point* input_array = new Point[array_size];
for(int i = 0; i < array_size; i++)
{
input_array[i] = Point::make_random();
}
Point* test_array = new Point[array_size];
std::cout << "\n\nInsertion sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::insertion_sort(test_array, array_size, true);
std::cout << "\n\nQuick sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::quick_sort(test_array, array_size, true);
std::cout << "\n\nMerge sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::merge_sort(test_array, array_size, true);
std::cout << "\n\nMerge sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::merge_sort(test_array, array_size, true);
std::cout << "\n\nMerge sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::merge_sort(test_array, array_size, true);
std::cout << "\n\nMerge sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::merge_sort(test_array, array_size, true);
std::cout << "\n\nOptimized sort: (please enter \"small array size\"): ";
int small_array_size;
std::cin >> small_array_size;
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
sort::merge_sort_optimized(test_array, array_size, small_array_size, true);
std::cout << "\n\nstd::sort:\n";
std::copy(input_array, input_array + array_size, test_array);
sort::print_array(test_array, 0, array_size);
std::sort(test_array, test_array + array_size);
sort::print_array(test_array, 0, array_size);
delete input_array;
}
}
| 35.275 | 121 | 0.608788 | gardenappl |
de644c9121d2c4979dc1e482b0ccf025b86ce39e | 638 | cpp | C++ | done/blist2.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | done/blist2.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | done/blist2.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | #include <algorithm>
#include <fstream>
#include <iostream>
using namespace std;
int N;
int S[101], T[101], B[101]; //start, end, buckets
int main(void) {
ifstream fin ("blist.in");
ofstream fout ("blist.out");
fin>>N;
for (int i=1; i<=N; i++) {
fin>>S[i]>>T[i]>>B[i];
}
int max_buckets=0;
for (int t=1; t<=1000; t++) { //time
int buckets_at_time=0;
for (int i=1; i<=N; i++) {
if (S[i] <= t && t <= T[i]) {
buckets_at_time+=B[i];
}
}
max_buckets=max(max_buckets, buckets_at_time); //finding max
}
fout<<max_buckets;
}
| 22.785714 | 68 | 0.504702 | birdhumming |
de667200b1edc16c4a6733f4a8050b9fb5ec4a99 | 22,013 | cpp | C++ | resultswindow.cpp | DOMjudge/DOMjura | 271e579713995b75be3d6fef289c6c714f26f1b4 | [
"MIT"
] | 9 | 2019-04-23T08:07:08.000Z | 2021-12-04T07:11:35.000Z | resultswindow.cpp | DOMjudge/DOMjura | 271e579713995b75be3d6fef289c6c714f26f1b4 | [
"MIT"
] | 5 | 2019-04-24T05:45:35.000Z | 2021-10-08T06:48:09.000Z | resultswindow.cpp | nickygerritsen/DOMjura | 271e579713995b75be3d6fef289c6c714f26f1b4 | [
"MIT"
] | 6 | 2015-06-26T14:00:23.000Z | 2019-04-22T02:59:31.000Z | #include "resultswindow.h"
#include <QKeyEvent>
#include <QApplication>
#include <QDesktopWidget>
#include <QPropertyAnimation>
#include <QtOpenGL/QtOpenGL>
#include <QTimer>
#include <QSettings>
#include <math.h>
#include "gradientcache.h"
#include "defines.h"
#include "contest.h"
namespace DJ {
namespace View {
ResultsWindow::ResultsWindow(QWidget *parent) : QGraphicsView(parent) {
setFrameShape(QFrame::NoFrame);
this->started = false;
this->offset = 0.0;
this->canDoNextStep = true;
this->resolvDone = false;
this->lastResolvTeam = -1;
this->currentResolvIndex = -1;
this->scene = new QGraphicsScene(this);
this->scene->setSceneRect(QApplication::desktop()->screenGeometry());
this->scene->setBackgroundBrush(Qt::black);
this->setScene(this->scene);
this->setGeometry(QApplication::desktop()->screenGeometry());
this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->centerOn(0, 0);
this->setViewportUpdateMode(FullViewportUpdate);
this->setCacheMode(CacheBackground);
this->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
if (USE_OPENGL) {
this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
} else {
this->setViewport(new QWidget);
}
this->headerItem = new HeaderGraphicsItem(QApplication::desktop()->screenGeometry().width());
this->headerItem->setPos(0, 0);
this->legendaItem = new LegendaGraphicsItem();
QRectF legendaRect = this->legendaItem->boundingRect();
this->legendaItem->setPos(QApplication::desktop()->screenGeometry().width() - legendaRect.width() - LEGENDA_RIGHT_OFFSET,
QApplication::desktop()->screenGeometry().height() - legendaRect.height() - LEGENDA_BOTTOM_OFFSET);
this->legendaItem->setZValue(1);
this->winnerItem = new WinnerGraphicsItem;
this->winnerItem->setPos(0, 0);
this->winnerItem->setZValue(2);
this->winnerItem->setOpacity(0);
this->pixmap = new QGraphicsPixmapItem;
this->pixmap->setZValue(1);
this->scene->addItem(this->pixmap);
this->scene->addItem(this->headerItem);
this->scene->addItem(this->legendaItem);
this->scene->addItem(this->winnerItem);
}
void ResultsWindow::setTeams(QList<ResultTeam> teams, bool animated, int lastResolvedTeam, int lastResolvedProblem, int currentTeam) {
if (animated) {
if (this->lastResolvTeam >= 0) {
this->teamItems.at(this->lastResolvTeam)->setHighlighted(false);
}
// Save all data
this->teamsToSet = teams;
this->lastResolvTeam = lastResolvedTeam;
this->lastResolvProblem = lastResolvedProblem;
this->currentResolvIndex = currentTeam;
this->teamItems.at(this->lastResolvTeam)->setHighlighted(true);
int screenHeight = QApplication::desktop()->screenGeometry().height();
int itemToScrollHeight = HEADER_HEIGHT + (this->lastResolvTeam + 1) * TEAMITEM_HEIGHT + RESOLV_BELOW_OFFSET;
int toScroll = qMax(0, itemToScrollHeight - screenHeight);
QPointF toScrollPoint(0, toScroll);
if (this->headerItem->pos().y() == -toScroll) {
// start a timer that waits a second
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_WAIT);
} else {
// First, move to the the row to highlight
QParallelAnimationGroup *scrollToRowAnim = new QParallelAnimationGroup;
scrollToRowAnim->setProperty("DJ_animType", "toRow");
connect(scrollToRowAnim, SIGNAL(finished()), this, SLOT(animationDone()));
QPropertyAnimation *animHeader = new QPropertyAnimation(this->headerItem, "pos");
animHeader->setDuration(TIME_TO_SCROLL);
animHeader->setStartValue(this->headerItem->pos());
animHeader->setEndValue(QPointF(0, 0) - toScrollPoint);
scrollToRowAnim->addAnimation(animHeader);
for (int i = 0; i < this->teamItems.size(); i++) {
QPropertyAnimation *animItem = new QPropertyAnimation(this->teamItems.at(i), "pos");
animItem->setDuration(TIME_TO_SCROLL);
QPointF startPoint;
startPoint.setX(0);
startPoint.setY(HEADER_HEIGHT + i * TEAMITEM_HEIGHT);
QPointF newPoint = startPoint;
newPoint -= toScrollPoint;
animItem->setStartValue(this->teamItems.at(i)->pos());
animItem->setEndValue(newPoint);
scrollToRowAnim->addAnimation(animItem);
}
this->runningAnimations.append(scrollToRowAnim);
scrollToRowAnim->start();
}
} else {
for (int i = 0; i < this->teamItems.size(); i++) {
this->scene->removeItem(this->teamItems.at(i));
delete this->teamItems.at(i);
}
this->teamItems.clear();
if (teams.size() == 0) {
return;
}
this->teams = teams;
int numprobs = teams.at(0).problems.size();
GradientCache::getInstance()->setNumProbs(numprobs);
int probWidth = (NAME_WIDTH - (numprobs - 1) * PROB_MARGIN) / numprobs;
for (int i = 0; i < teams.size(); i++) {
QList<ResultProblem> problems = teams.at(i).problems;
if (problems.size() == 0) {
return;
}
QList<ProblemGraphicsItem *> problemItems;
for (int j = 0; j < numprobs; j++) {
ProblemGraphicsItem *probItem = new ProblemGraphicsItem(0, probWidth);
probItem->setProblemId(problems.at(j).problemId);
probItem->setState(problems.at(j).state);
probItem->setNumTries(problems.at(j).numTries);
probItem->setTime(problems.at(j).time);
problemItems.append(probItem);
}
TeamGraphicsItem *teamItem = new TeamGraphicsItem(problemItems);
teamItem->setRank(teams.at(i).rank);
teamItem->setName(teams.at(i).name);
teamItem->setSolved(teams.at(i).solved);
teamItem->setTime(teams.at(i).time);
if (this->lastResolvTeam >= 0 && i >= this->lastResolvTeam && i < GOLD) {
teamItem->setMedal(GOLD_MEDAL);
} else if (this->lastResolvTeam >= 0 && i >= this->lastResolvTeam && i < SILVER) {
teamItem->setMedal(SILVER_MEDAL);
} else if (this->lastResolvTeam >= 0 && i >= this->lastResolvTeam && i < BRONZE) {
teamItem->setMedal(BRONZE_MEDAL);
} else {
teamItem->setMedal(NO_MEDAL);
}
teamItem->setPos(0, HEADER_HEIGHT + i * TEAMITEM_HEIGHT + this->offset);
teamItem->setEven(i % 2 == 0);
this->teamItems.append(teamItem);
this->scene->addItem(teamItem);
}
}
}
void ResultsWindow::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Escape:
case Qt::Key_Q:
case Qt::Key_X:
close();
break;
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Space:
if (this->canDoNextStep) {
doNextStep();
}
}
}
void ResultsWindow::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
if (this->canDoNextStep) {
doNextStep();
}
}
}
void ResultsWindow::stopAnimations() {
foreach (QAbstractAnimation *animation, this->runningAnimations) {
animation->stop();
delete animation;
}
this->runningAnimations.clear();
foreach (QTimer *timer, this->runningTimers) {
timer->stop();
delete timer;
}
this->runningTimers.clear();
}
void ResultsWindow::reload() {
if (USE_OPENGL) {
this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
} else {
this->setViewport(new QWidget);
}
QString filename = BRANDING_IMAGE;
// Update branding image
if (!filename.isEmpty()) {
QPixmap pixmap(filename);
if (!pixmap.isNull()) {
this->pixmap->setPixmap(pixmap);
} else {
this->pixmap->setPixmap(QPixmap());
}
} else {
this->pixmap->setPixmap(QPixmap());
}
resizeImage();
this->offset = 0.0;
this->started = false;
this->canDoNextStep = true;
this->currentResolvIndex = -1;
this->lastResolvTeam = -1;
this->resolvDone = false;
this->headerItem->setPos(0, 0);
this->winnerItem->setOpacity(0);
this->hideLegendAfterTimeout();
}
void ResultsWindow::setResolvDone() {
this->resolvDone = true;
this->canDoNextStep = true;
}
void ResultsWindow::hideLegendAfterTimeout() {
this->legendaItem->setOpacity(1);
QRectF legendaRect = this->legendaItem->boundingRect();
this->legendaItem->setPos(QApplication::desktop()->screenGeometry().width() - legendaRect.width() - LEGENDA_RIGHT_OFFSET,
QApplication::desktop()->screenGeometry().height() - legendaRect.height() - LEGENDA_BOTTOM_OFFSET);
QTimer *legendaTimer = new QTimer(this);
legendaTimer->setSingleShot(true);
connect(legendaTimer, SIGNAL(timeout()), this, SLOT(hideLegenda()));
this->runningTimers.append(legendaTimer);
legendaTimer->start(LEGEND_WAIT_TIME);
}
void ResultsWindow::doNextStep() {
if (!this->started) {
this->canDoNextStep = false;
QParallelAnimationGroup *scrollToBottomAnim = new QParallelAnimationGroup;
connect(scrollToBottomAnim, SIGNAL(finished()), this, SLOT(animationDone()));
int screenHeight = QApplication::desktop()->screenGeometry().height();
int totalItemsHeight = HEADER_HEIGHT + this->teamItems.size() * TEAMITEM_HEIGHT + SCROLL_BELOW_OFFSET;
int toScroll = qMax(0, totalItemsHeight - screenHeight);
QPointF toScrollPoint(0, toScroll);
if (toScroll == 0) {
delete scrollToBottomAnim;
this->started = true;
doNextStep();
} else {
int timetoScroll = TIME_TO_WAIT + TIME_PER_ITEM * log(this->teamItems.size());
QPropertyAnimation *animHeader = new QPropertyAnimation(this->headerItem, "pos");
animHeader->setDuration(timetoScroll);
animHeader->setEasingCurve(QEasingCurve::OutBack);
animHeader->setStartValue(QPointF(0, 0));
animHeader->setEndValue(QPointF(0, 0) - toScrollPoint);
scrollToBottomAnim->addAnimation(animHeader);
for (int i = 0; i < this->teamItems.size(); i++) {
QPropertyAnimation *animItem = new QPropertyAnimation(this->teamItems.at(i), "pos");
animItem->setDuration(timetoScroll);
animItem->setEasingCurve(QEasingCurve::OutBack);
QPointF startPoint;
startPoint.setX(0);
startPoint.setY(HEADER_HEIGHT + i * TEAMITEM_HEIGHT);
QPointF newPoint = startPoint;
newPoint -= toScrollPoint;
animItem->setStartValue(startPoint);
animItem->setEndValue(newPoint);
scrollToBottomAnim->addAnimation(animItem);
}
scrollToBottomAnim->setProperty("DJ_animType", "scrollToBottom");
this->runningAnimations.append(scrollToBottomAnim);
scrollToBottomAnim->start();
}
} else if (this->resolvDone) {
this->canDoNextStep = false;
if (this->teams.isEmpty()) {
this->winnerItem->setWinner("No teams selected");
} else {
ResultTeam winningTeam = this->teams.at(0);
this->winnerItem->setWinner(winningTeam.name);
}
QPropertyAnimation *winnerAnim = new QPropertyAnimation(this->winnerItem, "opacity");
winnerAnim->setDuration(TIME_FOR_WINNER);
winnerAnim->setStartValue(0);
winnerAnim->setEndValue(1);
winnerAnim->setProperty("DJ_animType", "winner");
this->runningAnimations.append(winnerAnim);
winnerAnim->start();
} else {
this->canDoNextStep = false;
emit newStandingNeeded();
}
}
void ResultsWindow::animationDone() {
this->runningAnimations.removeAll((QAbstractAnimation *)this->sender());
this->sender()->deleteLater();
if (this->sender()->property("DJ_animType") == "scrollToBottom") {
this->started = true;
this->canDoNextStep = true;
} else if (this->sender()->property("DJ_animType") == "toRow") {
// start a timer that waits a second
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_WAIT);
} else if (this->sender()->property("DJ_animType") == "problemResolv") {
TeamGraphicsItem *team = this->teamItems.at(this->lastResolvTeam);
ProblemGraphicsItem *problem = team->getProblemGraphicsItem(this->lastResolvProblem);
problem->setHighlighted(false);
if (problem->isSolved()) {
problem->setState(SOLVED);
// Determine where to move the row to
int moveTo = this->lastResolvTeam;
while (this->teamsToSet.at(moveTo).id != this->teams.at(this->lastResolvTeam).id) {
moveTo--;
}
TeamGraphicsItem *teamThatMoves = this->teamItems.at(this->lastResolvTeam);
ResultTeam resultTeam = this->teamsToSet.at(moveTo);
teamThatMoves->setRank(resultTeam.rank);
teamThatMoves->setTime(resultTeam.time);
teamThatMoves->setSolved(resultTeam.solved);
int tme = TIME_TO_MOVE_INIT + TIME_TO_MOVE * (this->lastResolvTeam - moveTo);
if (tme == TIME_TO_MOVE_INIT) {
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerMoveUpDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_MOVE);
} else {
// Now move the current team to moveTo and move all teams from moveTo until the current team one down
QPointF moveToPoint = this->teamItems.at(moveTo)->pos();
QParallelAnimationGroup *moveAnim = new QParallelAnimationGroup;
QPropertyAnimation *moveUpAnim = new QPropertyAnimation(this->teamItems.at(this->lastResolvTeam), "pos");
connect(moveAnim, SIGNAL(finished()), this, SLOT(animationDone()));
moveUpAnim->setDuration(tme);
moveUpAnim->setStartValue(this->teamItems.at(this->lastResolvTeam)->pos());
moveUpAnim->setEndValue(moveToPoint);
moveAnim->addAnimation(moveUpAnim);
// Update standings
for (int i = moveTo; i < this->teamItems.size(); i++) {
if (i != this->lastResolvTeam) {
TeamGraphicsItem *team = this->teamItems.at(i);
ResultTeam resultTeamToSet;
if (i < this->lastResolvTeam) {
resultTeamToSet = this->teamsToSet.at(i+1);
} else {
resultTeamToSet = this->teamsToSet.at(i);
}
team->setRank(resultTeamToSet.rank);
}
}
for (int i = moveTo; i < this->lastResolvTeam; i++) {
TeamGraphicsItem *team = this->teamItems.at(i);
QPropertyAnimation *moveDownAnim = new QPropertyAnimation(team, "pos");
moveDownAnim->setDuration(tme);
moveDownAnim->setStartValue(team->pos());
moveDownAnim->setEndValue(team->pos() + QPointF(0, TEAMITEM_HEIGHT));
moveAnim->addAnimation(moveDownAnim);
}
this->runningAnimations.append(moveAnim);
moveAnim->setProperty("DJ_animType", "moveTeam");
moveAnim->start();
}
} else { // if the problem is not solved, just go to the next resolv
this->offset = this->headerItem->pos().y();
this->setTeams(this->teamsToSet);
doNextStep();
}
} else if (this->sender()->property("DJ_animType") == "moveTeam") {
QTimer *timer = new QTimer;
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(timerMoveUpDone()));
this->runningTimers.append(timer);
timer->start(TIME_TO_MOVE_INIT);
} else if (this->sender()->property("DJ_animType") == "winner") {
// Do nothing...
}
}
void ResultsWindow::timerDone() {
this->runningTimers.removeAll((QTimer *)this->sender());
this->sender()->deleteLater();
if (this->lastResolvTeam == this->currentResolvIndex) {
// Animate problem highlight
TeamGraphicsItem *team = this->teamItems.at(this->lastResolvTeam);
ProblemGraphicsItem *problem = team->getProblemGraphicsItem(this->lastResolvProblem);
problem->setHighlighted(true);
QPropertyAnimation *animHLC = new QPropertyAnimation(problem, "highlightColor");
animHLC->setDuration(TIME_TO_BLINK);
animHLC->setKeyValueAt(0, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.125, QColor(70, 62, 14));
animHLC->setKeyValueAt(0.25, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.375, QColor(70, 62, 14));
animHLC->setKeyValueAt(0.5, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.625, QColor(70, 62, 14));
animHLC->setKeyValueAt(0.75, QColor(143, 124, 29));
animHLC->setKeyValueAt(0.875, QColor(70, 62, 14));
if (problem->isSolved()) {
animHLC->setKeyValueAt(1, QColor(0, 128, 0));
} else {
animHLC->setKeyValueAt(1, QColor(133, 0, 0));
}
QPropertyAnimation *animFC = new QPropertyAnimation(problem, "finalColor");
animFC->setDuration(TIME_TO_BLINK);
animFC->setKeyValueAt(0, QColor(255, 223, 54));
animFC->setKeyValueAt(0.125, QColor(255, 223, 54));
animFC->setKeyValueAt(0.25, QColor(255, 223, 54));
animFC->setKeyValueAt(0.375, QColor(255, 223, 54));
animFC->setKeyValueAt(0.5, QColor(255, 223, 54));
animFC->setKeyValueAt(0.625, QColor(255, 223, 54));
animFC->setKeyValueAt(0.75, QColor(255, 223, 54));
animFC->setKeyValueAt(0.875, QColor(255, 223, 54));
if (problem->isSolved()) {
animFC->setKeyValueAt(1, QColor(0, 230, 0));
} else {
animFC->setKeyValueAt(1, QColor(240, 0, 0));
}
QParallelAnimationGroup *parAnim = new QParallelAnimationGroup;
parAnim->addAnimation(animHLC);
parAnim->addAnimation(animFC);
parAnim->setProperty("DJ_animType", "problemResolv");
this->runningAnimations.append(parAnim);
connect(parAnim, SIGNAL(finished()), this, SLOT(animationDone()));
parAnim->start();
} else {
this->offset = this->headerItem->pos().y();
this->setTeams(this->teamsToSet);
this->teamItems.at(this->lastResolvTeam)->setHighlighted(true);
if (this->lastResolvTeam >= NEED_TO_CLICK) {
doNextStep();
} else {
this->canDoNextStep = true;
}
}
}
void ResultsWindow::timerMoveUpDone() {
this->runningTimers.removeAll((QTimer *)this->sender());
this->sender()->deleteLater();
this->offset = this->headerItem->pos().y();
this->setTeams(this->teamsToSet);
doNextStep();
}
void ResultsWindow::resizeImage() {
QSize size;
if (!this->pixmap->pixmap().isNull()) {
size = this->pixmap->pixmap().size();
} else {
size = QSize(0, 0);
}
QRect screenSize = QApplication::desktop()->screenGeometry();
QPointF labelPos;
labelPos.setX(screenSize.width() - size.width() - BRANDING_IMAGE_OFFSET_X);
labelPos.setY(screenSize.height() - size.height() - BRANDING_IMAGE_OFFSET_Y);
this->pixmap->setPos(labelPos);
}
void ResultsWindow::hideLegenda() {
this->runningTimers.removeAll((QTimer *)this->sender());
this->sender()->deleteLater();
QPropertyAnimation *legendaAnim = new QPropertyAnimation(this->legendaItem, "opacity");
legendaAnim->setDuration(LEGEND_HIDE_TIME);
legendaAnim->setEasingCurve(QEasingCurve::InOutExpo);
legendaAnim->setStartValue(1);
legendaAnim->setEndValue(0);
this->runningAnimations.append(legendaAnim);
legendaAnim->setProperty("DJ_animType", "legenda");
legendaAnim->start();
}
int ResultsWindow::getCurrentResolvIndex() {
return this->currentResolvIndex;
}
ResultTeam ResultsWindow::getResultTeam(int i) {
return this->teams.at(i);
}
void ResultsWindow::setContest(Model::Contest *contest) {
this->winnerItem->setContestName(contest->getName());
}
} // namespace View
} // namespace DJ
| 41.37782 | 135 | 0.592968 | DOMjudge |
de6c98ed7e226f6109bc8274ffbd2160d5e7e07c | 530 | cpp | C++ | src/skills/vision/vision.cpp | GiulianoWF/RIDGS | 4acde23988e088b4f9a82c27bae67100ed83de5b | [
"MIT"
] | null | null | null | src/skills/vision/vision.cpp | GiulianoWF/RIDGS | 4acde23988e088b4f9a82c27bae67100ed83de5b | [
"MIT"
] | null | null | null | src/skills/vision/vision.cpp | GiulianoWF/RIDGS | 4acde23988e088b4f9a82c27bae67100ed83de5b | [
"MIT"
] | null | null | null | #include <iostream>
#include <opencv2/core.hpp>
#include "RIDGS_com.hpp"
int main(){
auto server_communication = ridgs::ProcessServerCOM("vision");
std::cout << "vision::working" << std::endl;
auto mat = cv::Mat();
std::string read;
server_communication >> read;
std::cout << "vision:Recieved from server (" << read << ")" << std::endl;
std::cout << "vision::Sending to server an number: 2" << std::endl;
server_communication.send(std::string{"1"});
std::cout << "vision::end working" << std::endl;
}
| 24.090909 | 75 | 0.639623 | GiulianoWF |
de6fbc5f6f6105bfb30d1270b51f1d446087c00e | 3,010 | cpp | C++ | libnaucrates/src/operators/CDXLScalarIndexCondList.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libnaucrates/src/operators/CDXLScalarIndexCondList.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libnaucrates/src/operators/CDXLScalarIndexCondList.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CDXLScalarIndexCondList.cpp
//
// @doc:
// Implementation of DXL index condition lists for DXL index scan operator
//---------------------------------------------------------------------------
#include "naucrates/dxl/operators/CDXLScalarIndexCondList.h"
#include "naucrates/dxl/operators/CDXLNode.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
using namespace gpos;
using namespace gpdxl;
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::CDXLScalarIndexCondList
//
// @doc:
// ctor
//
//---------------------------------------------------------------------------
CDXLScalarIndexCondList::CDXLScalarIndexCondList
(
IMemoryPool *pmp
)
:
CDXLScalar(pmp)
{
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::Edxlop
//
// @doc:
// Operator type
//
//---------------------------------------------------------------------------
Edxlopid
CDXLScalarIndexCondList::Edxlop() const
{
return EdxlopScalarIndexCondList;
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::PstrOpName
//
// @doc:
// Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLScalarIndexCondList::PstrOpName() const
{
return CDXLTokens::PstrToken(EdxltokenScalarIndexCondList);
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::SerializeToDXL
//
// @doc:
// Serialize operator in DXL format
//
//---------------------------------------------------------------------------
void
CDXLScalarIndexCondList::SerializeToDXL
(
CXMLSerializer *pxmlser,
const CDXLNode *pdxln
)
const
{
const CWStringConst *pstrElemName = PstrOpName();
pxmlser->OpenElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
pdxln->SerializeChildrenToDXL(pxmlser);
pxmlser->CloseElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CDXLScalarIndexCondList::AssertValid
//
// @doc:
// Checks whether operator node is well-structured
//
//---------------------------------------------------------------------------
void
CDXLScalarIndexCondList::AssertValid
(
const CDXLNode *pdxln,
BOOL fValidateChildren
)
const
{
GPOS_ASSERT(NULL != pdxln);
if (fValidateChildren)
{
const ULONG ulArity = pdxln->UlArity();
for (ULONG ul = 0; ul < ulArity; ul++)
{
CDXLNode *pdxlnChild = (*pdxln)[ul];
GPOS_ASSERT(EdxloptypeScalar == pdxlnChild->Pdxlop()->Edxloperatortype());
pdxlnChild->Pdxlop()->AssertValid(pdxlnChild, fValidateChildren);
}
}
}
#endif // GPOS_DEBUG
// EOF
| 25.083333 | 86 | 0.509635 | khannaekta |
de711760fec74ea2eb2739d540b16704726d40b8 | 8,384 | cpp | C++ | src/game/client/neotokyo/neo_hud_weapon.cpp | L-Leite/neotokyo-re | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 4 | 2017-08-29T15:39:53.000Z | 2019-06-04T07:37:48.000Z | src/game/client/neotokyo/neo_hud_weapon.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | null | null | null | src/game/client/neotokyo/neo_hud_weapon.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 1 | 2021-08-10T20:01:00.000Z | 2021-08-10T20:01:00.000Z | #include "cbase.h"
#include "hud.h"
#include "hud_macros.h"
#include "view.h"
#include "iclientmode.h"
#include <KeyValues.h>
#include <vgui/ISystem.h>
#include <vgui/ISurface.h>
#include <vgui/ILocalize.h>
#include "hudelement.h"
#include "neo_hud_numericdisplay.h"
#include "c_neo_player.h"
#include "weapon_neobase.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Health panel
//-----------------------------------------------------------------------------
class CNHudWeapon : public CHudElement, public CNHudNumericDisplay
{
DECLARE_CLASS_SIMPLE( CNHudWeapon, CNHudNumericDisplay );
public:
CNHudWeapon( const char *pElementName );
virtual void Init();
virtual void VidInit();
virtual void OnThink();
virtual void Paint();
virtual void DrawNumber( vgui::HFont hFont, int x, int y, int number );
void DrawBullets( vgui::HFont hFont, int x, int y, int iClip, int iDefaultClip );
void DrawWeaponIcon( vgui::HFont hFont );
void DrawWeaponName( vgui::HFont hFont );
void CopyWeaponName( wchar_t* szNewWepName );
private:
CPanelAnimationVarAliasType( float, m_flDigit_XPos, "digit_xpos", "50", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flDigit_YPos, "digit_ypos", "2", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flDigit2_XPos, "digit2_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flDigit2_YPos, "digit2_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_XPos, "bar_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_YPos, "bar_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_Width, "bar_width", "2", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flBar_Height, "bar_height", "2", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flIcon_XPos, "icon_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flIcon_YPos, "icon_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flText_XPos, "text_xpos", "8", "proportional_float" );
CPanelAnimationVarAliasType( float, m_flText_YPos, "text_ypos", "20", "proportional_float" );
CPanelAnimationVar( Color, m_TextColor, "TextColor", "FgColor" );
CPanelAnimationVar( vgui::HFont, m_hTFont, "TextFont", "NHudOCRSmall" );
CPanelAnimationVar( vgui::HFont, m_hNumberFont, "NumberFont", "NHudOCR" );
CPanelAnimationVar( vgui::HFont, m_hNumberGlowFont, "NumberGlowFont", "NHudOCRBlur" );
CPanelAnimationVar( vgui::HFont, m_hBulletFont, "HudBulletsFont", "NHudBullets" );
int m_iWhiteAdditiveTexture;
wchar_t m_szWeaponName[ 16 ];
EHANDLE m_hCurrentWeapon;
int m_iClip1;
int m_iDefaultClip;
int m_iAmmoCount;
wchar_t m_uBulletChar;
wchar_t m_uWeaponChar;
bool m_bUsesClips;
};
DECLARE_HUDELEMENT_DEPTH( CNHudWeapon, 50 );
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CNHudWeapon::CNHudWeapon( const char *pElementName ) : CHudElement( pElementName ), CNHudNumericDisplay( nullptr, "NHudWeapon" )
{
vgui::Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
SetHiddenBits( HIDEHUD_PLAYERDEAD | HIDEHUD_HEALTH | HIDEHUD_WEAPONSELECTION );
m_iWhiteAdditiveTexture = surface()->CreateNewTextureID();
surface()->DrawSetTextureFile( m_iWhiteAdditiveTexture, "vgui/white_additive", true, false );
}
void CNHudWeapon::Init()
{
m_iClip1 = -1;
m_iDefaultClip = -1;
m_iAmmoCount = -1;
m_uBulletChar = L'a';
m_uWeaponChar = L'h';
}
void CNHudWeapon::VidInit()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNHudWeapon::OnThink()
{
C_NEOPlayer* pLocalPlayer = C_NEOPlayer::GetLocalNEOPlayer();
if ( pLocalPlayer )
{
C_WeaponNEOBase* pWeapon = pLocalPlayer->GetActiveNEOWeapon();
if ( pWeapon )
{
SetPaintEnabled( true );
SetPaintBackgroundEnabled( true );
if ( pWeapon == m_hCurrentWeapon )
{
m_iClip1 = pWeapon->Clip1();
m_iAmmoCount = pLocalPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() );
if ( pWeapon->GetUnknown1452() )
m_iAmmoCount /= pWeapon->GetDefaultClip1();
m_uWeaponChar = pWeapon->GetWeaponChar();
}
else
{
m_hCurrentWeapon = pWeapon;
m_iClip1 = pWeapon->Clip1();
m_iDefaultClip = pWeapon->GetDefaultClip1();
m_uBulletChar = pWeapon->GetNEOWpnData().m_szBulletCharacter[0];
m_iAmmoCount = pLocalPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() );
if ( pWeapon->GetUnknown1452() )
m_iAmmoCount /= pWeapon->GetDefaultClip1();
m_bUsesClips = pWeapon->UsesClipsForAmmo1();
}
return;
}
}
SetPaintEnabled( false );
SetPaintBackgroundEnabled( false );
}
void CNHudWeapon::Paint()
{
int wide, tall;
GetSize( wide, tall );
DrawBox( 0, 0, wide + wide / 2, tall, Color( 200, 200, 200, 28 ), 1.0f );
C_NEOPlayer* pLocalPlayer = C_NEOPlayer::GetLocalNEOPlayer();
if ( !pLocalPlayer )
return;
C_WeaponNEOBase* pWeapon = pLocalPlayer->GetActiveNEOWeapon();
if ( !pWeapon )
return;
surface()->DrawSetTextColor( 255, 255, 255, 150 );
if ( pWeapon->HasAmmoClip() )
{
int iDefaultClip = 30;
if ( m_iDefaultClip <= 30 )
iDefaultClip = m_iDefaultClip;
int iClip = m_iClip1;
if ( iClip > 30 )
iClip = 30;
DrawBullets( m_hBulletFont, m_flDigit_XPos, m_flDigit_YPos, iClip, iDefaultClip );
if ( m_bUsesClips )
{
surface()->DrawSetTextColor( 255, 255, 255, 100 );
DrawNumber( m_hNumberFont, m_flDigit2_XPos, m_flDigit2_YPos, m_iAmmoCount );
DrawWeaponIcon( m_hBulletFont );
}
}
wchar_t weaponName[ 16 ];
g_pVGuiLocalize->ConvertANSIToUnicode( pWeapon->GetPrintName(), weaponName, sizeof( weaponName ) );
CopyWeaponName( weaponName );
DrawWeaponName( m_hTFont );
}
void CNHudWeapon::DrawNumber( HFont hFont, int x, int y, int number )
{
wchar_t buffer[ 10 ];
V_snwprintf( buffer, ARRAYSIZE( buffer ), L"%d", number );
int charWidth = surface()->GetCharacterWidth( hFont, 48 );
if ( number < 100 && m_Unknown246 )
x += charWidth;
if ( number < 10 && m_Unknown246 )
x += charWidth;
int textWide, textTall;
surface()->GetTextSize( hFont, buffer, textWide, textTall );
surface()->DrawSetTextPos( x - textWide, y );
surface()->DrawSetTextFont( hFont );
int bufLen = V_wcslen( buffer );
for ( int i = 0; i < bufLen; i++ )
surface()->DrawUnicodeChar( buffer[ i ] );
}
void CNHudWeapon::DrawBullets( HFont hFont, int x, int y, int iClip, int iDefaultClip )
{
wchar_t buffer[ 10 ];
V_snwprintf( buffer, ARRAYSIZE( buffer ), L"%d", iClip );
int bulletWidth = surface()->GetCharacterWidth( hFont, m_uBulletChar );
int textWide, textTall;
surface()->GetTextSize( hFont, buffer, textWide, textTall );
surface()->DrawSetTextPos( x - iDefaultClip * bulletWidth, y );
surface()->DrawSetTextFont( hFont );
if ( m_uBulletChar == L'd' )
surface()->DrawSetTextPos( x - bulletWidth * ( iDefaultClip + 1 ), y );
for ( int i = 0; i < iDefaultClip; i++ )
{
if ( i < iDefaultClip - iClip )
surface()->DrawSetTextColor( 255, 255, 255, 50 );
else
surface()->DrawSetTextColor( 255, 255, 255, 150 );
surface()->DrawUnicodeChar( m_uBulletChar );
}
}
void CNHudWeapon::DrawWeaponIcon( vgui::HFont hFont )
{
surface()->DrawSetTextPos( m_flIcon_XPos, m_flIcon_YPos );
surface()->DrawSetTextFont( hFont );
surface()->DrawSetTextColor( 255, 255, 255, 100 );
surface()->DrawUnicodeChar( m_uWeaponChar );
}
void CNHudWeapon::DrawWeaponName( vgui::HFont hFont )
{
surface()->DrawSetTextFont( hFont );
int textWide, textTall;
surface()->GetTextSize( hFont, m_szWeaponName, textWide, textTall );
surface()->DrawSetTextPos( m_flText_XPos - textWide, m_flText_YPos );
int bufLen = V_wcslen( m_szWeaponName );
for ( int i = 0; i < bufLen; i++ )
surface()->DrawUnicodeChar( m_szWeaponName[ i ] );
}
void CNHudWeapon::CopyWeaponName( wchar_t* szNewWepName )
{
V_wcsncpy( m_szWeaponName, szNewWepName, sizeof( m_szWeaponName ) );
m_uWeaponChar = 0;
}
| 28.420339 | 128 | 0.671517 | L-Leite |
de71c7d92d2d698230ad1886dda2b7837b009675 | 4,392 | cpp | C++ | src/threadpool.cpp | lingFlya/MyWebServer | 6c87995e19c76c873c8385ccb847d76e3dc62bff | [
"MIT"
] | null | null | null | src/threadpool.cpp | lingFlya/MyWebServer | 6c87995e19c76c873c8385ccb847d76e3dc62bff | [
"MIT"
] | 1 | 2020-09-06T07:57:02.000Z | 2020-09-12T14:32:25.000Z | src/threadpool.cpp | lingFlya/MyWebServer | 6c87995e19c76c873c8385ccb847d76e3dc62bff | [
"MIT"
] | null | null | null | /************************************************************************************
*@author RedDragon
*@date 2020/9/5
*@brief 线程池实现
* 就是通过pthread_create()创建固定线程数,省去了来一个任务才创建线程和销毁线程
* 的开销,我这里创建了四个固定线程,通过互斥量mutex和条件变量cond和一个任务队列task_queue添加任务
* 和完成任务.
*
* addTask是生产者
* worker是消费者
*************************************************************************************/
#include "threadpool.h"
#include <cstring>
// 消费者线程
void* threadPool::worker(void* arg)
{
if(arg == nullptr)
return nullptr;
threadPool* pool = (threadPool*)arg;
for(;;)
{
int err = pthread_mutex_lock(pool->mtx);
if(err != 0)
{
printf("errno = %d: %s", err, strerror(err));
break;
}
while (pool->taskCount <= 0)
pthread_cond_wait(pool->cond, pool->mtx);
// 拿到任务
Task tk = pool->taskQueue[pool->begin];
pool->begin += 1;
pool->taskCount -= 1;
err = pthread_mutex_unlock(pool->mtx);
if(err != 0)
{
printf("errno = %d: %s", err, strerror(err));
break;
}
// 执行任务
tk.func(tk.arg);
}
return nullptr;
}
/*
* @brief: 创建count个工作线程
* @return 成功创建的线程数
*/
int threadPool::createThread(int count)
{
int old = threadCount;
for(int i = 0; i < count; ++i)
{
pthread_t newTid;
int ret = pthread_create(&newTid, nullptr, worker, this);
if(ret != 0)
{// 内存等资源不够, 可能创建线程失败
printf("errno=%d: %s\n",ret, strerror(ret));
break;
}
else
{
printf("创建线程成功!\n");
tidVec.push_back(newTid);
threadCount++;
}
}
return threadCount - old;
}
// 构造函数(线程数初始为4)
threadPool::threadPool()
: threadPool(0)
{}
threadPool::threadPool(int count)
{
mtx = new pthread_mutex_t;
cond = new pthread_cond_t;
pthread_mutex_init(mtx, nullptr);
pthread_cond_init(cond, nullptr);
coreThreadCount = count;
threadCount = 0;
taskQueue = new Task[QUEUE_SIZE];
begin = end = taskCount = 0;
shutdown = false;
}
threadPool::~threadPool()
{
// 如果线程还在运行, 就join
// if(!shutdown)
// joinAll(THREADPOOL_GRACEFUL);
pthread_mutex_destroy(mtx);
pthread_cond_destroy(cond);
delete mtx;
delete cond;
delete[] taskQueue;
}
ThreadPoolStatus threadPool::addTask(Task tk)
{
int ret = pthread_mutex_lock(mtx); // 加锁
if(ret != 0)
{
printf("%s\n", strerror(ret));
return ThreadPoolStatus::LOCK_FAILURE;
}
int next = (end + 1)%QUEUE_SIZE;
ThreadPoolStatus err;
do{
if(taskCount == QUEUE_SIZE){
err = ThreadPoolStatus::QUEUE_FULL;
break;
}
if(shutdown){
err = ThreadPoolStatus::SHUTDOWN;
break;
}
// 创建线程
if(threadCount < maxThreadCount)
createThread(1);
// 增加任务
taskQueue[end] = tk;
++taskCount;
end = next;
// 通知工作线程
ret = pthread_cond_signal(cond);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
}while(false);
ret = pthread_mutex_unlock(mtx);// 解锁
if(ret != 0)
{
printf("%s\n", strerror(ret));
return ThreadPoolStatus::LOCK_FAILURE;
}
return err;
}
ThreadPoolStatus threadPool::joinAll()
{
int ret = pthread_mutex_lock(mtx);
if(ret != 0)
return ThreadPoolStatus::LOCK_FAILURE;
ThreadPoolStatus err;
do{
if(shutdown){
err = ThreadPoolStatus::SHUTDOWN;
break;
}
// 唤醒所有线程, 所有线程都会退出
ret = pthread_cond_broadcast(cond);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
ret = pthread_mutex_unlock(mtx);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
for(int i = 0; i < threadCount; ++i)
{
ret = pthread_join(tidVec.back(), nullptr);
if(ret != 0)
err = ThreadPoolStatus::LOCK_FAILURE;
--threadCount;
tidVec.pop_back();
}
shutdown = true;
}while(false);
return err;
} | 24.4 | 87 | 0.502277 | lingFlya |
de7286095e21275895928729783b3c6f179f3ae9 | 2,897 | cpp | C++ | trunk/ProjectFootball/src/singlePlayer/db/bean/CPfPhaseTypes.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | trunk/ProjectFootball/src/singlePlayer/db/bean/CPfPhaseTypes.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | trunk/ProjectFootball/src/singlePlayer/db/bean/CPfPhaseTypes.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | /******************************************************************************
* Copyright (C) 2010 - Ikaro Games www.ikarogames.com *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* *
* generated by dia/DAOcodegen.py *
* Version: 1.23 *
******************************************************************************/
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include "CPfPhaseTypes.h"
CPfPhaseTypes::CPfPhaseTypes()
{
m_SPhaseType = "";
m_XPhaseType = "0";
}
CPfPhaseTypes::CPfPhaseTypes(const CPfPhaseTypes &obj)
{
m_SPhaseType = obj.m_SPhaseType;
m_XPhaseType = obj.m_XPhaseType;
}
CPfPhaseTypes::~CPfPhaseTypes()
{
}
const std::string& CPfPhaseTypes::getSPhaseType() const
{
return m_SPhaseType;
}
const std::string& CPfPhaseTypes::getSPhaseType_str() const
{
return m_SPhaseType;
}
int CPfPhaseTypes::getXPhaseType() const
{
if( m_XPhaseType=="" ){
return 0;
}else{
return atoi(m_XPhaseType.c_str());
}
}
const std::string& CPfPhaseTypes::getXPhaseType_str() const
{
return m_XPhaseType;
}
void CPfPhaseTypes::setSPhaseType(const std::string &SPhaseType)
{
m_SPhaseType = SPhaseType;
}
void CPfPhaseTypes::setSPhaseType_str(const std::string &SPhaseType)
{
m_SPhaseType = SPhaseType;
}
void CPfPhaseTypes::setXPhaseType(int XPhaseType)
{
std::ostringstream stream;
stream << XPhaseType;
m_XPhaseType = stream.str();
}
void CPfPhaseTypes::setXPhaseType_str(const std::string &XPhaseType)
{
m_XPhaseType = XPhaseType;
}
| 31.835165 | 79 | 0.509838 | dividio |
de74d7c4918fd6a20d3e7fa062ba1669a51ee5bc | 3,393 | hpp | C++ | include/parserFuncs.hpp | kleidibujari/doit | 5f566992f0dd1118def6ccdfdff47243f82e9ae1 | [
"MIT"
] | null | null | null | include/parserFuncs.hpp | kleidibujari/doit | 5f566992f0dd1118def6ccdfdff47243f82e9ae1 | [
"MIT"
] | null | null | null | include/parserFuncs.hpp | kleidibujari/doit | 5f566992f0dd1118def6ccdfdff47243f82e9ae1 | [
"MIT"
] | null | null | null | #include <string>
#include <fstream>
#include <vector>
#include <iostream>
#define CONFIG "$HOME/.config/do-it/doit.conf"
#include "usage.hpp"
std::string FILELOC;
//writing to file for strings (tasks)
void writeFile(std::string val)
{
std::ofstream ptr(FILELOC, std::ios_base::app);
ptr << val << std::endl;
ptr.close();
}
std::string readFile(int taskNum)
{
std::ifstream ptr(FILELOC);
int currentLine = 1;
std::string temp;
if (ptr.is_open())
{
while (getline(ptr, temp))
{
if (currentLine == taskNum){break;}
currentLine++;
}
} else
{
temp = "err";
}
ptr.close();
return temp;
}
void listTasks()
{
std::cout << "\n=====<tasks>=====\n";
std::string s;
int sTotal = 0;
std::ifstream ptr(FILELOC);
while (getline(ptr, s))
{
sTotal++;
}
for (int i = 1; i < sTotal + 1; i++){
std::cout << i << ") " << readFile(i) << "\n";
}
std::cout << "=====</tasks>=====\n\n";
}
void removeTask(int taskNum)
{
std::string TEMPFILE = FILELOC;
TEMPFILE.erase(TEMPFILE.length(), TEMPFILE.length() - 7);
TEMPFILE += "temp.txt";
// open file in read mode or in mode
std::ifstream is(FILELOC);
// open file in write mode or out mode
std::ofstream ofs;
//ofs.open("../temp.txt", std::ofstream::out);
ofs.open(TEMPFILE.c_str(), std::ofstream::out);
// loop getting single characters
char c;
int line_no = 1;
while (is.get(c))
{
// if a newline character
if (c == '\n')
line_no++;
// file content not to be deleted
if (line_no != taskNum)
ofs << c;
}
// closing output file
ofs.close();
// closing input file
is.close();
// remove the original file
remove(FILELOC.c_str());
// rename the file
//rename("../temp.txt", FILELOC.c_str());
rename(TEMPFILE.c_str(), FILELOC.c_str());
}
void removeEmpty()
{
int lineNum = 1;
std::string temp;
std::fstream ptr(FILELOC);
while(std::getline(ptr, temp))
{
if (!temp.empty())
{
removeTask(lineNum);
}
lineNum++;
}
}
void parseLine(int argc, std::vector<std::string> &args)
{
//reading location of list from config file
std::fstream config(CONFIG);
getline(config, FILELOC);
if (args[0] == "-help")
{
printUsage();
config.close();
}
else if (args[0] == "-a")
{
std::string temp;
for (size_t i = 1; i < (argc - 1); i++)
{
temp = temp + args[i] + " ";
}
writeFile(temp);
config.close();
}
else if (args[0] == "-l")
{
listTasks();
config.close();
}
else if (args[0] == "-r")
{
removeTask(stoi(args[1]));
removeEmpty();
config.close();
}
else
{
std::cout << "\ninvalid command // use -help to see available commands\n\n";
config.close();
}
}
| 21.074534 | 87 | 0.465665 | kleidibujari |
de7915917f0b394091ebc1d1b367b5f036ee7b41 | 494 | cpp | C++ | uva/c/11032a.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/c/11032a.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/c/11032a.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | #include<cstdio>
int sum,max,s[100];
void go(int n,int w,int i)
{
if(w>sum-w)return;
if(!n)
{
max>?=w;
return;
}
for(;i>=0;i--)
go(n-1,w+s[i],i-1);
}
main()
{
int i,n,T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=sum=0;i<n;i++)
{
scanf("%d",&s[i]);
sum+=s[i];
}
max=0,go(n/2,0,n-1);
if(n%2)go(n/2+1,0,n-1);
printf("%d %d\n",max,sum-max);
}
}
| 15.935484 | 38 | 0.364372 | dk00 |
de79da105fbc7421b93e2eb6900e99ba44d5293d | 1,968 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_CBP_TARGET_TC_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_CBP_TARGET_TC_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_CBP_TARGET_TC_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_CBP_TARGET_TC_MIB_
#define _CISCO_CBP_TARGET_TC_MIB_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xe {
namespace CISCO_CBP_TARGET_TC_MIB {
class CcbptTargetDirection : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf undirected;
static const ydk::Enum::YLeaf input;
static const ydk::Enum::YLeaf output;
static const ydk::Enum::YLeaf inOut;
static int get_enum_value(const std::string & name) {
if (name == "undirected") return 1;
if (name == "input") return 2;
if (name == "output") return 3;
if (name == "inOut") return 4;
return -1;
}
};
class CcbptPolicySourceType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ciscoCbQos;
static const ydk::Enum::YLeaf ciscoCbpBase;
static int get_enum_value(const std::string & name) {
if (name == "ciscoCbQos") return 1;
if (name == "ciscoCbpBase") return 2;
return -1;
}
};
class CcbptTargetType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf genIf;
static const ydk::Enum::YLeaf atmPvc;
static const ydk::Enum::YLeaf frDlci;
static const ydk::Enum::YLeaf entity_;
static const ydk::Enum::YLeaf fwZone;
static const ydk::Enum::YLeaf fwZonePair;
static const ydk::Enum::YLeaf aaaSession;
static int get_enum_value(const std::string & name) {
if (name == "genIf") return 1;
if (name == "atmPvc") return 2;
if (name == "frDlci") return 3;
if (name == "entity") return 4;
if (name == "fwZone") return 5;
if (name == "fwZonePair") return 6;
if (name == "aaaSession") return 7;
return -1;
}
};
}
}
#endif /* _CISCO_CBP_TARGET_TC_MIB_ */
| 27.333333 | 61 | 0.587398 | CiscoDevNet |
de7b7bed00d7886066295bde50de83dd9e7a33cb | 2,815 | hpp | C++ | pulsar/datastore/GenericBase.hpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/datastore/GenericBase.hpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/datastore/GenericBase.hpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | /*! \file
*
* \brief Base class for holding generic data
*/
#pragma once
#include "pulsar/util/Serialization_fwd.hpp"
#include <bphash/Hash.hpp>
#include <memory>
namespace pulsar {
namespace detail {
/* Developer note
*
* Why not just have serialize functions and let cereal handle the
* polymorphic serialization?
*
* Answer: It would require registering every type of GenericHolder<T>,
* including any types held in the modules. That's a pain, so I work around
* it a bit by having the derived GenericHolder<T> handle the serialization
*/
/*! \brief An interface to a templated class that can hold anything
*
* This allows for storing any data types in containers.
*
* \threadunsafe
*/
class GenericBase
{
public:
GenericBase(void) noexcept = default;
virtual ~GenericBase() noexcept = default;
GenericBase & operator=(const GenericBase & rhs) = delete;
GenericBase & operator=(const GenericBase && rhs) = delete;
GenericBase(const GenericBase & rhs) = delete;
GenericBase(const GenericBase && rhs) = delete;
///////////////////////////////////
// Virtual functions
///////////////////////////////////
/*! \brief Returns a string representing the type
*
* \return A string representing the type (obtained via typeid().name())
*/
virtual const char * type(void) const noexcept = 0;
/*! \brief Returns a string representing the demangled type of the stored object
*
* For a C++ object, will return the demangled C++ type. For a python
* object, will return its class string.
*
* \return A string representing the type
*/
virtual std::string demangled_type(void) const = 0;
/*! \brief Check if the data stored in this object is serializable
*
* \return True if the stored type is serializable, false otherwise
*/
virtual bool is_serializable(void) const noexcept = 0;
/*! \brief Check if the data stored in this object is hashable
*
* \return True if the stored type is hashable, false otherwise
*/
virtual bool is_hashable(void) const noexcept = 0;
/*! \brief Serialize the data as a byte array
*
* \throw pulsar::PulsarException if the type is not
* serializable
*/
virtual ByteArray to_byte_array(void) const = 0;
/*! \brief Obtain the hash of the data
*
* \throw pulsar::PulsarException if the type is not
* hashable
*/
virtual bphash::HashValue my_hash(void) const = 0;
};
} //closing namespace datastore
} //closing namespace pulsar
| 26.809524 | 88 | 0.601066 | pulsar-chem |
de863c9bcce16e963f2d95a55060694a965760d8 | 730 | hh | C++ | Geant4/include/NDDRunAction.hh | leenderthayen/NDP | ffc16ccff47da53326e9a83f98b675d5db24bc59 | [
"MIT"
] | 1 | 2022-02-08T20:10:10.000Z | 2022-02-08T20:10:10.000Z | Geant4/include/NDDRunAction.hh | leenderthayen/NDP | ffc16ccff47da53326e9a83f98b675d5db24bc59 | [
"MIT"
] | null | null | null | Geant4/include/NDDRunAction.hh | leenderthayen/NDP | ffc16ccff47da53326e9a83f98b675d5db24bc59 | [
"MIT"
] | 2 | 2021-01-11T20:44:30.000Z | 2021-06-02T17:27:43.000Z | //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#ifndef NDDRunAction_h
#define NDDRunAction_h 1
#include "G4UserRunAction.hh"
#include "G4String.hh"
//class NDDRunMessenger;
class NDDAnalysisManager;
class G4Run;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
class NDDRunAction : public G4UserRunAction {
public:
NDDRunAction(NDDAnalysisManager*);
virtual ~NDDRunAction();
public:
virtual void BeginOfRunAction(const G4Run*);
virtual void EndOfRunAction(const G4Run*);
private:
//NDDRunMessenger* runMessenger;
NDDAnalysisManager* analysisManager;
};
#endif
| 23.548387 | 80 | 0.69863 | leenderthayen |
de869e63596bf166e298a1c6737f2c83eb299e06 | 2,747 | cpp | C++ | lib/flow/GrownGrid.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | null | null | null | lib/flow/GrownGrid.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | null | null | null | lib/flow/GrownGrid.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | 1 | 2021-12-04T15:35:46.000Z | 2021-12-04T15:35:46.000Z | #include "GrownGrid.h"
using VAPoR::GrownGrid;
// Constructor
GrownGrid::GrownGrid( const VAPoR::Grid* gp, VAPoR::DataMgr* mp, float z)
: _grid2d( gp ), _dataMgr( mp ), _defaultZ( z )
{}
// Destructor
GrownGrid::~GrownGrid()
{
if( _grid2d && _dataMgr )
{
_dataMgr->UnlockGrid( _grid2d );
delete _grid2d;
}
}
float GrownGrid::GetDefaultZ() const
{
return _defaultZ;
}
std::string GrownGrid::GetType() const
{
std::string type( "GrownGrid" );
return type;
}
float GrownGrid::GetMissingValue() const
{
return _grid2d->GetMissingValue();
}
void GrownGrid::GetUserExtentsHelper( VAPoR::DblArr3 &minu, VAPoR::DblArr3 &maxu) const
{
_grid2d->GetUserExtents( minu, maxu );
if (_grid2d->GetGeometryDim() < 3) {
minu[2] = _defaultZ;
maxu[2] = _defaultZ;
}
}
bool GrownGrid::InsideGrid(const VAPoR::DblArr3 &coords) const
{
// Note that we don't use defaultZ to decide if a position is inside of
// a grid or not.
return ( _grid2d->InsideGrid( coords ) );
}
float GrownGrid::GetValue(const VAPoR::DblArr3 &coords) const
{
return _grid2d->GetValue( coords );
}
float GrownGrid::GetValueNearestNeighbor(const VAPoR::DblArr3 &coords) const
{
return _grid2d->GetValue( coords );
}
float GrownGrid::GetValueLinear(const VAPoR::DblArr3 &coords) const
{
return _grid2d->GetValue( coords );
}
std::vector<size_t> GrownGrid::GetCoordDimensions(size_t) const
{
std::vector<size_t> tmp;
return tmp;
}
//
// Start meaningless functions!
//
size_t GrownGrid::GetGeometryDim() const
{
return 3;
}
const std::vector<size_t>& GrownGrid::GetNodeDimensions() const
{
return( GetDimensions() );
}
const std::vector<size_t>& GrownGrid::GetCellDimensions() const
{
return( GetDimensions() );
}
bool GrownGrid::GetIndicesCell(const VAPoR::DblArr3 &coords,
VAPoR::Size_tArr3 &indices
) const
{
return false;
}
bool GrownGrid::GetCellNodes(
const VAPoR::Size_tArr3 &cindices, std::vector <VAPoR::Size_tArr3> &nodes) const
{
return false;
}
bool GrownGrid::GetCellNeighbors(
const VAPoR::Size_tArr3 &cindices, std::vector <VAPoR::Size_tArr3> &nodes) const
{
return false;
}
bool GrownGrid::GetNodeCells(
const VAPoR::Size_tArr3 &cindices, std::vector <VAPoR::Size_tArr3> &nodes) const
{
return false;
}
size_t GrownGrid::GetMaxVertexPerFace() const
{
return 0;
}
size_t GrownGrid::GetMaxVertexPerCell() const
{
return 0;
}
VAPoR::Grid::ConstCoordItr GrownGrid::ConstCoordBegin() const
{
return VAPoR::Grid::ConstCoordItr();
}
VAPoR::Grid::ConstCoordItr GrownGrid::ConstCoordEnd() const
{
return VAPoR::Grid::ConstCoordItr();
}
| 19.621429 | 87 | 0.673098 | RemiLacroix-IDRIS |
de87008313d0f53b1e0ea3dabdd0a6baef8d04f2 | 12,977 | hpp | C++ | wax/hala_noengine_structs.hpp | LIBHALA/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 1 | 2021-02-25T16:21:42.000Z | 2021-02-25T16:21:42.000Z | wax/hala_noengine_structs.hpp | mkstoyanov/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 9 | 2020-09-03T23:31:22.000Z | 2020-10-21T23:40:11.000Z | wax/hala_noengine_structs.hpp | mkstoyanov/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 2 | 2020-03-03T17:39:37.000Z | 2020-11-05T16:01:28.000Z | #ifndef __HALA_NOENGINE_STRUCTS_HPP
#define __HALA_NOENGINE_STRUCTS_HPP
/*
* Code Author: Miroslav Stoyanov
*
* Copyright (C) 2018 Miroslav Stoyanov
*
* This file is part of
* Hardware Accelerated Linear Algebra (HALA)
*
*/
#include "hala_sparse_extensions.hpp"
namespace hala{
/*!
* \internal
* \file hala_noengine_structs.hpp
* \ingroup HALAWAXENGINED
* \brief Wrappers that use engined vectors and bypass carrying the engine to each call.
* \author Miroslav Stoyanov
* \copyright BSD-3-Clause
*
* \endinternal
*/
/*!
* \ingroup HALAWAXEXT
* \addtogroup HALAWAXENGINED Engined vectors
*
* Writing a generalized template while carrying the engine variable to each call
* can get repetitive and tedious. HALA offers an engined-vector overload that
* binds an engine and a vector using either owning or non-owning references so that the binded pair
* can be used in hala calls without the need to explicitly carry the engine object.
*/
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief If the class \b a is one of the engines, the struct defaults to std::true_type and std::false_type otherwise.
*
* \endinternal
*/
template<class a> struct is_engine{
//! \brief Set to true or false if the engine type is one of the compatible engine types.
#ifdef HALA_ENABLE_GPU
static const bool value = std::is_same<a, cpu_engine>::value || std::is_same<a, gpu_engine>::value || std::is_same<a, mixed_engine>::value;
#else
static const bool value = std::is_same<a, cpu_engine>::value;
#endif
};
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Defines the types of the vector and the internal variable of the hala::engined_vector.
*
* Allows for switching between owning and non-owning modes with specialization to this struct.
* The owning mode (when \b vec is not a reference) this will assume both the internal variable
* and the returned variables as the vector itself, i.e., this is an identity template.
* In non-owning mode (when \b vec is a reference) this will use a reference wrapper for
* the internal variable and will strip away the reference for the return types.
* \endinternal
*/
template<class vec, typename = void> struct engined_vector_binding{
//! \brief The type of the internal variable used in the engined_vector class.
using variable = vec;
//! \brief The type of the returned variable used in the engined_vector class.
using type = vec;
};
#ifndef __HALA_DOXYGEN_SKIP
template<class vec> struct engined_vector_binding<vec, std::enable_if_t<std::is_reference<vec>::value>>{
using variable = std::reference_wrapper<std::remove_reference_t<vec>>;
using type = std::remove_reference_t<vec>;
};
#endif
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Allows the distinction between a vector and reference-wrapper to a vector, either way returns a reference to the vector.
*
* \endinternal
*/
template<class vec> vec& get_vec(vec &x){ return x; }
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Allows the distinction between a vector and reference-wrapper to a vector, either way returns a reference to the vector.
*
* \endinternal
*/
template<class vec> vec& get_vec(std::reference_wrapper<vec> &x){ return x.get(); }
/*!
* \ingroup HALAWAXENGINED
* \brief A struct that binds an engine and a vector so both can be carried in one context.
*
* The purpose of the construct is to create a new entity that carries both a vector and
* an engine in one context. That way long algorithms do not have to constantly repeat
* the engine variable into each call to HALA. Instead the engine will be bounded to
* all input/output vectors and be carried out through the computations.
*
* Do not call the constructor directly, use the factory methods hala::bind_engine_vector
* and hala::new_vector.
*
* \internal
* The owning vs. non-owning mode is determined by the type \b vec, which must be either
* a vector like (owning) or reference to a vector-like (non-owning).
* The factory methods take care of the distinction depending whether calling
* hala::bind_engine_vector or hala::new_vector.
* \endinternal
*
* For example:
* \code
* template<class VectorLikeA, class VectorLikeB, , class VectorLikeX>
* void advanced_solver(VectorLikeA const &A, VectorLikeB const &b, VectorLikeX &x){
* auto t = hala::new_vector(x);
* hala::vcopy(x, t);
* hala::axpy(-1.0, b, x);
* // ...
* // imagine many more HALA calls used to solve Ax = b
* // ...
* }
* \endcode
* The advanced solver works by default on the CPU, but what if we want to perform the solve
* on the GPU. If we use the engine mechanics, we would have to add another variable to
* the template indicating the engine type and then pass the variable to every HALA call:
* \code
* ...
* auto t = hala::new_vector(engine, x);
* hala::vcopy(engine, x, t);
* ...
* \endcode
* If the advanced solver has many lines of code, the above will change a lot of code
* and can easily lead to an error if one of the calls misses the engine.
* In contrast, the hala::engined_vector allows to instantiate the solver with the GPU backend
* and without making any changes to the solver code:
* \code
* template<class cengine, class VectorLikeA, class VectorLikeB, , class VectorLikeX>
* void advanced_solver(cengine const&engine, VectorLikeA const &A, VectorLikeB const &b, VectorLikeX &x){
* auto bindA = hala::bind_engine_vector(engine, A);
* auto bindb = hala::bind_engine_vector(engine, b);
* auto bindx = hala::bind_engine_vector(engine, x);
* advanced_solver(bindA, bindb, bindx);
* }
* \endcode
* The above small piece of code will overload the advanced solver and allow for calls with any engine type
* while making no changes to the solver itself.
*/
template<class cengine, class vec>
struct engined_vector{
//! \brief The type of the vector used in the binding, removes any reference qualifies but leaves const.
using vtype = typename engined_vector_binding<vec>::type;
//! \brief Defines the scalar type of the underlying vector, mostly used for the precision of the stopping criteria.
using value_type = get_standard_type<vtype>;
//! \brief Reference to the engine, it is recommended to use the engine() method in place of direct access.
std::reference_wrapper<cengine const> e;
//! \brief Either owning a vector variable or non-owning reference to a vector variable.
typename engined_vector_binding<vec>::variable v;
//! \brief Initialize the engined_vector with non-owning references to the engine and \b x.
engined_vector(cengine const &engine, vtype &x) : e(engine), v(x){
static_assert(is_engine<cpu_engine>::value, "engined_vector constructed with cengine that is not an engine");
static_assert(std::is_reference<vec>::value, "engined_vector cannot take a reference in non-referenced mode, instantiate with vec& instead");
}
//! \brief Initialize the engined_vector with ownership to an internal vector.
engined_vector(cengine const &engine) : e(engine), v(new_vector(engine, v)){
static_assert(is_engine<cpu_engine>::value, "engined_vector constructed with cengine that is not an engine");
static_assert(!std::is_reference<vec>::value, "engined_vector in non-owning mode must be initialized with the vector (use the other constructor)");
}
/*!
* \brief Returns \b true if the other engined_vector has a compatible engine.
*
* Engines are compatible if
* -# they have the same type, e.g., both cpu_engine
* -# if using hala::gpu_engine or hala::mixed_engine, then the device ids of the engines should also match.
*
* Overloads are provided to handle all possible pairs of engine types.
*/
template<class oengine, class vec2>
bool engine_match(engined_vector<oengine, vec2> const &) const{ return false; }
#ifndef __HALA_DOXYGEN_SKIP
template<class vec2, class ce = cengine>
std::enable_if_t<std::is_same<ce, cpu_engine>::value, bool>
engine_match(engined_vector<cengine, vec2> const &) const{
return true;
}
#ifdef HALA_ENABLE_GPU
template<class vec2, class ce = cengine>
std::enable_if_t<std::is_same<ce, gpu_engine>::value, bool>
engine_match(engined_vector<cengine, vec2> const &other) const{
return (engine().device() == other.engine().device());
}
template<class vec2, class ce = cengine>
std::enable_if_t<std::is_same<ce, mixed_engine>::value, bool>
engine_match(engined_vector<cengine, vec2> const &other) const{
return (engine().gpu().device() == other.engine().gpu().device());
}
#endif
#endif
//! \brief Return a reference to the engine.
cengine const& engine() const{ return e.get(); }
//! \brief Return a const reference to the vector.
vtype const& vector() const{ return get_vec(v); }
//! \brief Return a reference to the vector.
vtype& vector(){ return get_vec(v); }
//! \brief Returns the size of the vector.
size_t size() const{ return get_size(vector()); }
//! \brief Resizes the vector.
void resize(size_t new_size){ set_size(new_size, vector()); }
};
/*!
* \internal
* \ingroup HALAWAXENGINED
* \brief Runs a sanity check whether the classes have the same engine.
*
* Checks the engine type and the GPU device id.
* There is a variadric overload to check multiple vectors.
* \endinternal
*/
template<class ev1, class ev2>
bool check_engines(ev1 const &x, ev2 const &y){ return x.engine_match(y); }
#ifndef __HALA_DOXYGEN_SKIP
template<class ev1, class ev2, class ev3, class... evs>
bool check_engines(ev1 const &x, ev2 const &y, ev3 const &z, evs const&... more){
if (!check_engines(x, y)) return false;
return check_engines(y, z, more...);
}
#endif
/*!
* \ingroup HALAWAXENGINED
* \brief Creates a bind between the engine and the vector.
*
* Factory method to construct a bind between the vector and the engine.
*
* Overloads:
* \code
* auto x1 = bind_engine_vector(engine, x);
* auto y1 = bind_engine_vector(engined_vector, y);
* auto z1 = bind_engine_vector(vector, z);
* \endcode
* Overloads are provided for all engine types (case x1), the engine reference can be taken from an existing
* hala::engined_vector, or the call can be made with a generic vector-like class in which case
* z1 will be just a reference to z for calls that do not use binded engines.
*/
template<class cengine, class vec>
std::enable_if_t<is_engine<cengine>::value, engined_vector<cengine, vec&>> bind_engine_vector(cengine const &e, vec &x){
return engined_vector<cengine, vec&>(e, x);
}
/*!
* \ingroup HALAWAXENGINED
* \brief Returns the engine associated with the vector.
*
* The method is an easy way to obtain the engine from the engined vector,
* and the method is overloaded for general vector-like classes to return an instance of the cpu_engine.
*
* \b Note: do not use this to differentiate between GPU and CPU vectors,
* i.e., this will return hala::cpu_engine even if \b vec is hala::cuda_vector.
* The intended use is within the no-engine context where
* an engined_vector and a CPU vectors are the only acceptable inputs.
*/
template<class cengine, class vec>
auto get_engine(engined_vector<cengine, vec> const &x){ return x.engine(); }
#ifndef __HALA_DOXYGEN_SKIP // tell Doxygen to skip this section (overloads are documented with the main methods)
template<class vec>
auto get_engine(vec const &){ return cpu_engine(); }
template<class cengine, class vec>
auto new_vector(engined_vector<cengine, vec> const &x){
return engined_vector<cengine, get_vdefault<cengine, typename engined_vector<cengine, vec>::vtype>>(x.engine());
}
template<class cengine, class vec>
void set_zero(size_t num_entries, engined_vector<cengine, vec> &x){
set_zero(x.engine(), num_entries, x.vector());
}
template<class cengine, class vec>
void set_size(size_t num_entries, engined_vector<cengine, vec> &x){
set_size(num_entries, x.vector());
}
template<class vec>
auto new_vector(vec const &x){
return new_vector(cpu_engine(), x);
}
template<class cengine, class vec>
std::enable_if_t<is_engine<cengine>::value, engined_vector<cengine, vec const&>> bind_engine_vector(cengine const &e, vec const &x){
return engined_vector<cengine, vec const&>(e, x);
}
template<class cvec, class vec> std::enable_if_t<!is_engine<cvec>::value, vec&> bind_engine_vector(cvec const &, vec &x){ return x; }
template<class cvec, class vec> std::enable_if_t<!is_engine<cvec>::value, vec const&> bind_engine_vector(cvec const &, vec const &x){ return x; }
template<class cengine, class cvec, class vec>
auto bind_engine_vector(engined_vector<cengine, cvec> const &s, vec &x){ return bind_engine_vector(s.engine(), x); }
#endif
}
#include "hala_noengine_overloads.hpp"
#undef __HALA_NOENGINE_OVERLOADS_HPP
#include "hala_noengine_overloads.hpp"
#endif
| 40.301242 | 155 | 0.720968 | LIBHALA |
de87394e6105d98162a80b0871c3279630f002c7 | 1,907 | cpp | C++ | StringToInt.cpp | vibiu/SwordOfOffer | 6daa7d108a4f043353d372e835a1f8923c933dcc | [
"BSD-3-Clause"
] | 1 | 2020-05-14T13:59:11.000Z | 2020-05-14T13:59:11.000Z | StringToInt.cpp | vibiu/SwordOfOffer | 6daa7d108a4f043353d372e835a1f8923c933dcc | [
"BSD-3-Clause"
] | null | null | null | StringToInt.cpp | vibiu/SwordOfOffer | 6daa7d108a4f043353d372e835a1f8923c933dcc | [
"BSD-3-Clause"
] | null | null | null | #include "StringToInt.h"
#include <cstdio>
int g_nStatus = kValid;
long long StrToIntCore(const char *digit, bool minus)
{
long long num = 0;
while (*digit != '\0')
{
if (*digit >= '0' && *digit <= '9')
{
int flag = minus ? -1 : 1;
num = num * 10 + flag * (*digit - '0');
if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000))
{
num = 0;
break;
}
digit++;
}
else
{
num = 0;
break;
}
}
if (*digit == '\0')
g_nStatus = kValid;
return num;
}
int StrToInt(const char *str)
{
g_nStatus = kInvalid;
long long num = 0;
if (str != nullptr && *str != '\0')
{
bool minus = false;
if (*str == '+')
str++;
else if (*str == '-')
{
str++;
minus = true;
}
if (*str != '\0')
num = StrToIntCore(str, minus);
}
return (int)num;
}
void StringToIntTest(const char *string)
{
int result = StrToInt(string);
if (result == 0 && g_nStatus == kInvalid)
printf("the input %s is invalid.\n", string);
else
printf("number for %s is: %d.\n", string, result);
}
void StringToIntTest1()
{
StringToIntTest(nullptr);
StringToIntTest("");
StringToIntTest("123");
StringToIntTest("+123");
StringToIntTest("-123");
StringToIntTest("1a33");
StringToIntTest("+0");
StringToIntTest("-0");
//有效的最大正整数, 0x7FFFFFFF
StringToIntTest("+2147483647");
StringToIntTest("-2147483647");
StringToIntTest("+2147483648");
//有效的最小负整数, 0x80000000
StringToIntTest("-2147483648");
StringToIntTest("+2147483649");
StringToIntTest("-2147483649");
StringToIntTest("+");
StringToIntTest("-");
}
| 18.881188 | 88 | 0.497116 | vibiu |
de89cab261393b40c494907099628b1cfd1e4f51 | 7,456 | cpp | C++ | testapp/scenes/physics/shakescene.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | 6 | 2015-12-08T05:38:03.000Z | 2021-04-09T13:45:59.000Z | testapp/scenes/physics/shakescene.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | testapp/scenes/physics/shakescene.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (C) 2007 by the members of PG 510, University of Dortmund: *
* d-collide-devel@lists.sourceforge.net *
*
* Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, *
* Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, *
* Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met:*
* - Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* - Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* - Neither the name of the PG510 nor the names of its contributors may be *
* used to endorse or promote products derived from this software without *
* specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE *
*******************************************************************************/
#include "shakescene.h"
#include "dcollide-config_testapp.h"
#include "myobjectnode.h"
#include "debug.h"
#include "Ogre.h"
#include <world.h>
#include <shapes/shapes.h>
#include <worldcollisions.h>
#include <collisioninfo.h>
#include <proxyfactory.h>
#include <algorithm>
/*!
* Construct a new d-collide based scene object.
*
* The scene itself is not yet created, only the necessary data
* structures. Call \ref initializeScene to actually create a scene.
*
* \param root A pointer to the ogre root object. Ownership is NOT
* taken, the pointer will not be deleted by this class.
*/
ShakeScene::ShakeScene(Ogre::Root* root) : PhysicsSceneBase(root) {
mPhysicsSimStepsize = 0.03;
mLinearDampingFactor = 0.005;
mAngularDampingFactor = 0.005;
}
ShakeScene::~ShakeScene() {
}
dcollide::Vector3 ShakeScene::initialWorldDimension() const {
return dcollide::Vector3(2048.0, 2048.0, 2048.0);
}
/*!
* Setup the actual scene, i.e. add objects to the \ref dcollide::World
* object.
*
* \return TRUE on success, otherwise FALSE.
*/
bool ShakeScene::initializeScene() {
dWorldSetGravity(mOdeWorld, 0,0,-10);
MyObjectNode* baseplate = new MyObjectNode( getCollisionWorld(),
new dcollide::Box(500,500, 20),
dcollide::PROXYTYPE_FIXED);
baseplate->translate(dcollide::Vector3(-250, -250, -20));
addTopLevelObject(baseplate);
/* z
* ^ -10 10 y
* 40 | +-----+ /
* | | |/
* | | |
* 20 | +-----+
* 20 | +---+ +---+
* | | | | |
* 0 | +---+ +---+
* +-----------------> x
* -21 -1,0,1 21
*/
MyObjectNode* underBox1 = new MyObjectNode(
getCollisionWorld(),new dcollide::Box(20,20,20), dcollide::PROXYTYPE_RIGID, true, false);
underBox1->setPosition(-29,0,0);
underBox1->createPhysicsBody(mOdeWorld,4);
addTopLevelObject(underBox1);
MyObjectNode* underBox2 = new MyObjectNode(
getCollisionWorld(),new dcollide::Box(20,20,20), dcollide::PROXYTYPE_RIGID, true, false);
underBox2->setPosition(9,0,0);
underBox2->createPhysicsBody(mOdeWorld,4);
addTopLevelObject(underBox2);
MyObjectNode* TopBox = new MyObjectNode(
getCollisionWorld(),new dcollide::Box(20,20,20), dcollide::PROXYTYPE_RIGID, true, false);
TopBox->setPosition(-10,0,20);
TopBox->createPhysicsBody(mOdeWorld,50);
addTopLevelObject(TopBox);
// create my own wall
/* z
* ^ +---+
* | | |
* | +---+
* | +---+ +---+
* | | | | |
* | +---+ +---+
* | +---+ +---+ +---+
* | | | | | | |
* | +---+ +---+ +---+
+ | +---+ +---+ +---+ +---+
* | | | | | | | | |
* | +---+ +---+ +---+ +---+
* | +---+ +---+ +---+ +---+ +---+
* | | | | | | | | | | |
* | +---+ +---+ +---+ +---+ +---+
* | +---+ +---+ +---+ +---+ +---+ +---+
* | | | | | | | | | | | | |
* | +---+ +---+ +---+ +---+ +---+ +---+
* +---------------------------------------> x
* -63,-43,-42,-22,-21,-1,0,1 21,22 42,43 63
* 2nd level: -31,-11,-10,10,11,31,32,52
*/
int baseBoxes = 10;
int boxWidth = 20;
int boxDistance = 15;
for (int row = 0; row<baseBoxes;row++){
for (int i=0; i<baseBoxes-row; i++){
MyObjectNode* box = new MyObjectNode( getCollisionWorld(),
new dcollide::Box(boxWidth,boxWidth,boxWidth),dcollide::PROXYTYPE_RIGID, true, false);
float nr = (baseBoxes-row)/2.0;
box->setPosition(-(nr*boxWidth+(nr-0.5)*boxDistance) + i*boxWidth+i*boxDistance, 100 , row*boxWidth );
box->createPhysicsBody(mOdeWorld, 2);
addTopLevelObject(box);
}
}
// Gregors Wall
dcollide::real wallDistance = -100;
int baseboxes = 8;
for (int row = 0; row<baseboxes;row++){
for (int i=0; i<baseboxes-row; i++){
MyObjectNode* box = new MyObjectNode( getCollisionWorld(),
new dcollide::Box(10,10, 10),
dcollide::PROXYTYPE_RIGID, true, false);
box->setPosition(-50 + (row * 15)/2 + i * 13, wallDistance , row*10);
box->createPhysicsBody(mOdeWorld, 4);
addTopLevelObject(box);
}
}
return true;
}
void ShakeScene::startNextSceneFrame() {
}
std::string ShakeScene::getSceneDescription() const {
return "One physikbody on top of two other. Why is it shaking?";
}
/*
* vim: et sw=4 ts=4
*/
| 39.659574 | 114 | 0.51301 | ColinGilbert |
de90eead59c3ab1260386bb28a3889c8ea14ee16 | 7,361 | hpp | C++ | include/System/Xml/Schema/AttributeMatchState.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/Schema/AttributeMatchState.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/Schema/AttributeMatchState.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // 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: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Forward declaring type: AttributeMatchState
struct AttributeMatchState;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::AttributeMatchState, "System.Xml.Schema", "AttributeMatchState");
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: System.Xml.Schema.AttributeMatchState
// [TokenAttribute] Offset: FFFFFFFF
struct AttributeMatchState/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: AttributeMatchState
constexpr AttributeMatchState(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public System.Xml.Schema.AttributeMatchState AttributeFound
static constexpr const int AttributeFound = 0;
// Get static field: static public System.Xml.Schema.AttributeMatchState AttributeFound
static ::System::Xml::Schema::AttributeMatchState _get_AttributeFound();
// Set static field: static public System.Xml.Schema.AttributeMatchState AttributeFound
static void _set_AttributeFound(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AnyIdAttributeFound
static constexpr const int AnyIdAttributeFound = 1;
// Get static field: static public System.Xml.Schema.AttributeMatchState AnyIdAttributeFound
static ::System::Xml::Schema::AttributeMatchState _get_AnyIdAttributeFound();
// Set static field: static public System.Xml.Schema.AttributeMatchState AnyIdAttributeFound
static void _set_AnyIdAttributeFound(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState UndeclaredElementAndAttribute
static constexpr const int UndeclaredElementAndAttribute = 2;
// Get static field: static public System.Xml.Schema.AttributeMatchState UndeclaredElementAndAttribute
static ::System::Xml::Schema::AttributeMatchState _get_UndeclaredElementAndAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState UndeclaredElementAndAttribute
static void _set_UndeclaredElementAndAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState UndeclaredAttribute
static constexpr const int UndeclaredAttribute = 3;
// Get static field: static public System.Xml.Schema.AttributeMatchState UndeclaredAttribute
static ::System::Xml::Schema::AttributeMatchState _get_UndeclaredAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState UndeclaredAttribute
static void _set_UndeclaredAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AnyAttributeLax
static constexpr const int AnyAttributeLax = 4;
// Get static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeLax
static ::System::Xml::Schema::AttributeMatchState _get_AnyAttributeLax();
// Set static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeLax
static void _set_AnyAttributeLax(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AnyAttributeSkip
static constexpr const int AnyAttributeSkip = 5;
// Get static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeSkip
static ::System::Xml::Schema::AttributeMatchState _get_AnyAttributeSkip();
// Set static field: static public System.Xml.Schema.AttributeMatchState AnyAttributeSkip
static void _set_AnyAttributeSkip(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState ProhibitedAnyAttribute
static constexpr const int ProhibitedAnyAttribute = 6;
// Get static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAnyAttribute
static ::System::Xml::Schema::AttributeMatchState _get_ProhibitedAnyAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAnyAttribute
static void _set_ProhibitedAnyAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState ProhibitedAttribute
static constexpr const int ProhibitedAttribute = 7;
// Get static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAttribute
static ::System::Xml::Schema::AttributeMatchState _get_ProhibitedAttribute();
// Set static field: static public System.Xml.Schema.AttributeMatchState ProhibitedAttribute
static void _set_ProhibitedAttribute(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState AttributeNameMismatch
static constexpr const int AttributeNameMismatch = 8;
// Get static field: static public System.Xml.Schema.AttributeMatchState AttributeNameMismatch
static ::System::Xml::Schema::AttributeMatchState _get_AttributeNameMismatch();
// Set static field: static public System.Xml.Schema.AttributeMatchState AttributeNameMismatch
static void _set_AttributeNameMismatch(::System::Xml::Schema::AttributeMatchState value);
// static field const value: static public System.Xml.Schema.AttributeMatchState ValidateAttributeInvalidCall
static constexpr const int ValidateAttributeInvalidCall = 9;
// Get static field: static public System.Xml.Schema.AttributeMatchState ValidateAttributeInvalidCall
static ::System::Xml::Schema::AttributeMatchState _get_ValidateAttributeInvalidCall();
// Set static field: static public System.Xml.Schema.AttributeMatchState ValidateAttributeInvalidCall
static void _set_ValidateAttributeInvalidCall(::System::Xml::Schema::AttributeMatchState value);
// Get instance field reference: public System.Int32 value__
[[deprecated("Use field access instead!")]] int& dyn_value__();
}; // System.Xml.Schema.AttributeMatchState
#pragma pack(pop)
static check_size<sizeof(AttributeMatchState), 0 + sizeof(int)> __System_Xml_Schema_AttributeMatchStateSizeCheck;
static_assert(sizeof(AttributeMatchState) == 0x4);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 65.723214 | 115 | 0.776253 | v0idp |
de944d3eea1531b4035a9ddc0c78c0761e00f7bd | 8,890 | cpp | C++ | QuadGeom.cpp | cleak/VoxelPerf | 02dad67747b113a3cd38cae6a2c307f877cab068 | [
"MIT"
] | 42 | 2017-07-30T17:50:16.000Z | 2022-03-27T09:27:04.000Z | QuadGeom.cpp | cleak/VoxelPerf | 02dad67747b113a3cd38cae6a2c307f877cab068 | [
"MIT"
] | 1 | 2019-03-13T07:09:44.000Z | 2019-03-15T07:02:23.000Z | QuadGeom.cpp | cleak/VoxelPerf | 02dad67747b113a3cd38cae6a2c307f877cab068 | [
"MIT"
] | 3 | 2018-05-10T20:38:29.000Z | 2020-06-21T21:12:39.000Z | #include "QuadGeom.h"
#include <iostream>
#include <cstddef>
#include <vector>
using namespace glm;
using namespace std;
#pragma pack(push, 1)
struct PointQuad {
//vec3 position;
uint8_t x;
uint8_t y;
uint8_t z;
//uint8_t pad0;
//PackedColor color;
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t faceIdx;
};
#pragma pack(pop)
// Stores information about the location and size of each set of layers of a voxel object
struct LayersInfo {
uint16_t layerStartIdx[6];
uint16_t layerSize[6];
};
struct LayeredVertexBuffer {
int nextLayerIdx[6] = {};
vector<PointQuad> layer[6] = {};
};
int FloatToPackedInt(float f) {
if (f == 1.0f) {
return 511;
}
if (f == -1.0f) {
return -512;
}
return 0;
}
PackedVec PackVec(vec3 v) {
PackedVec p;
p.w = 0;
p.x = FloatToPackedInt(v.x);
p.y = FloatToPackedInt(v.y);
p.z = FloatToPackedInt(v.z);
return p;
}
uint8_t RoundColor(float c) {
return (uint8_t)round(c * 0xff);
}
void BufferPointQuadFace(ivec3 voxIdx, ivec3 normal, vec3 color, vector<PointQuad>& vertices, int& nextIdx,
uint8_t faceIdx) {
if (normal.x > 0 || normal.y > 0 || normal.z > 0) {
voxIdx += normal;
}
PointQuad p;
p.r = RoundColor(color.r);
p.g = RoundColor(color.g);
p.b = RoundColor(color.b);
p.x = voxIdx.x;
p.y = voxIdx.y;
p.z = voxIdx.z;
p.faceIdx = faceIdx;
if (nextIdx >= vertices.size()) {
vertices.push_back(p);
} else {
vertices[nextIdx] = p;
}
nextIdx++;
}
// Buffers all faces of a voxel in the given vector
void BufferPointQuadVoxel(VoxelSet& voxels, vec3 offset, ivec3 idx, LayeredVertexBuffer& vertexBuffers) {
if (!voxels.IsSolid(idx)) {
return;
}
vec3 color = voxels.At(idx);
vector<ivec3> normals = {
{ 1, 0, 0 },
{-1, 0, 0 },
{ 0, 1, 0 },
{ 0,-1, 0 },
{ 0, 0, 1 },
{ 0, 0,-1 },
};
PointQuad p;
int enabledFaces = 0;
for (int i = 0; i < normals.size(); ++i) {
if (voxels.IsSolid(idx + normals[i])) {
continue;
}
BufferPointQuadFace(idx, normals[i], color, vertexBuffers.layer[i], vertexBuffers.nextLayerIdx[i], (uint8_t)i);
}
}
// Buffers an entire voxel model in the given vector
void BufferVoxelSetPointQuads(VoxelSet& voxels, vec3 offset, LayeredVertexBuffer& vertexBuffers) {
for (int i = 0; i < 6; ++i) {
vertexBuffers.nextLayerIdx[i] = 0;
}
for (int z = 0; z < voxels.size.z; ++z) {
for (int y = 0; y < voxels.size.y; ++y) {
for (int x = 0; x < voxels.size.x; ++x) {
BufferPointQuadVoxel(voxels, offset, ivec3(x, y, z), vertexBuffers);
}
}
}
}
void MakeGridPointQuads(VoxelSet& model, ivec3 dimensions, vec3 spacing, std::vector<GLuint>& vaos,
std::vector<GLuint>& vbos, std::vector<LayersInfo>& layersInfo, GLuint program) {
size_t modelCount = dimensions.x * dimensions.y * dimensions.z;
vbos.resize(modelCount);
vaos.resize(modelCount);
layersInfo.resize(modelCount);
glGenBuffers(vbos.size(), &vbos[0]);
CheckGLErrors();
glGenVertexArrays(vaos.size(), &vaos[0]);
CheckGLErrors();
int nextVbo = 0;
LayeredVertexBuffer vertexBuffers;
for (int z = 0; z < dimensions.z; ++z) {
for (int y = 0; y < dimensions.y; ++y) {
for (int x = 0; x < dimensions.x; ++x) {
ivec3 idx(x, y, z);
vec3 offset = vec3(idx) * spacing;
offset -= vec3(0, dimensions.y, 0) * spacing / 2.0f;
BufferVoxelSetPointQuads(model, offset, vertexBuffers);
glBindVertexArray(vaos[nextVbo]);
glBindBuffer(GL_ARRAY_BUFFER, vbos[nextVbo]);
int totalQuads = 0;
for (int i = 0; i < 6; ++i) {
totalQuads += vertexBuffers.layer[i].size();
}
glBufferData(GL_ARRAY_BUFFER, sizeof(PointQuad) * totalQuads, nullptr, GL_STATIC_DRAW);
layersInfo[nextVbo].layerStartIdx[0] = 0;
for (int i = 0; i < 6; ++i) {
layersInfo[nextVbo].layerSize[i] = vertexBuffers.layer[i].size();
if (i > 0) {
layersInfo[nextVbo].layerStartIdx[i] = layersInfo[nextVbo].layerStartIdx[i - 1] + layersInfo[nextVbo].layerSize[i];
}
glBufferSubData(GL_ARRAY_BUFFER, layersInfo[nextVbo].layerStartIdx[i] * sizeof(PointQuad),
layersInfo[nextVbo].layerSize[i] * sizeof(PointQuad), &vertexBuffers.layer[i][0]);
}
GLint vPosLoc = glGetAttribLocation(program, "vPos");
glEnableVertexAttribArray(vPosLoc);
glVertexAttribPointer(vPosLoc, 3, GL_BYTE, GL_FALSE,
sizeof(PointQuad),
(void*)offsetof(PointQuad, x));
CheckGLErrors();
GLint vColorPos = glGetAttribLocation(program, "vColor");
glEnableVertexAttribArray(vColorPos);
glVertexAttribPointer(vColorPos, 3, GL_UNSIGNED_BYTE, GL_TRUE,
sizeof(PointQuad),
(void*)offsetof(PointQuad, r));
CheckGLErrors();
GLint vExtent1 = glGetAttribLocation(program, "vFaceIdx");
glEnableVertexAttribArray(vExtent1);
glVertexAttribIPointer(vExtent1, 1, GL_BYTE,
sizeof(PointQuad),
(void*)offsetof(PointQuad, faceIdx));
CheckGLErrors();
nextVbo++;
}
}
}
}
PerfRecord RunQuadGeometryShaderTest(VoxelSet & model, glm::ivec3 gridSize, glm::vec3 voxelSpacing) {
GLuint program;
GLint mvpLoc;
GLint offsetLoc;
vector<GLuint> vaos;
vector<GLuint> vbos;
vector<vec3> offsets;
std::vector<LayersInfo> layersInfo;
vector<ivec3> normals = {
{ 1, 0, 0 },
{ -1, 0, 0 },
{ 0, 1, 0 },
{ 0,-1, 0 },
{ 0, 0, 1 },
{ 0, 0,-1 },
};
PerfRecord record = RunPerf(
[&]() {
// Setup
program = MakeShaderProgram({
{ "Shaders/point_quads.vert", GL_VERTEX_SHADER },
{ "Shaders/point_voxels.frag", GL_FRAGMENT_SHADER },
{ "Shaders/point_quads.geom", GL_GEOMETRY_SHADER },
});
mvpLoc = glGetUniformLocation(program, "mvp");
offsetLoc = glGetUniformLocation(program, "vOffset");
MakeGridPointQuads(model, gridSize, voxelSpacing, vaos, vbos, layersInfo, program);
offsets.resize(vaos.size());
int nextOffsetIdx = 0;
for (int z = 0; z < gridSize.z; ++z) {
for (int y = 0; y < gridSize.y; ++y) {
for (int x = 0; x < gridSize.x; ++x) {
ivec3 idx(x, y, z);
vec3 offset = vec3(idx) * voxelSpacing;
offset -= vec3(0, gridSize.y, 0) * voxelSpacing / 2.0f;
offsets[nextOffsetIdx] = offset;
nextOffsetIdx++;
}
}
}
},
[&]() {
// Draw
mat4 mvp = MakeMvp();
//PrintMatrix(mvp);
glUseProgram(program);
glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, (const GLfloat*)&mvp);
for (int i = 0; i < vaos.size(); ++i) {
vec3 offset = offsets[i];
glUniform3fv(offsetLoc, 1, (const GLfloat*)&offset);
glBindVertexArray(vaos[i]);
for (int j = 0; j < 6; ++j) {
// Kludge to iterate over x twice, y twice, and z twice
int compareIdx = j / 2;
// Visibility threshold along a particular axis
float thresh = offset[compareIdx] + voxelSpacing[compareIdx] / 2.0f;
// Direction of normal (used for deciding how to compare)
float normalDir = normals[j][compareIdx];
thresh += normalDir * voxelSpacing[compareIdx] / 2.0f;
// Cull layers that are entirely backfacing
if (normalDir * thresh > normalDir * CameraPosition()[compareIdx]) {
continue;
}
glDrawArrays(GL_POINTS, layersInfo[i].layerStartIdx[j], layersInfo[i].layerSize[j]);
}
}
},
[&]() {
// Teardown
glDeleteBuffers(vbos.size(), &vbos[0]);
CheckGLErrors();
glDeleteVertexArrays(vaos.size(), &vaos[0]);
CheckGLErrors();
glDeleteProgram(program);
CheckGLErrors();
});
return record;
}
| 28.49359 | 139 | 0.534196 | cleak |
de95e3bdaf5dec6a0c3ab2e703b95a35ed6c046e | 9,055 | hpp | C++ | include/lug/Math/Matrix.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 275 | 2016-10-08T15:33:17.000Z | 2022-03-30T06:11:56.000Z | include/lug/Math/Matrix.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 24 | 2016-09-29T20:51:20.000Z | 2018-05-09T21:41:36.000Z | include/lug/Math/Matrix.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 37 | 2017-02-25T05:03:48.000Z | 2021-05-10T19:06:29.000Z | #pragma once
#include <cstdint>
#include <valarray>
#include <lug/Math/Export.hpp>
#include <lug/Math/ValArray.hpp>
#include <lug/System/Debug.hpp>
namespace lug {
namespace Math {
template <uint8_t Rows, uint8_t Columns, typename T = float>
class Matrix {
public:
// TODO: Use custom valarray with compile time size
using Values = ValArray<Rows * Columns, T>;
public:
constexpr Matrix() = default;
explicit Matrix(T value);
Matrix(const Values& values);
Matrix(std::initializer_list<T> list);
Matrix(const Matrix<Rows, Columns, T>& matrix) = default;
Matrix(Matrix<Rows, Columns, T>&& matrix) = default;
Matrix<Rows, Columns, T>& operator=(const Matrix<Rows, Columns, T>& rhs) = default;
Matrix<Rows, Columns, T>& operator=(Matrix<Rows, Columns, T>&& rhs) = default;
~Matrix() = default;
constexpr uint8_t getRows() const;
constexpr uint8_t getColumns() const;
Values& getValues();
constexpr const Values& getValues() const;
T& operator()(uint8_t row, uint8_t col = 0);
constexpr const T& operator()(uint8_t row, uint8_t col = 0) const;
// Matrix/Scalar operations
Matrix<Rows, Columns, T>& operator+=(T rhs);
Matrix<Rows, Columns, T>& operator-=(T rhs);
Matrix<Rows, Columns, T>& operator*=(T rhs);
Matrix<Rows, Columns, T>& operator/=(T rhs);
// Matrix/Matrix operations
Matrix<Rows, Columns, T>& operator+=(const Matrix<Rows, Columns, T>& rhs);
Matrix<Rows, Columns, T>& operator-=(const Matrix<Rows, Columns, T>& rhs);
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == Columns)>::type>
Matrix<Rows, Columns, T>& operator*=(const Matrix<Rows, Columns, T>& rhs);
template <typename = typename std::enable_if<(Rows == Columns)>::type>
Matrix<Rows, Columns, T>& operator/=(const Matrix<Rows, Columns, T>& rhs);
#else
template <bool EnableBool = true>
typename std::enable_if<(Rows == Columns) && EnableBool, Matrix<Rows, Columns, T>>::type& operator*=(const Matrix<Rows, Columns, T>& rhs);
template <bool EnableBool = true>
typename std::enable_if<(Rows == Columns) && EnableBool, Matrix<Rows, Columns, T>>::type& operator/=(const Matrix<Rows, Columns, T>& rhs);
#endif
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == 1)>::type>
Matrix<Rows, Columns, T> inverse() const;
template <typename = typename std::enable_if<(Rows == 2)>::type, typename = void>
Matrix<Rows, Columns, T> inverse() const;
template <typename = typename std::enable_if<(Rows == 3)>::type, typename = void, typename = void>
Matrix<Rows, Columns, T> inverse() const;
template <typename = typename std::enable_if<(Rows == 4)>::type, typename = void, typename = void, typename = void>
Matrix<Rows, Columns, T> inverse() const;
#else
template <bool EnableBool = true>
typename std::enable_if<(Rows == 1) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 2) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 3) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 4) && EnableBool, Matrix<Rows, Columns, T>>::type inverse() const;
#endif
Matrix<Columns, Rows, T> transpose() const;
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == 1)>::type>
T det() const;
template <typename = typename std::enable_if<(Rows == 2)>::type, typename = void>
T det() const;
template <typename = typename std::enable_if<(Rows == 3)>::type, typename = void, typename = void>
T det() const;
template <typename = typename std::enable_if<(Rows == 4)>::type, typename = void, typename = void, typename = void>
T det() const;
template <typename = typename std::enable_if<(Rows > 4)>::type, typename = void, typename = void, typename = void, typename = void>
T det() const;
#else
template <bool EnableBool = true>
typename std::enable_if<(Rows == 1) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 2) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 3) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows == 4) && EnableBool, T>::type det() const;
template <bool EnableBool = true>
typename std::enable_if<(Rows > 4) && EnableBool, T>::type det() const;
#endif
#if defined(LUG_COMPILER_MSVC)
template <typename = typename std::enable_if<(Rows == Columns)>::type>
static Matrix<Rows, Columns, T> identity();
#else
template <bool EnableBool = true>
static typename std::enable_if<(Rows == Columns) && EnableBool, Matrix<Rows, Columns, T>>::type identity();
#endif
protected:
Values _values;
};
#define DEFINE_LENGTH_MATRIX(rows, columns) \
template <typename T = float> \
using Mat##rows##x##columns= Matrix<rows, columns, T>; \
\
template class LUG_MATH_API Matrix<rows, columns, float>; \
using Mat##rows##x##columns##f = Mat##rows##x##columns<float>; \
\
template class LUG_MATH_API Matrix<rows, columns, double>; \
using Mat##rows##x##columns##d = Mat##rows##x##columns<double>; \
\
template class LUG_MATH_API Matrix<rows, columns, int32_t>; \
using Mat##rows##x##columns##i = Mat##rows##x##columns<int32_t>; \
\
template class LUG_MATH_API Matrix<rows, columns, uint32_t>; \
using Mat##rows##x##columns##u = Mat##rows##x##columns<uint32_t>;
DEFINE_LENGTH_MATRIX(2, 2)
DEFINE_LENGTH_MATRIX(2, 3)
DEFINE_LENGTH_MATRIX(2, 4)
DEFINE_LENGTH_MATRIX(3, 2)
DEFINE_LENGTH_MATRIX(3, 3)
DEFINE_LENGTH_MATRIX(3, 4)
DEFINE_LENGTH_MATRIX(4, 2)
DEFINE_LENGTH_MATRIX(4, 3)
DEFINE_LENGTH_MATRIX(4, 4)
#undef DEFINE_LENGTH_MATRIX
// Unary operations
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(const Matrix<Rows, Columns, T>& lhs);
// Matrix/Scalar operations
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator+(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator*(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator/(const Matrix<Rows, Columns, T>& lhs, T rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator+(T lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(T lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator*(T lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator/(T lhs, const Matrix<Rows, Columns, T>& rhs);
// Matrix/Matrix operation
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator+(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
Matrix<Rows, Columns, T> operator-(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t RowsLeft, uint8_t ColumnsLeft, uint8_t RowsRight, uint8_t ColumnsRight, typename T>
Matrix<RowsLeft, ColumnsRight, T> operator*(const Matrix<RowsLeft, ColumnsLeft, T>& lhs, const Matrix<RowsRight, ColumnsRight, T>& rhs);
template <uint8_t RowsLeft, uint8_t ColumnsLeft, uint8_t RowsRight, uint8_t ColumnsRight, typename T>
Matrix<RowsLeft, ColumnsRight, T> operator/(const Matrix<RowsLeft, ColumnsLeft, T>& lhs, const Matrix<RowsRight, ColumnsRight, T>& rhs);
// Comparaison operators
template <uint8_t Rows, uint8_t Columns, typename T>
bool operator==(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
bool operator!=(const Matrix<Rows, Columns, T>& lhs, const Matrix<Rows, Columns, T>& rhs);
template <uint8_t Rows, uint8_t Columns, typename T>
std::ostream& operator<<(std::ostream& os, const Matrix<Rows, Columns, T>& matrix);
#include <lug/Math/Matrix.inl>
} // Math
} // lug
| 38.206751 | 142 | 0.660298 | Lugdunum3D |
de97a2e85933d99eecd9920b7cbf6585da61d37e | 469 | cpp | C++ | problems/acmicpc_1946.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_1946.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_1946.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <utility>
#include <algorithm>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while(t--) {
int n;
scanf("%d", &n);
auto a = new pair<int, int>[n];
for(int i = 0; i < n; i++) {
scanf("%d%d", &a[i].first, &a[i].second);
}
sort(a, a + n);
int x = a[0].second;
int cnt = 1;
for(int i = 1; i < n; i++) {
if(a[i].second < x) {
cnt++;
x = a[i].second;
}
}
printf("%d\n", cnt);
delete[] a;
}
} | 17.37037 | 44 | 0.479744 | qawbecrdtey |
de99adee4df621b0bdf1bdfaaa851877f2b72aca | 6,980 | cc | C++ | src/vnsw/agent/cmn/agent_cmn.cc | sysbot/contrail-controller | 893de3e41aa7b8e40092fba4a5da34284f5ee00f | [
"Apache-2.0"
] | 1 | 2015-11-08T07:28:10.000Z | 2015-11-08T07:28:10.000Z | src/vnsw/agent/cmn/agent_cmn.cc | sysbot/contrail-controller | 893de3e41aa7b8e40092fba4a5da34284f5ee00f | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/cmn/agent_cmn.cc | sysbot/contrail-controller | 893de3e41aa7b8e40092fba4a5da34284f5ee00f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <string>
#include <vector>
#include <base/logging.h>
#include <base/lifetime.h>
#include <io/event_manager.h>
#include <cmn/agent_cmn.h>
#include "cfg/init_config.h"
#include <oper/interface.h>
#include <oper/nexthop.h>
#include <oper/mirror_table.h>
#include <pkt/flowtable.h>
#include <pkt/pkt_types.h>
#include "uve/flow_stats.h"
#include <base/misc_utils.h>
#include <cmn/buildinfo.h>
const std::string Agent::null_str_ = "";
const std::string Agent::fabric_vn_name_ = "default-domain:default-project:ip-fabric";
const std::string Agent::fabric_vrf_name_ =
"default-domain:default-project:ip-fabric:__default__";
const std::string Agent::link_local_vn_name_ =
"default-domain:default-project:__link_local__";
const std::string Agent::link_local_vrf_name_ =
"default-domain:default-project:__link_local__:__link_local__";
AgentStats *AgentStats::singleton_;
Agent *Agent::singleton_;
AgentInit *AgentInit::instance_;
const string &Agent::GetHostInterfaceName() {
// There is single host interface. Its addressed by type and not name
return Agent::null_str_;
};
const string &Agent::GetVirtualHostInterfaceName() {
return virtual_host_intf_name_;
};
void Agent::SetVirtualHostInterfaceName(const string &name) {
virtual_host_intf_name_ = name;
};
const string &Agent::GetHostName() {
return host_name_;
};
bool Agent::GetBuildInfo(std::string &build_info_str) {
return MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info_str);
};
void Agent::SetHostName(const string &name) {
host_name_ = name;
};
bool Agent::isXenMode() {
AgentConfig *config = AgentConfig::GetInstance();
return config->isXenMode();
}
static void SetTaskPolicyOne(const char *task, const char *exclude_list[],
int count) {
TaskScheduler *scheduler = TaskScheduler::GetInstance();
TaskPolicy policy;
for (int i = 0; i < count; ++i) {
int task_id = scheduler->GetTaskId(exclude_list[i]);
policy.push_back(TaskExclusion(task_id));
}
scheduler->SetPolicy(scheduler->GetTaskId(task), policy);
}
void Agent::SetAgentTaskPolicy() {
const char *db_exclude_list[] = {
"Agent::FlowHandler",
"Agent::Services",
"Agent::StatsCollector",
"sandesh::RecvQueue",
"io::ReaderTask",
"Agent::Uve",
"Agent::KSync"
};
SetTaskPolicyOne("db::DBTable", db_exclude_list,
sizeof(db_exclude_list) / sizeof(char *));
const char *flow_exclude_list[] = {
"Agent::StatsCollector",
"io::ReaderTask"
};
SetTaskPolicyOne("Agent::FlowHandler", flow_exclude_list,
sizeof(flow_exclude_list) / sizeof(char *));
const char *sandesh_exclude_list[] = {
"db::DBTable",
"Agent::FlowHandler",
"Agent::Services",
"Agent::StatsCollector",
"io::ReaderTask",
};
SetTaskPolicyOne("sandesh::RecvQueue", sandesh_exclude_list,
sizeof(sandesh_exclude_list) / sizeof(char *));
const char *xmpp_config_exclude_list[] = {
"Agent::FlowHandler",
"Agent::Services",
"Agent::StatsCollector",
"sandesh::RecvQueue",
"io::ReaderTask",
"xmpp::StateMachine",
"db::DBTable"
};
SetTaskPolicyOne("bgp::Config", xmpp_config_exclude_list,
sizeof(xmpp_config_exclude_list) / sizeof(char *));
const char *xmpp_state_machine_exclude_list[] = {
"io::ReaderTask",
"db::DBTable"
};
SetTaskPolicyOne("xmpp::StateMachine", xmpp_state_machine_exclude_list,
sizeof(xmpp_state_machine_exclude_list) / sizeof(char *));
const char *ksync_exclude_list[] = {
"Agent::FlowHandler",
"Agent::StatsCollector",
"db::DBTable"
};
SetTaskPolicyOne("Agent::KSync", ksync_exclude_list,
sizeof(ksync_exclude_list) / sizeof(char *));
}
void Agent::CreateLifetimeManager() {
lifetime_manager_ = new LifetimeManager(
TaskScheduler::GetInstance()->GetTaskId("db::DBTable"));
}
void Agent::ShutdownLifetimeManager() {
delete lifetime_manager_;
lifetime_manager_ = NULL;
}
void AgentStatsReq::HandleRequest() const {
IpcStatsResp *ipc = new IpcStatsResp();
ipc->set_ipc_in_msgs(AgentStats::GetInstance()->GetIpcInMsgs());
ipc->set_ipc_out_msgs(AgentStats::GetInstance()->GetIpcOutMsgs());
ipc->set_context(context());
ipc->set_more(true);
ipc->Response();
PktTrapStatsResp *pkt = new PktTrapStatsResp();
pkt->set_exceptions(AgentStats::GetInstance()->GetPktExceptions());
pkt->set_invalid_agent_hdr(AgentStats::GetInstance()->GetPktInvalidAgentHdr());
pkt->set_invalid_interface(AgentStats::GetInstance()->GetPktInvalidInterface());
pkt->set_no_handler(AgentStats::GetInstance()->GetPktNoHandler());
pkt->set_pkt_dropped(AgentStats::GetInstance()->GetPktDropped());
pkt->set_context(context());
pkt->set_more(true);
pkt->Response();
FlowStatsResp *flow = new FlowStatsResp();
flow->set_flow_active(AgentStats::GetInstance()->GetFlowActive());
flow->set_flow_created(AgentStats::GetInstance()->GetFlowCreated());
flow->set_flow_aged(AgentStats::GetInstance()->GetFlowAged());
flow->set_context(context());
flow->set_more(true);
flow->Response();
XmppStatsResp *xmpp_resp = new XmppStatsResp();
vector<XmppStatsInfo> list;
for (int count = 0; count < MAX_XMPP_SERVERS; count++) {
XmppStatsInfo peer;
if (!Agent::GetInstance()->GetXmppServer(count).empty()) {
peer.set_ip(Agent::GetInstance()->GetXmppServer(count));
AgentXmppChannel *ch = Agent::GetInstance()->GetAgentXmppChannel(count);
if (ch == NULL) {
continue;
}
XmppChannel *xc = ch->GetXmppChannel();
if (xc == NULL) {
continue;
}
peer.set_reconnect(AgentStats::GetInstance()->GetXmppReconnect(count));
peer.set_in_msgs(AgentStats::GetInstance()->GetXmppInMsgs(count));
peer.set_out_msgs(AgentStats::GetInstance()->GetXmppOutMsgs(count));
list.push_back(peer);
}
}
xmpp_resp->set_xmpp_list(list);
xmpp_resp->set_context(context());
xmpp_resp->set_more(true);
xmpp_resp->Response();
SandeshStatsResp *sandesh = new SandeshStatsResp();
sandesh->set_sandesh_in_msgs(AgentStats::GetInstance()->GetSandeshInMsgs());
sandesh->set_sandesh_out_msgs(AgentStats::GetInstance()->GetSandeshOutMsgs());
sandesh->set_sandesh_http_sessions(AgentStats::GetInstance()->GetSandeshHttpSessions());
sandesh->set_sandesh_reconnects(AgentStats::GetInstance()->GetSandeshReconnects());
sandesh->set_context(context());
sandesh->set_more(false);
sandesh->Response();
}
| 34.384236 | 92 | 0.666332 | sysbot |
de9c61d6c8b97e1eac63891e58caadc4bb079554 | 6,422 | cpp | C++ | source/os/cmd_interface_win.cpp | inmoition-depthcamera/sdk | 11f4894295475f6adc896815878fbff9f49b4480 | [
"MIT"
] | 2 | 2018-12-03T03:46:08.000Z | 2020-05-24T04:02:39.000Z | source/os/cmd_interface_win.cpp | inmoition-depthcamera/sdk | 11f4894295475f6adc896815878fbff9f49b4480 | [
"MIT"
] | 1 | 2018-09-20T03:02:35.000Z | 2018-09-30T11:10:40.000Z | source/os/cmd_interface_win.cpp | inmoition-depthcamera/sdk | 11f4894295475f6adc896815878fbff9f49b4480 | [
"MIT"
] | null | null | null | #include "cmd_interface_win.h"
#include <cctype>
#include <algorithm>
#include <SetupAPI.h>
#include <Cfgmgr32.h>
#include "tchar.h"
#pragma comment(lib, "SetupAPI.lib")
#pragma comment(lib, "Cfgmgr32.lib")
#include "iostream"
using namespace std;
CmdInterfaceWin::CmdInterfaceWin()
{
mComHandle = INVALID_HANDLE_VALUE;
memset(&mOverlappedSend, 0, sizeof(OVERLAPPED));
memset(&mOverlappedRecv, 0, sizeof(OVERLAPPED));
mOverlappedSend.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
mOverlappedRecv.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
}
CmdInterfaceWin::~CmdInterfaceWin()
{
if (mOverlappedRecv.hEvent != INVALID_HANDLE_VALUE){
CloseHandle(mOverlappedRecv.hEvent);
mOverlappedRecv.hEvent = INVALID_HANDLE_VALUE;
}
if (mOverlappedSend.hEvent != INVALID_HANDLE_VALUE){
CloseHandle(mOverlappedSend.hEvent);
mOverlappedSend.hEvent = INVALID_HANDLE_VALUE;
}
}
bool CmdInterfaceWin::Open(string &port_name)
{
if (IsOpened())
Close();
mPortName = port_name;
mComHandle = ::CreateFile(port_name.c_str(),
GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (mComHandle == INVALID_HANDLE_VALUE) {
CloseHandle(mComHandle);
return false;
}
PurgeComm(mComHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
if (SetupComm(mComHandle, 102400, 102400) == 0) {
CloseHandle(mComHandle);
return false;
}
DCB dcb;
dcb.DCBlength = sizeof(DCB);
if (GetCommState(mComHandle, &dcb) == 0) {
CloseHandle(mComHandle);
return false;
}
else {
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fRtsControl = 0;
dcb.fDtrControl = 1;// use dtr control to notify usb serial port open and close event
if (SetCommState(mComHandle, &dcb) == 0) {
CloseHandle(mComHandle);
return false;
}
}
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 2;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 5;
timeouts.WriteTotalTimeoutConstant = 50000;
timeouts.WriteTotalTimeoutMultiplier = 1000;
SetCommTimeouts(mComHandle, &timeouts);
mIsCmdOpened = true;
mRxThreadExitFlag = false;
mRxThread = new std::thread(mRxThreadProc, this);
return true;
}
bool CmdInterfaceWin::Close()
{
if (!IsOpened())
return true;
mRxThreadExitFlag = true;
mIsCmdOpened = false;
if (mComHandle != INVALID_HANDLE_VALUE) {
CloseHandle(mComHandle);
mComHandle = INVALID_HANDLE_VALUE;
}
if (mRxThread->joinable())
mRxThread->join();
delete mRxThread;
mRxThread = NULL;
return true;
}
bool CmdInterfaceWin::ReadFromIO(uint8_t * rx_buf, uint32_t rx_buf_len, uint32_t * rx_len)
{
if (IsOpened()) {
uint32_t res;
ResetEvent(mOverlappedRecv.hEvent);
res = ReadFile(mComHandle, rx_buf, rx_buf_len, (LPDWORD)rx_len, &mOverlappedRecv);
if (res == FALSE){
if (GetLastError() == ERROR_IO_PENDING){
if (WaitForSingleObject(mOverlappedRecv.hEvent, INFINITE) == WAIT_OBJECT_0) {
GetOverlappedResult(mComHandle, &mOverlappedRecv, (LPDWORD)rx_len, FALSE);
return true;
}
}
}
}
return false;
}
bool CmdInterfaceWin::WriteToIo(const uint8_t * tx_buf, uint32_t tx_buf_len, uint32_t * tx_len)
{
if (IsOpened()) {
ResetEvent(mOverlappedSend.hEvent);
uint32_t res = WriteFile(mComHandle, tx_buf, tx_buf_len, (LPDWORD)tx_len, &mOverlappedSend);
if (!res){
if (GetLastError() == ERROR_IO_PENDING){
WaitForSingleObject(mOverlappedSend.hEvent, INFINITE);
GetOverlappedResult(mComHandle, &mOverlappedSend, (LPDWORD)tx_len, FALSE);
}
}
}
return true;
}
bool CmdInterfaceWin::GetCmdDevices(std::vector<std::pair<std::string, std::string>>& device_list)
{
const TCHAR * vid_pid1 = _T("VID_0483&PID_5760"), *vid_pid2 = _T("VID_0483&PID_5740");
DWORD dwGuids = 0;
TCHAR prop_buf[1024];
SetupDiClassGuidsFromName(_T("Ports"), NULL, 0, &dwGuids);
if (dwGuids == 0)
return false;
GUID *pGuids = new GUID[dwGuids];
SetupDiClassGuidsFromName(_T("Ports"), pGuids, dwGuids, &dwGuids);
for (DWORD i = 0; i < dwGuids; i++) {
HDEVINFO hDevInfo = SetupDiGetClassDevs(&pGuids[i], NULL, NULL, DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
break;
for (int index = 0; ; index++) {
SP_DEVINFO_DATA devInfo;
std::pair<std::string, std::string> p;
devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
if (!SetupDiEnumDeviceInfo(hDevInfo, index, &devInfo)) { break; }
prop_buf[0] = 0;
CM_Get_Device_ID(devInfo.DevInst, prop_buf, 1024, 0);
if (_tcsstr(prop_buf, vid_pid1) || _tcsstr(prop_buf, vid_pid2)) {
p.second = prop_buf;
HKEY hDeviceKey = SetupDiOpenDevRegKey(hDevInfo, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
if (hDeviceKey) {
prop_buf[0] = 0;
DWORD dw_size = sizeof(prop_buf);
DWORD dw_type = 0;
if ((RegQueryValueEx(hDeviceKey, _T("PortName"), NULL, &dw_type, (LPBYTE)prop_buf, &dw_size) == ERROR_SUCCESS) && (dw_type == REG_SZ)) {
p.first = prop_buf;
device_list.push_back(p);
}
}
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
delete[]pGuids;
return true;
}
bool CmdInterfaceWin::GetUvcRelatedCmdPort(string & uvc_port_name, string & cmd_port_name)
{
std::vector<std::pair<std::string, std::string>> device_list;
bool ret = GetCmdDevices(device_list);
char video_id[32];
string uvc_name = uvc_port_name;
for (uint32_t i = 0; i < uvc_name.length(); i++)
uvc_name[i] = tolower(uvc_name[i]);
const char *id_ptr_end, *id_ptr = strstr(uvc_name.c_str(), "vid_");
if (id_ptr == NULL)
return false;
while (*id_ptr && *id_ptr != '#' && *id_ptr != '\\') id_ptr++;
id_ptr++;
if (strlen(id_ptr) < 5)
return false;
id_ptr_end = id_ptr + 4;
while (*id_ptr_end && *id_ptr_end != '&') id_ptr_end++;
for (int i = 0; i < id_ptr_end - id_ptr; i++)
video_id[i] = tolower(id_ptr[i]); // to lower case
video_id[id_ptr_end - id_ptr] = 0;
if (ret && device_list.size() > 0) {
for (auto dev : device_list) {
for (uint32_t i = 0; i < dev.second.length(); i++)
dev.second[i] = tolower(dev.second[i]);
if (strstr(dev.second.c_str(), video_id)) {
cmd_port_name = "\\\\.\\" + dev.first;
return true;
}
}
}
return false;
} | 28.166667 | 142 | 0.677048 | inmoition-depthcamera |
de9f0148e647af62dac35bb1244d9fccfc910b79 | 4,141 | cpp | C++ | src/sink/asynchronous.p.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 193 | 2015-01-05T08:48:05.000Z | 2022-01-31T22:04:01.000Z | src/sink/asynchronous.p.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 135 | 2015-01-13T13:02:49.000Z | 2022-01-12T15:06:48.000Z | src/sink/asynchronous.p.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 40 | 2015-01-21T16:37:30.000Z | 2022-01-25T15:54:04.000Z | #include "asynchronous.hpp"
#include <cmath>
#include <condition_variable>
#include <mutex>
namespace blackhole {
inline namespace v1 {
namespace sink {
namespace {
auto exp2(std::size_t factor) -> std::size_t {
if (factor < 2 || factor > 20) {
throw std::invalid_argument("factor should fit in [2; 20] range");
}
return static_cast<std::size_t>(std::exp2(factor));
}
} // namespace
class drop_overflow_policy_t : public overflow_policy_t {
typedef overflow_policy_t::action_t action_t;
public:
/// Drops on overlow.
virtual auto overflow() -> action_t {
return action_t::drop;
}
/// Does nothing on wakeup.
virtual auto wakeup() -> void {}
};
class wait_overflow_policy_t : public overflow_policy_t {
typedef overflow_policy_t::action_t action_t;
mutable std::mutex mutex;
std::condition_variable cv;
public:
virtual auto overflow() -> action_t {
std::unique_lock<std::mutex> lock(mutex);
// TODO: WTF? Replace with something more convenient and not filling my eyes with blood.
cv.wait_for(lock, std::chrono::milliseconds(1));
return action_t::retry;
}
virtual auto wakeup() -> void {
cv.notify_one();
}
};
auto overflow_policy_factory_t::create(const std::string& name) const ->
std::unique_ptr<overflow_policy_t>
{
if (name == "drop") {
return std::unique_ptr<overflow_policy_t>(new drop_overflow_policy_t);
} else if (name == "wait") {
return std::unique_ptr<overflow_policy_t>(new wait_overflow_policy_t);
}
throw std::invalid_argument("no overflow policy with name \"" + name + "\" found");
}
asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) :
queue(exp2(factor)),
stopped(false),
wrapped(std::move(wrapped)),
overflow_policy(new wait_overflow_policy_t),
thread(std::bind(&asynchronous_t::run, this))
{}
asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> sink,
std::size_t factor,
std::unique_ptr<overflow_policy_t> overflow_policy) :
queue(exp2(factor)),
stopped(false),
wrapped(std::move(sink)),
overflow_policy(std::move(overflow_policy)),
thread(std::bind(&asynchronous_t::run, this))
{}
asynchronous_t::~asynchronous_t() {
stopped.store(true);
thread.join();
}
auto asynchronous_t::capacity() const -> std::size_t {
return queue.capacity();
}
auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void {
while (true) {
// TODO: Uncomment.
// switch (filter->filter(record, message)) {
// case filter_t::accept:
// case filter_t::neutral:
// break;
// case filter_t::reject:
// return;
// }
const auto enqueued = queue.enqueue_with([&](value_type& value) {
value = {recordbuf_t(record), message.to_string()};
});
if (enqueued) {
// TODO: underflow_policy->wakeup();
return;
} else {
switch (overflow_policy->overflow()) {
case overflow_policy_t::action_t::retry:
continue;
case overflow_policy_t::action_t::drop:
return;
}
}
}
}
auto asynchronous_t::run() -> void {
while (true) {
value_type result;
const auto dequeued = queue.dequeue_with([&](value_type& value) {
result = std::move(value);
});
if (stopped && !dequeued) {
return;
}
if (dequeued) {
try {
wrapped->emit(result.record.into_view(), result.message);
overflow_policy->wakeup();
} catch (...) {
throw;
// TODO: exception_policy->process();
}
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// TODO: underflow_policy->underflow(); [wait for enqueue, sleep].
}
}
}
} // namespace sink
} // namespace v1
} // namespace blackhole
| 27.243421 | 96 | 0.596474 | JakariaBlaine |
dea0a1fb9a741d9064df11dad67398c83e52d92a | 1,738 | hpp | C++ | cpp/include/cuspatial/query.hpp | taureandyernv/cuspatial | 9dc7a4b9c353167e917015b4483a980a802cb581 | [
"Apache-2.0"
] | 2 | 2020-01-30T15:10:05.000Z | 2020-07-13T04:16:42.000Z | cpp/include/cuspatial/query.hpp | taureandyernv/cuspatial | 9dc7a4b9c353167e917015b4483a980a802cb581 | [
"Apache-2.0"
] | null | null | null | cpp/include/cuspatial/query.hpp | taureandyernv/cuspatial | 9dc7a4b9c353167e917015b4483a980a802cb581 | [
"Apache-2.0"
] | 1 | 2021-02-22T08:31:00.000Z | 2021-02-22T08:31:00.000Z | /*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/types.h>
namespace cuspatial {
/**
* @brief Find all points (x,y) that fall within a query window
* (left, bottom, right, top)
* @param[in] left: x-coordinate of left edge of the query window
* @param[in] bottom: y-coordinate of bottom of the query window
* @param[in] right: x-coordinate of right edge of the query window
* @param[in] top: y-coordinate of top of the query window
* @param[in] x: x-coordinates of points to be queried
* @param[in] y: y-coordinates of points to be queried
* @returns pair of gdf_columns of query results of in_x and in_y columns.
*/
std::pair<gdf_column,gdf_column> spatial_window_points(const gdf_scalar& left,
const gdf_scalar& bottom,
const gdf_scalar& right,
const gdf_scalar& top,
const gdf_column& x,
const gdf_column& y);
} // namespace cuspatial
| 39.5 | 81 | 0.607595 | taureandyernv |
dea237dfea8efa14ff17503ac74369a0fbe400a7 | 1,201 | cpp | C++ | src/reactor.cpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | src/reactor.cpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | src/reactor.cpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | #include <sketch/reactor.hpp>
#include <iostream>
#include <sketch/window.hpp>
namespace sk {
namespace {
void
default_on_draw(gsl::not_null<window_t*>)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
}
void
default_on_quit(gsl::not_null<window_t*> window)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
window->quit();
}
void
default_on_keydown(
gsl::not_null<window_t*>, [[maybe_unused]] std::size_t keycode)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
}
void
default_on_mouse_move(
gsl::not_null<window_t*>,
[[maybe_unused]] const std::tuple<std::size_t, std::size_t>& point)
{
// do nothing
std::cout << __FUNCTION__ << '\n';
}
}
reactor_t::reactor_t()
: _on_draw(default_on_draw),
_on_quit(default_on_quit),
_on_keydown(default_on_keydown),
_on_mouse_move(default_on_mouse_move)
{
}
void
reactor_t::on_draw()
{
_on_draw(_window);
}
void
reactor_t::on_quit()
{
_on_quit(_window);
}
void
reactor_t::on_keydown(std::size_t keycode)
{
_on_keydown(_window, keycode);
}
void
reactor_t::on_mouse_move(const std::tuple<std::size_t, std::size_t>& point)
{
_on_mouse_move(_window, point);
}
}
| 15.802632 | 75 | 0.665279 | vladislavmarkov |
dea5f37108a6cba34b584995d6db22083219e47c | 1,021 | cpp | C++ | damc_common/Osc/OscDynamicVariable.cpp | amurzeau/waveplay | e0fc097137138c4a6985998db502468074bf739f | [
"MIT"
] | 5 | 2021-10-02T03:01:56.000Z | 2022-01-24T20:59:19.000Z | damc_common/Osc/OscDynamicVariable.cpp | amurzeau/waveplay | e0fc097137138c4a6985998db502468074bf739f | [
"MIT"
] | null | null | null | damc_common/Osc/OscDynamicVariable.cpp | amurzeau/waveplay | e0fc097137138c4a6985998db502468074bf739f | [
"MIT"
] | null | null | null | #include "OscDynamicVariable.h"
#include <spdlog/spdlog.h>
EXPLICIT_INSTANCIATE_OSC_VARIABLE(template, OscDynamicVariable)
template<typename T>
OscDynamicVariable<T>::OscDynamicVariable(OscContainer* parent, std::string name) : OscContainer(parent, name) {}
template<typename T> std::vector<T> OscDynamicVariable<T>::get() {
if(onReadCallback) {
return onReadCallback();
} else {
return std::vector<T>{};
}
}
template<typename T> std::string OscDynamicVariable<T>::getAsString() const {
return {};
}
template<typename T> void OscDynamicVariable<T>::setReadCallback(std::function<std::vector<T>()> onReadCallback) {
this->onReadCallback = onReadCallback;
}
template<typename T> void OscDynamicVariable<T>::notifyOsc() {
std::vector<OscArgument> valueToSend;
auto values = get();
SPDLOG_TRACE("{} = ", getFullAddress());
valueToSend.reserve(values.size());
for(const auto& v : values) {
SPDLOG_TRACE(" - {} ", v);
valueToSend.push_back(v);
}
sendMessage(&valueToSend[0], valueToSend.size());
}
| 26.179487 | 114 | 0.728697 | amurzeau |
dea84b5648da991e302dc63bcf4d54da31307b40 | 22,928 | hpp | C++ | libraries/belle/Source/Symbols/Chord.hpp | jogawebb/Spaghettis | 78f21ba3065ce316ef0cb84e94aecc9e8787343d | [
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 47 | 2017-09-05T02:49:22.000Z | 2022-01-20T08:11:47.000Z | libraries/belle/Source/Symbols/Chord.hpp | jogawebb/Spaghettis | 78f21ba3065ce316ef0cb84e94aecc9e8787343d | [
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 106 | 2018-05-16T14:58:52.000Z | 2022-01-12T13:57:24.000Z | libraries/belle/Source/Symbols/Chord.hpp | jogawebb/Spaghettis | 78f21ba3065ce316ef0cb84e94aecc9e8787343d | [
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 11 | 2018-05-16T06:44:51.000Z | 2021-11-10T07:04:46.000Z |
/*
Copyright (c) 2007-2013 William Andrew Burnson.
Copyright (c) 2013-2020 Nicolas Danet.
*/
/* < http://opensource.org/licenses/BSD-2-Clause > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* < https://en.wikipedia.org/wiki/Chord_%28music%29 > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* No support for bitonal chord and tonal cluster. */
/* < http://musescore.org/en/node/14449 > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* No support for Maxima, Longa, Breve (and relative rests). */
/* < https://en.wikipedia.org/wiki/Double_whole_note > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace belle {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace Shapes {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Chord {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Note {
public:
Note() : linespace_ (0), isTied_ (false)
{
}
Note (int i, mica::Concept accidental, mica::Concept chromatic, bool tied)
{
linespace_ = i;
accidental_ = accidental;
chromatic_ = chromatic;
isTied_ = tied;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#if PRIM_CPP11
public:
Note (const Note&) = default;
Note (Note&&) = default;
Note& operator = (const Note&) = default;
Note& operator = (Note&&) = default;
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
bool operator < (const Note& o) const
{
mica::Concept diff = mica::index (mica::Accidentals, o.accidental_, accidental_);
return (linespace_ < o.linespace_) || ((linespace_ == o.linespace_) && (diff.getNumerator() < 0));
}
bool operator > (const Note& o) const
{
mica::Concept diff = mica::index (mica::Accidentals, o.accidental_, accidental_);
return (linespace_ > o.linespace_) || ((linespace_ == o.linespace_) && (diff.getNumerator() > 0));
}
bool operator == (const Note& o) const
{
return (linespace_ == o.linespace_) && (accidental_ == o.accidental_);
}
bool operator != (const Note& o) const
{
return !(*this == o);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
int getLinespace() const
{
return linespace_;
}
mica::Concept getAccidental() const
{
return accidental_;
}
mica::Concept getChromatic() const
{
return chromatic_;
}
bool isTied() const
{
return isTied_;
}
private:
int linespace_;
mica::Concept accidental_;
mica::Concept chromatic_;
bool isTied_;
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Chord() : duration_ (Ratio (1, 4)), isStemUp_ (true)
{
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#if PRIM_CPP11
public:
Chord (const Chord&) = default;
Chord (Chord&&) = default;
Chord& operator = (const Chord&) = default;
Chord& operator = (Chord&&) = default;
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Chord& setDuration (mica::Concept duration)
{
duration_ = duration.toRatio(); return *this;
}
Chord& setBeam (mica::Concept beam)
{
beam_ = beam; return *this;
}
Chord& setDirection (mica::Concept direction)
{
direction_ = direction; return *this;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void addNote (mica::Concept linespace, mica::Concept accidental, mica::Concept chromatic, bool tied)
{
notes_.add (Chord::Note (linespace.getNumerator(), accidental, chromatic, tied));
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
/* Due to path filling artifacts flags are engraved later. */
public:
void addToPath (Path& path) const
{
if (!notes_.size()) { path.addShape (Shapes::Rest (duration_)); }
else {
//
prepare (path); /* Note that in functions below only the sorted notes are used. */
path.addPath (engraveLedgerLines());
Path notes (engraveNotes());
path.addPath (engraveDots (notes));
path.addPath (engraveAccidentals (notes));
path.addPath (notes);
//
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
mica::Concept getDirection() const
{
return direction_;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
void prepare (Path& path) const
{
/* In case. */
sorted_.clear();
clustered_.clear();
/* Sort and remove duplicated notes if any. */
Array < Note > temp (notes_);
temp.sort();
sorted_.add (temp.getFirst());
for (int i = 1; i < temp.size(); ++i) { if (temp[i] != temp[i - 1]) { sorted_.add (temp[i]); } }
/* Determine the ties direction. */
temp.clear();
for (int i = 0; i < sorted_.size(); ++i) {
if (sorted_[i].isTied()) { temp.add (sorted_[i]); }
}
if (temp.size()) {
//
path.setProperty (temp.getFirst().getChromatic(), mica::Below);
path.setProperty (temp.getLast().getChromatic(), mica::Above);
for (int i = 1; i < temp.size() - 1; ++i) {
if (temp[i].getLinespace() >= 0) { path.setProperty (temp[i].getChromatic(), mica::Above); }
else {
path.setProperty (temp[i].getChromatic(), mica::Below);
}
}
//
}
/* Determine the stem direction. */
if (direction_ == mica::Undefined) {
Array < int > linespaces;
for (int i = 0; i < sorted_.size(); ++i) { linespaces.add (sorted_[i].getLinespace()); }
direction_ = Utils::getDirection (linespaces);
}
isStemUp_ = (direction_ == mica::Up);
/* Base of the chord always comes first. */
if (isStemUp_ == false) { sorted_.reverse(); }
/* Group notes by clusters (consecutive staff lines and staff spaces). */
Array < Note > cluster;
cluster.add (sorted_.getFirst());
clustered_.add (cluster);
for (int i = 1; i < sorted_.size(); ++i) {
if ((Math::abs ((sorted_[i].getLinespace() - sorted_[i - 1].getLinespace())) < 2)) {
clustered_.getLast().add (sorted_[i]);
} else {
Array < Note > newCluster;
newCluster.add (sorted_[i]);
clustered_.add (newCluster);
}
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
Path engraveLedgerLines() const
{
Path path;
int highNote = getHighestLinespace();
int lowNote = getLowestLinespace();
int highCluster = getHighestLinespaceInClusters();
int lowCluster = getLowestLinespaceInClusters();
for (int i = Utils::getTopLine() + 2; i <= highNote; i += 2) {
Affine affine = Affine::translation (Vector (0.0, Utils::getPosition (i)));
if (i < highCluster) { path.addShape (Shapes::LedgerLineTwoColumn (isStemUp_), affine); }
else {
path.addShape (Shapes::LedgerLine(), affine);
}
}
for (int i = Utils::getBottomLine() - 2; i >= lowNote; i -= 2) {
Affine affine = Affine::translation (Vector (0.0, Utils::getPosition (i)));
if (i > lowCluster) { path.addShape (Shapes::LedgerLineTwoColumn (isStemUp_), affine); }
else {
path.addShape (Shapes::LedgerLine(), affine);
}
}
return path;
}
Path engraveNotes() const
{
Path path;
for (int i = 0; i < sorted_.size(); ++i) {
//
Ratio base = Utils::getUndottedValue (duration_);
double y = Utils::getPosition (sorted_[i].getLinespace());
double x = getColumn (i);
Vector v;
Affine origin;
if (x) { v = Vector (x * (House::kNoteHeadWidthPrecise - (House::kNoteStemThickness / 2.0)), y); }
else {
v = Vector (0.0, y);
}
origin = Affine::translation (v);
path.getBox (sorted_[i].getChromatic()) = Box (v); /* Anchors for ties. */
if (i || (duration_ >= Ratio (1, 1))) {
//
if (base <= Ratio (1, 4)) { path.addShape (Shapes::QuarterNote().setHeight (0.0), origin); }
else if (base == Ratio (1, 2)) { path.addShape (Shapes::HalfNote().setHeight (0.0), origin); }
else {
path.addShape (Shapes::WholeNote(), origin);
}
//
} else {
//
double h = getHeight();
if (base == Ratio (1, 2)) { path.addShape (Shapes::HalfNote().setHeight (h), origin); }
else {
if (beam_ == mica::Undefined) { path.addShape (Shapes::QuarterNote().setHeight (h), origin); }
else {
path.addShape (Shapes::QuarterNote().hasBeam (true).setHeight (h), origin);
}
}
//
}
//
}
/* Rearrange anchors to avoid collision with note heads. */
double right = path.getBounds().getRight();
for (int i = 0; i < sorted_.size(); ++i) {
path.getBox (sorted_[i].getChromatic()).setRight (right);
}
return path;
}
Path engraveDots (Path& notes) const
{
Path path;
int count = Utils::countDots (duration_);
if (count) {
//
Path collision;
/* Reserve the place for the flags. */
if (beam_ == mica::Undefined && Utils::countFlags (duration_)) {
Path flag ((Shapes::FlagStemUp())); /* Avoid most vexing parse. */
Affine affine = Affine::translation (flag.getBounds().getWidth());
collision.addRectangle (notes.getBounds() + affine.appliedTo (notes.getBox (mica::Stem)));
} else {
collision.addRectangle (notes.getBounds());
}
double x = collision.getBounds().getRight() + House::kRhythmicDotDistance;
Array < int > y;
Array < int > remains;
int previous = 1234; /* Dummy. */
for (int i = 0; i < sorted_.size(); ++i) {
//
int linespace = sorted_[i].getLinespace();
int current = (linespace % 2) ? linespace : linespace + 1;
if (current != previous) { y.add (current); previous = current; }
else {
remains.add (current);
}
//
}
for (int i = 0; i < remains.size(); ++i) {
//
int j = 0;
bool placed = false;
while (!placed) {
//
int below = remains[i] - (2 * j);
int above = remains[i] + (2 * j);
if (y.contains (below) == false) { y.add (below); placed = true; }
else if (y.contains (above) == false) { y.add (above); placed = true; }
j++;
//
}
//
}
for (int i = 0; i < y.size(); ++i) {
//
for (int j = 0; j < count; ++j) {
//
Vector v (x + (j * House::kRhythmicDotExtra), Utils::getPosition (y[i]));
Affine origin = Affine::translation (v);
path.addShape (Shapes::RhythmicDot(), origin);
collision.addShape (Shapes::RhythmicDot(), origin);
//
}
//
}
/* Rearrange anchors to avoid collision with dots. */
double right = collision.getBounds().getRight();
for (int i = 0; i < sorted_.size(); ++i) {
notes.getBox (sorted_[i].getChromatic()).setRight (right);
}
//
}
return path;
}
Path engraveAccidentals (Path& notes) const
{
Path path;
Array < Path > shape;
Array < int > order;
Array < Vector > place;
shape.resize (sorted_.size());
order.resize (sorted_.size());
place.resize (sorted_.size());
for (int i = 0; i < sorted_.size(); ++i) {
//
mica::Concept accidental (sorted_[i].getAccidental());
if (accidental == mica::DoubleFlat) { shape[i] = Path (Shapes::AccidentalDoubleFlat()); }
else if (accidental == mica::Flat) { shape[i] = Path (Shapes::AccidentalFlat()); }
else if (accidental == mica::Natural) { shape[i] = Path (Shapes::AccidentalNatural()); }
else if (accidental == mica::Sharp) { shape[i] = Path (Shapes::AccidentalSharp()); }
else if (accidental == mica::DoubleSharp) { shape[i] = Path (Shapes::AccidentalDoubleSharp()); }
//
}
for (int i = 0; i < sorted_.size(); ++i) { /* Alterne from up and down to the middle. */
//
if (isStemUp_) {
if (i % 2 == 0) { order[i] = (sorted_.size() - 1) - (i / 2); }
else {
order[i] = (i - 1) / 2;
}
} else {
if (i % 2 == 0) { order[i] = i / 2; }
else {
order[i] = (sorted_.size() - 1) - (i - 1) / 2;
}
}
//
}
Path collision;
collision.addRectangle (notes.getBounds());
for (int i = 0; i < sorted_.size(); ++i) {
//
if (!shape[order[i]].isEmpty()) {
//
double y = Utils::getPosition (sorted_[order[i]].getLinespace());
double d = Optics::nonCollidingByOutlines (collision, shape[order[i]], Point (0.0, y), kPi);
place[order[i]] = Vector (-(d + House::kAccidentalExtra), y);
collision.addPath (shape[order[i]], Affine::translation (place[order[i]]));
//
}
//
}
Vector v (-(House::kAccidentalDistance - House::kAccidentalExtra), 0.0);
for (int i = 0; i < sorted_.size(); ++i) {
//
if (!shape[order[i]].isEmpty()) {
//
path.addPath (shape[order[i]], Affine::translation (place[order[i]] + v));
//
}
//
}
/* Rearrange anchors to avoid collision with accidentals. */
double left = collision.getBounds().getLeft() + v.getX();
for (int i = 0; i < sorted_.size(); ++i) {
notes.getBox (sorted_[i].getChromatic()).setLeft (left);
}
return path;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
double getHeight() const
{
/* Basic. */
int last = sorted_.getLast().getLinespace();
int first = sorted_.getFirst().getLinespace();
double height = House::kNoteStemHeight + (Math::abs (last - first) * (House::kNoteHeadHeight / 2.0));
/* Extra flags. */
int flags = Utils::countFlags (duration_);
if (flags > 2) { height += (flags - 2) * House::kStaffSpaceWidth; }
/* Ledger lines case. */
bool top = !isStemUp_ && (last > (Utils::getTopLine() + 2));
bool bottom = isStemUp_ && (last < (Utils::getBottomLine() - 2));
if (top || bottom) { height = Math::max (height, Math::abs (Utils::getPosition (first))); }
/* Stem up or stem down. */
return height * (isStemUp_ ? 1.0 : -1.0);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
int getColumn (int i) const
{
for (int j = 0; j < clustered_.size(); ++j) { /* Stagger heads according to clusters. */
//
int n = clustered_[j].size();
if (i >= n) { i -= n; }
else {
break;
}
//
}
if (i % 2 == 0) { return 0; }
else if (isStemUp_) { return 1; }
else {
return -1;
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
int getLowestLinespace() const
{
int n = sorted_.getFirst().getLinespace();
for (int i = 1; i < sorted_.size(); ++i) { n = Math::min (n, sorted_[i].getLinespace()); }
return n;
}
int getLowestLinespaceInClusters() const
{
int n = 0;
bool first = true;
for (int i = 0; i < clustered_.size(); ++i) {
//
if (clustered_[i].size() > 1) {
//
for (int j = 0; j < clustered_[i].size(); ++j) {
if (first) { n = clustered_[i][j].getLinespace(); first = false; }
else {
n = Math::min (n, clustered_[i][j].getLinespace());
}
}
//
}
//
}
return n;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
int getHighestLinespace() const
{
int n = sorted_.getFirst().getLinespace();
for (int i = 1; i < sorted_.size(); ++i) { n = Math::max (n, sorted_[i].getLinespace()); }
return n;
}
int getHighestLinespaceInClusters() const
{
int n = 0;
bool first = true;
for (int i = 0; i < clustered_.size(); ++i) {
//
if (clustered_[i].size() > 1) {
//
for (int j = 0; j < clustered_[i].size(); ++j) {
if (first) { n = clustered_[i][j].getLinespace(); first = false; }
else {
n = Math::max (n, clustered_[i][j].getLinespace());
}
}
//
}
//
}
return n;
}
private:
Ratio duration_;
mutable mica::Concept direction_;
mica::Concept beam_;
Array < Note > notes_;
private:
mutable bool isStemUp_;
mutable Array < Note > sorted_;
mutable Array < Array < Note > > clustered_;
private:
PRIM_LEAK_DETECTOR (Chord)
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace Shapes
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace belle
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
| 32.942529 | 110 | 0.371293 | jogawebb |
dea89fd398cf96bb569d0f1b2240062e33740405 | 5,710 | cpp | C++ | src/ScriptProcs/Event/Keyboard.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/ScriptProcs/Event/Keyboard.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/ScriptProcs/Event/Keyboard.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | #include "../../global.h"
#include "Keyboard.h"
#include "../../Unicode.h"
#include "../../vm.h"
#include "../../Config.h"
int GetKey(ScriptValue *args) {
if (args->type == SCRIPT_LIST && args->listVal->numVals) {
if (args->listVal->vals[0].type == SCRIPT_STRING) {
if (args->listVal->vals[0].stringVal->len) {
int junk;
unsigned long c = NextUnicodeChar(args->listVal->vals[0].stringVal->value, &junk);
if (c > 0xFFFF) return 0;
return 0xFF&VkKeyScanW((wchar_t)c);
}
return 0;
}
else {
ScriptValue sv;
CoerceIntNoRelease(args->listVal->vals[0], sv);
return sv.i32;
}
}
return 0;
}
void ScriptGetKeyState(ScriptValue &s, ScriptValue *args) {
int i = GetKey(args);
CreateIntValue(s, GetKeyState(i));
}
void KeyDown(ScriptValue &s, ScriptValue *args) {
int i = GetKey(args);
if (i && i <= 254) {
int extend = 0;
if (args->type == SCRIPT_LIST && args->listVal->numVals >= 2) {
ScriptValue sv;
CoerceIntNoRelease(args->listVal->vals[1], sv);
if (sv.intVal == 1) {
extend = KEYEVENTF_EXTENDEDKEY;
}
}
keybd_event(i, 0, extend, 0);
}
}
void KeyUp(ScriptValue &s, ScriptValue *args) {
int i = GetKey(args);
if (i && i <= 254) {
int extend = KEYEVENTF_KEYUP;
if (args->type == SCRIPT_LIST && args->listVal->numVals >= 2) {
ScriptValue sv;
CoerceIntNoRelease(args->listVal->vals[1], sv);
if (sv.intVal == 1) {
extend = KEYEVENTF_KEYUP|KEYEVENTF_EXTENDEDKEY;
}
}
keybd_event(i, 0, extend, 0);
}
}
HHOOK hook;
struct KeyboardEvents {
unsigned int total;
unsigned char keys[16*256];
};
KeyboardEvents *keyEvents = 0;
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam) {
if (hook) {
KBDLLHOOKSTRUCT* key = (KBDLLHOOKSTRUCT*) lParam;
int vk = key->vkCode;
if (vk != 120 && vk != 116) {
vk = vk;
}
if (vk >= 0 && vk <= 255) {
if (*((unsigned int*)&keyEvents->keys[vk*16 ]) |
*((unsigned int*)&keyEvents->keys[vk*16 + 4]) |
*((unsigned int*)&keyEvents->keys[vk*16 + 8]) |
*((unsigned int*)&keyEvents->keys[vk*16 + 12])) {
int flags = 0;
int shift;
if (GetKeyState(VK_CONTROL)&0x8000)
flags = KEY_CONTROL;
if ((shift = GetKeyState(VK_SHIFT))&0x8000)
flags |= KEY_SHIFT;
if (GetKeyState(VK_MENU)&0x8000)
flags |= KEY_ALT;
if ((GetKeyState(VK_RWIN) | GetKeyState(VK_LWIN))&0x8000)
flags |= KEY_WIN;
if (keyEvents->keys[vk*16+flags]) {
int down = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);
int scancode = key->scanCode;
unsigned char s[256];
wchar_t key[5];
memset(s, 0, 256);
//int test = GetAsyncKeyState(VK_CAPITAL);
//GetKeyboardState(s);
s[VK_SHIFT] = (shift>>8)&0x80;
s[VK_CAPITAL] = (GetKeyState(VK_CAPITAL))>>8;
s[VK_NUMLOCK] = (GetKeyState(VK_TAB)>>8);
s[VK_SCROLL] = (GetKeyState(VK_SCROLL))>>8;
//s[VK_CONTROL] = (char) GetKeyState(VK_CONTROL);
int wParam = (vk &0xFFFF) + (flags<<16) + (down<<24);
//HKL layout = GetKeyboardLayout(0);
s[vk] = 0x80;
char temp = ToUnicode(vk, scancode, s, key, 5, 0);
int lParam = 0;
if (temp) {
lParam = key[0];
if (temp >= 2) {
lParam = (key[1]<<16);
}
}
PostMessage(ghWnd, WMU_EATEN_KEY, wParam, lParam);
PostMessage(ghWnd, WM_KEYDOWN, wParam, lParam);
return 1;
}
}
}
return CallNextHookEx(hook, code, wParam, lParam);
}
return 0;
}
static void UpdateKeyEvents() {
if (!keyEvents) return;
if (!keyEvents->total && hook) {
UnhookWindowsHookEx(hook);
hook = 0;
free(keyEvents);
keyEvents = 0;
}
else if (!hook) {
hook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, ghInst, 0);
if (!hook) errorPrintf(0, "Hook creation failed: %i\n", GetLastError());
}
}
void CleanKeyEvents() {
if (keyEvents) {
UnhookWindowsHookEx(hook);
hook = 0;
free(keyEvents);
keyEvents = 0;
}
}
void RegisterKeyEvent(ScriptValue &s, ScriptValue *args) {
if (args->type != SCRIPT_LIST) return;
ListValue *list = args->listVal;
int len = list->numVals;
if (len < 2) return;
ScriptValue sv;
CoerceIntNoRelease(list->vals[0], sv);
int dCare = (sv.i32>>16)&15;
sv.intVal -= (dCare<<16);
if (sv.intVal < 0 || sv.intVal > 15 || (dCare&sv.i32)) return;
if (!keyEvents) {
keyEvents = (KeyboardEvents*)calloc(1, sizeof(KeyboardEvents));
if (!keyEvents) return;
}
int state = sv.i32;
int count = 0;
for (int j=0; j<16; j++) {
if (!(j&~dCare)) {
int state2 = state+j;
for (int i=1; i < len; i++) {
CoerceIntNoRelease(list->vals[i], sv);
if (sv.intVal < 0 || sv.intVal > 255) continue;
int t = sv.i32*16 + state2;
if (keyEvents->keys[t] == 255) continue;
keyEvents->keys[t]++;
keyEvents->total++;
count ++;
}
}
}
UpdateKeyEvents();
if (count) {
CreateIntValue(s, count);
}
}
void UnregisterKeyEvent(ScriptValue &s, ScriptValue *args) {
if (args->type != SCRIPT_LIST) return;
ListValue *list = args->listVal;
int len = list->numVals;
if (len < 2) return;
ScriptValue sv;
CoerceIntNoRelease(list->vals[0], sv);
int dCare = (sv.i32>>16)&15;
sv.intVal -= (dCare<<16);
if (sv.intVal < 0 || sv.intVal > 15 || (dCare&sv.i32)) return;
if (!keyEvents) return;
int state = sv.i32;
int count = 0;
for (int j=0; j<16; j++) {
if (!(j&~dCare)) {
int state2 = state+j;
for (int i=1; i < len; i++) {
CoerceIntNoRelease(list->vals[i], sv);
if (sv.intVal < 0 || sv.intVal > 255) continue;
int t = sv.i32*16 + state2;
if (!keyEvents->keys[t]) continue;
keyEvents->keys[t]--;
keyEvents->total--;
count ++;
}
}
}
UpdateKeyEvents();
if (count) {
CreateIntValue(s, count);
}
}
| 25.605381 | 86 | 0.605954 | MichaelMCE |
deac547ad73748c5e87d2125b7fc3a022d4576e1 | 2,699 | cpp | C++ | src/T56_memoryManager/T56_memoryManager.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 11 | 2017-06-06T23:02:48.000Z | 2021-08-17T20:13:05.000Z | src/T56_memoryManager/T56_memoryManager.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 1 | 2017-06-06T23:08:05.000Z | 2017-06-07T09:28:08.000Z | src/T56_memoryManager/T56_memoryManager.cpp | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | null | null | null | void T56_memoryManager::doStuff(Haplotype& haplo)
{
auto& ntrl = haplo.T5ntrl_Alleles;
auto& sel = haplo.T5sel_Alleles;
/////////////////
// Record info //
/////////////////
if (shouldRecordInfo)
{
if (SSP->Gmap.T5ntrl_nbLoci && ntrl.size() > maxNtrlSizeLastGeneration)
maxNtrlSizeLastGeneration = ntrl.size();
if (SSP->Gmap.T5sel_nbLoci && sel.size() > maxSelSizeLastGeneration)
maxSelSizeLastGeneration = sel.size();
}
////////////
// Shrink //
////////////
if (shouldShrink)
{
if (SSP->Gmap.T5ntrl_nbLoci)
{
if (ntrl.capacity() > 1.1 * (double)ntrl.size()) // if there is some non-negligible loss
{
auto oldCapacity = ntrl.capacity();
ntrl.shrink_to_fit();
if (oldCapacity > maxNtrlSizeLastGeneration && ntrl.size() < maxNtrlSizeLastGeneration && ntrl.size() > (double)maxNtrlSizeLastGeneration / 1.5)
{
ntrl.reserve(maxNtrlSizeLastGeneration);
} else
{
ntrl.reserve(1.1 * (double)ntrl.size());
}
}
}
if (SSP->Gmap.T5sel_nbLoci)
{
if (sel.capacity() > 1.1 * (double)sel.size()) // if there is some non-negligible loss
{
auto oldCapacity = sel.capacity();
sel.shrink_to_fit();
if (oldCapacity > maxNtrlSizeLastGeneration && sel.size() < maxSelSizeLastGeneration && sel.size() > (double)maxSelSizeLastGeneration / 1.5)
{
sel.reserve(maxSelSizeLastGeneration);
} else
{
sel.reserve(1.1 * (double)sel.size());
}
}
}
}
}
void T56_memoryManager::setGenerationInfo()
{
if (attempt_shrinking_every_N_generation != -1)
{
// If info was recorded last generation
if (shouldRecordInfo)
shouldShrink = true;
else
shouldShrink = false;
// Check if it is time to record information
if (GP->CurrentGeneration % attempt_shrinking_every_N_generation == 0)
shouldRecordInfo = true;
else
shouldRecordInfo = false;
}
}
template<typename INT>
void T56_memoryManager::set_attempt_shrinking_every_N_generation(INT i)
{
if (i != -1 && i < 2)
{
std::cout << "For option --shrinkT56EveryNGeneration, received a value that is lower than two and differentt from -1 (-1 means no shrinking)\n";
abort();
}
attempt_shrinking_every_N_generation = i;
}
| 31.022989 | 160 | 0.537607 | RemiMattheyDoret |
deb1711bc6acdcc92c3b6744d3b87893624f5c61 | 1,291 | cc | C++ | auxil/binpac/src/pac_enum.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | 1 | 2021-03-06T19:51:07.000Z | 2021-03-06T19:51:07.000Z | auxil/binpac/src/pac_enum.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | auxil/binpac/src/pac_enum.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | #include "pac_exception.h"
#include "pac_enum.h"
#include "pac_expr.h"
#include "pac_exttype.h"
#include "pac_output.h"
#include "pac_typedecl.h"
Enum::Enum(ID* id, Expr* expr)
: id_(id), expr_(expr)
{
}
Enum::~Enum()
{
delete id_;
delete expr_;
}
void Enum::GenHeader(Output* out_h, int *pval)
{
ASSERT(pval);
if ( expr_ )
{
if ( ! expr_->ConstFold(global_env(), pval) )
throw ExceptionNonConstExpr(expr_);
out_h->println("%s = %d,", id_->Name(), *pval);
}
else
out_h->println("%s,", id_->Name());
global_env()->AddConstID(id_, *pval);
}
EnumDecl::EnumDecl(ID *id, EnumList *enumlist)
: Decl(id, ENUM), enumlist_(enumlist)
{
ID *type_id = id->clone();
datatype_ = new ExternType(type_id, ExternType::NUMBER);
extern_typedecl_ = new TypeDecl(type_id, 0, datatype_);
}
EnumDecl::~EnumDecl()
{
delete_list(EnumList, enumlist_);
delete extern_typedecl_;
}
void EnumDecl::Prepare()
{
// Do nothing
}
void EnumDecl::GenForwardDeclaration(Output *out_h)
{
out_h->println("enum %s {", id_->Name());
out_h->inc_indent();
int c = 0;
foreach(i, EnumList, enumlist_)
{
(*i)->GenHeader(out_h, &c);
++c;
}
out_h->dec_indent();
out_h->println("};");
}
void EnumDecl::GenCode(Output* out_h, Output* /* out_cc */)
{
// Do nothing
}
| 18.183099 | 59 | 0.643687 | hugolin615 |
deb6cfa20098fe6465e4cf57c429b2ae34bba38f | 891 | cpp | C++ | Source/ModularGameplayActors/Private/ModularAIController.cpp | TheEmidee/UEModularGameplayActors | 9f87c2e4a418f90a2735c823ccb94e43a7721aaf | [
"MIT"
] | 1 | 2022-02-16T10:44:28.000Z | 2022-02-16T10:44:28.000Z | Source/ModularGameplayActors/Private/ModularAIController.cpp | TheEmidee/UEModularGameplayActors | 9f87c2e4a418f90a2735c823ccb94e43a7721aaf | [
"MIT"
] | null | null | null | Source/ModularGameplayActors/Private/ModularAIController.cpp | TheEmidee/UEModularGameplayActors | 9f87c2e4a418f90a2735c823ccb94e43a7721aaf | [
"MIT"
] | null | null | null | #include "ModularAIController.h"
#include <Components/GameFrameworkComponentManager.h>
void AModularAIController::PreInitializeComponents()
{
Super::PreInitializeComponents();
if ( auto * gi = GetGameInstance() )
{
if ( auto * system = gi->GetSubsystem< UGameFrameworkComponentManager >() )
{
system->AddReceiver( this );
}
}
}
void AModularAIController::BeginPlay()
{
UGameFrameworkComponentManager::SendGameFrameworkComponentExtensionEvent( this, UGameFrameworkComponentManager::NAME_GameActorReady );
Super::BeginPlay();
}
void AModularAIController::EndPlay( const EEndPlayReason::Type EndPlayReason )
{
if ( auto * system = GetGameInstance()->GetSubsystem< UGameFrameworkComponentManager >() )
{
system->RemoveReceiver( this );
}
Super::EndPlay( EndPlayReason );
} | 27 | 139 | 0.67789 | TheEmidee |
6312197b3a45d40f0d3df1d3f1156ab513b3d9ce | 1,307 | hpp | C++ | include/oxu/beatmap/components/slider.hpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | include/oxu/beatmap/components/slider.hpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | include/oxu/beatmap/components/slider.hpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | #pragma once
#include<cstdint>
#include<vector>
#include<oxu/beatmap/sections/difficulty.hpp>
#include<oxu/beatmap/components/hitCircle.hpp>
#include<oxu/framework/utils/vector2.hpp>
namespace oxu
{
enum class SliderCurveType
{
LINEAR = 0,
BEZIER = 1,
CIRCLE = 2
};
struct SliderInfo
{
SliderCurveType curve_type;
std::vector<framework::Vector2<float>> curve_points;
std::uint16_t slides;
double length;
/* edge sounds && edge sets */
};
class Slider : public HitCircle
{
private:
std::vector<framework::Vector2<float>> m_curve_points;
SliderCurveType m_curve_type;
std::uint16_t m_slides;
double m_length;
public:
Slider(
const ObjectInfo &obj_info,
const SliderInfo &slider_info,
const Difficulty &difficulty
);
void update(const double &delta, const Difficulty &difficulty) override;
void render(const Skin &skin) override;
void setErrorMargin(const long double &err, const Difficulty &difficulty) override;
bool shouldAddToPool(const std::uint32_t &mapTimeMs, const std::uint16_t &approach_rate_ms) const override;
bool shouldRemoveFromPool() const override;
};
}
| 26.14 | 115 | 0.644989 | oda404 |
631312d7b2678ed172f6f3ae98d26fe6dc006e13 | 326 | cpp | C++ | symbolinen_konekieli/Ratol_msdos/proj3/h53paa.cpp | tkukka/VariousContent | f7e7ae98ff8521c6c709dabe30855104afe3fe04 | [
"MIT"
] | null | null | null | symbolinen_konekieli/Ratol_msdos/proj3/h53paa.cpp | tkukka/VariousContent | f7e7ae98ff8521c6c709dabe30855104afe3fe04 | [
"MIT"
] | null | null | null | symbolinen_konekieli/Ratol_msdos/proj3/h53paa.cpp | tkukka/VariousContent | f7e7ae98ff8521c6c709dabe30855104afe3fe04 | [
"MIT"
] | null | null | null | //RaTol Symbolinen konekieli: Harjoitus 5, tehtävä 3
//Tero Kukka IY96A
//Tiedosto: h53paa.cpp
//Luotu: 25.4.1998
#include <constrea.h>
#include "header.h"
int main(void)
{
int taulu[100], lkm;
lkm = Lue(taulu, 100);
lajittele(taulu, lkm);
Tulosta(taulu, lkm);
return 0;
}
| 15.52381 | 60 | 0.592025 | tkukka |
631322d8229d61cf4bc8806c6550bc0689b4b3ff | 543 | hpp | C++ | Source/ThirdParty/tracy/server/TracySort.hpp | ValtoGameEngines/RBFX-Engine | f96fbeaea3a7c7a62d4bc430dc3dd4eff19ec086 | [
"MIT"
] | 1 | 2021-01-09T14:42:48.000Z | 2021-01-09T14:42:48.000Z | Source/ThirdParty/tracy/server/TracySort.hpp | ValtoGameEngines/RBFX-Engine | f96fbeaea3a7c7a62d4bc430dc3dd4eff19ec086 | [
"MIT"
] | null | null | null | Source/ThirdParty/tracy/server/TracySort.hpp | ValtoGameEngines/RBFX-Engine | f96fbeaea3a7c7a62d4bc430dc3dd4eff19ec086 | [
"MIT"
] | 1 | 2020-06-29T08:05:12.000Z | 2020-06-29T08:05:12.000Z | #ifndef __TRACYSORT_HPP__
#define __TRACYSORT_HPP__
#ifdef TRACY_NO_PARALLEL_ALGORITHMS // rbfx: Need a way to disable use of tbb. It is broken on any version of clang on ubuntu 18.04 (2020-02-20).
# define NO_PARALLEL_SORT
#elif ( defined _MSC_VER && _MSVC_LANG >= 201703L ) || __cplusplus >= 201703L
# if __has_include(<execution>)
# include <algorithm>
# include <execution>
# else
# define NO_PARALLEL_SORT
# endif
#else
# define NO_PARALLEL_SORT
#endif
#ifdef NO_PARALLEL_SORT
# include "tracy_pdqsort.h"
#endif
#endif
| 23.608696 | 145 | 0.742173 | ValtoGameEngines |
63160e547d733a2c8efac6c5f63f11d195f041f2 | 1,511 | hpp | C++ | include/managers/state_manager.hpp | zedrex/algosketch | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 16 | 2021-03-27T06:20:42.000Z | 2022-03-31T16:30:37.000Z | include/managers/state_manager.hpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 1 | 2021-07-13T07:57:41.000Z | 2021-07-13T07:57:41.000Z | include/managers/state_manager.hpp | zedrex/Algo-Plus-Plus | ff0f759f9e7e0e4ff040cf6c84334aceac47adae | [
"MIT"
] | 3 | 2021-04-03T02:58:56.000Z | 2021-06-04T18:23:49.000Z | #pragma once
#include <iostream>
#include <managers/window_manager.hpp>
#include <managers/event_manager.hpp>
#include <managers/resource_manager.hpp>
class State;
enum class Action
{
ChangeToMainMenu,
ChangeToNewSketchMenu,
ChangeToLoadSketchMenu,
ChangeToHelpMenu,
ChangeToCreditsMenu,
QuitApplication,
Array,
Graph,
Grid,
String,
Create,
Reset,
Run,
Pause,
Back,
BubbleSort,
SelectionSort,
InsertionSort,
ShellSort,
GnomeSort,
GraphDepthFirstSearch,
GraphBreadthFirstSearch,
GraphDijkstra,
GridDepthFirstSearch,
GridBreadthFirstSearchPathfinding,
GridFloodFill,
GridAStarPathfinder
};
class StateManager
{
public:
StateManager();
StateManager(WindowManager *applicationWindowManager, EventManager *applicationEventManager, ResourceManager *applicationResourceManager);
~StateManager();
void setWindowManager(WindowManager *applicationWindowManager);
void setEventManager(EventManager *applicationEventManager);
void setResourceManager(ResourceManager *applicationResourceManager);
void start();
State *getCurrentState();
WindowManager *getApplicationWindow();
EventManager *getEventManager();
void perform(Action action);
void changeState(State *newState);
void update();
void render();
private:
WindowManager *windowManager;
EventManager *eventManager;
ResourceManager *resourceManager;
State *currentState;
};
| 19.881579 | 142 | 0.731304 | zedrex |
6319d76c16f2570a4f6e5a180ba9cdb8682a5e56 | 9,305 | hpp | C++ | include/standardese/cpp_function.hpp | Manu343726/standardese | 0f7d997f0141b63795b2585397e97973c54c2bbc | [
"MIT"
] | null | null | null | include/standardese/cpp_function.hpp | Manu343726/standardese | 0f7d997f0141b63795b2585397e97973c54c2bbc | [
"MIT"
] | null | null | null | include/standardese/cpp_function.hpp | Manu343726/standardese | 0f7d997f0141b63795b2585397e97973c54c2bbc | [
"MIT"
] | 1 | 2018-09-03T05:44:25.000Z | 2018-09-03T05:44:25.000Z | // Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef STANDARDESE_CPP_FUNCTION_HPP_INCLUDED
#define STANDARDESE_CPP_FUNCTION_HPP_INCLUDED
#include <string>
#include <standardese/cpp_entity.hpp>
#include <standardese/cpp_type.hpp>
namespace standardese
{
class cpp_function_parameter
: public cpp_parameter_base
{
public:
static cpp_ptr<cpp_function_parameter> parse(cpp_cursor cur);
cpp_function_parameter(cpp_name name, cpp_raw_comment comment,
cpp_type_ref type, std::string default_value = "")
: cpp_parameter_base(function_parameter_t, std::move(name), std::move(comment)),
type_(std::move(type)), default_(std::move(default_value)) {}
const cpp_type_ref& get_type() const STANDARDESE_NOEXCEPT
{
return type_;
}
bool has_default_value() const STANDARDESE_NOEXCEPT
{
return !default_.empty();
}
const std::string& get_default_value() const STANDARDESE_NOEXCEPT
{
return default_;
}
private:
cpp_type_ref type_;
std::string default_;
};
enum cpp_function_flags : unsigned
{
cpp_variadic_fnc = 1,
cpp_constexpr_fnc = 2,
cpp_explicit_conversion = 4,
};
enum cpp_function_definition
{
cpp_function_definition_normal,
cpp_function_definition_deleted,
cpp_function_definition_defaulted,
};
struct cpp_function_info
{
cpp_function_flags flags = cpp_function_flags(0);
cpp_function_definition definition = cpp_function_definition_normal;
std::string noexcept_expression;
bool explicit_noexcept = false;
void set_flag(cpp_function_flags f) STANDARDESE_NOEXCEPT
{
flags = cpp_function_flags(unsigned(flags) | unsigned(f));
}
};
// common stuff for all functions
class cpp_function_base
: public cpp_entity, private cpp_entity_container<cpp_function_parameter>
{
public:
static cpp_ptr<cpp_function_base> try_parse(cpp_name scope, cpp_cursor cur);
void add_parameter(cpp_ptr<cpp_function_parameter> param)
{
cpp_entity_container::add_entity(std::move(param));
}
const cpp_entity_container<cpp_function_parameter>& get_parameters() const STANDARDESE_NOEXCEPT
{
return *this;
}
bool is_variadic() const STANDARDESE_NOEXCEPT
{
return info_.flags & cpp_variadic_fnc;
}
bool is_constexpr() const STANDARDESE_NOEXCEPT
{
return info_.flags & cpp_constexpr_fnc;
}
bool is_explicit() const STANDARDESE_NOEXCEPT
{
return info_.flags & cpp_explicit_conversion;
}
cpp_function_definition get_definition() const STANDARDESE_NOEXCEPT
{
return info_.definition;
}
// the part inside a noexcept(...)
// noexcept without condition leads to "true"
// no noexcept at all leads to "false"
const std::string& get_noexcept() const STANDARDESE_NOEXCEPT
{
return info_.noexcept_expression;
}
bool explicit_noexcept() const STANDARDESE_NOEXCEPT
{
return info_.explicit_noexcept;
}
protected:
cpp_function_base(cpp_entity::type t,
cpp_name scope, cpp_name name, cpp_raw_comment comment,
cpp_function_info info)
: cpp_entity(t, std::move(scope), std::move(name), std::move(comment)),
info_(std::move(info)) {}
private:
cpp_function_info info_;
};
class cpp_function
: public cpp_function_base
{
public:
static cpp_ptr<cpp_function> parse(cpp_name scope, cpp_cursor cur);
cpp_function(cpp_name scope, cpp_name name, cpp_raw_comment comment,
cpp_type_ref return_type, cpp_function_info info)
: cpp_function_base(function_t,
std::move(scope), std::move(name), std::move(comment),
std::move(info)),
return_(std::move(return_type)) {}
const cpp_type_ref& get_return_type() const STANDARDESE_NOEXCEPT
{
return return_;
}
private:
cpp_type_ref return_;
};
enum cpp_cv
{
cpp_cv_const = 1,
cpp_cv_volatile = 2,
};
inline bool is_const(cpp_cv cv) STANDARDESE_NOEXCEPT
{
return cv & cpp_cv_const;
}
inline bool is_volatile(cpp_cv cv) STANDARDESE_NOEXCEPT
{
return cv & cpp_cv_volatile;
}
enum cpp_ref_qualifier
{
cpp_ref_none,
cpp_ref_lvalue,
cpp_ref_rvalue
};
enum cpp_virtual
{
cpp_virtual_static,
cpp_virtual_none,
cpp_virtual_pure,
cpp_virtual_new,
cpp_virtual_overriden,
cpp_virtual_final
};
inline bool is_virtual(cpp_virtual virt) STANDARDESE_NOEXCEPT
{
return virt != cpp_virtual_static && virt != cpp_virtual_none;
}
inline bool is_overriden(cpp_virtual virt) STANDARDESE_NOEXCEPT
{
return virt == cpp_virtual_overriden || virt == cpp_virtual_final;
}
struct cpp_member_function_info
{
cpp_cv cv_qualifier = cpp_cv(0);
cpp_ref_qualifier ref_qualifier = cpp_ref_none;
cpp_virtual virtual_flag = cpp_virtual_none;
void set_cv(cpp_cv cv) STANDARDESE_NOEXCEPT
{
cv_qualifier = cpp_cv(unsigned(cv_qualifier) | unsigned(cv));
}
};
class cpp_member_function
: public cpp_function
{
public:
static cpp_ptr<cpp_member_function> parse(cpp_name scope, cpp_cursor cur);
cpp_member_function(cpp_name scope, cpp_name name, cpp_raw_comment comment,
cpp_type_ref return_type,
cpp_function_info finfo, cpp_member_function_info minfo)
: cpp_function(std::move(scope), std::move(name), std::move(comment),
std::move(return_type), std::move(finfo)),
info_(minfo)
{
set_type(member_function_t);
}
cpp_cv get_cv() const STANDARDESE_NOEXCEPT
{
return info_.cv_qualifier;
}
cpp_ref_qualifier get_ref_qualifier() const STANDARDESE_NOEXCEPT
{
return info_.ref_qualifier;
}
cpp_virtual get_virtual() const STANDARDESE_NOEXCEPT
{
return info_.virtual_flag;
}
private:
cpp_member_function_info info_;
};
class cpp_conversion_op
: public cpp_function_base
{
public:
static cpp_ptr<cpp_conversion_op> parse(cpp_name scope, cpp_cursor cur);
cpp_conversion_op(cpp_name scope, cpp_name name, cpp_raw_comment comment,
cpp_type_ref target_type,
cpp_function_info finfo, cpp_member_function_info minfo)
: cpp_function_base(conversion_op_t,
std::move(scope), std::move(name), std::move(comment),
std::move(finfo)),
target_type_(std::move(target_type)), info_(minfo) {}
const cpp_type_ref& get_target_type() const STANDARDESE_NOEXCEPT
{
return target_type_;
}
cpp_cv get_cv() const STANDARDESE_NOEXCEPT
{
return info_.cv_qualifier;
}
cpp_ref_qualifier get_ref_qualifier() const STANDARDESE_NOEXCEPT
{
return info_.ref_qualifier;
}
cpp_virtual get_virtual() const STANDARDESE_NOEXCEPT
{
return info_.virtual_flag;
}
private:
cpp_type_ref target_type_;
cpp_member_function_info info_;
};
class cpp_constructor
: public cpp_function_base
{
public:
static cpp_ptr<cpp_constructor> parse(cpp_name scope, cpp_cursor cur);
cpp_constructor(cpp_name scope, cpp_name name, cpp_raw_comment comment,
cpp_function_info info)
: cpp_function_base(constructor_t,
std::move(scope), std::move(name), std::move(comment),
std::move(info)) {}
};
class cpp_destructor
: public cpp_function_base
{
public:
static cpp_ptr<cpp_destructor> parse(cpp_name scope, cpp_cursor cur);
cpp_destructor(cpp_name scope, cpp_name name, cpp_raw_comment comment,
cpp_function_info info, cpp_virtual virtual_flag)
: cpp_function_base(destructor_t,
std::move(scope), std::move(name), std::move(comment),
std::move(info)),
virtual_(virtual_flag) {}
cpp_virtual get_virtual() const STANDARDESE_NOEXCEPT
{
return virtual_;
}
private:
cpp_virtual virtual_;
};
} // namespace standardese
#endif // STANDARDESE_CPP_FUNCTION_HPP_INCLUDED
| 28.897516 | 103 | 0.616443 | Manu343726 |
63204c5730e690db4ecfa8622777acef7b5707d1 | 4,138 | cpp | C++ | src/util/Screenshotter.cpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | 5 | 2020-01-15T12:49:45.000Z | 2021-11-24T05:15:59.000Z | src/util/Screenshotter.cpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | null | null | null | src/util/Screenshotter.cpp | dat14jpe/mulen | 33beeb8a38e5556ddd44efba909e18aab9a3d401 | [
"MIT"
] | null | null | null | #include "Screenshotter.hpp"
#include "GLObject.hpp"
#include "lodepng.h"
#include <iostream>
namespace Util {
Screenshotter::Screenshotter()
: thread{ &Screenshotter::Thread, this }
{
}
Screenshotter::~Screenshotter()
{
{
std::lock_guard<std::mutex> lk(m);
done = true;
}
cv.notify_one();
thread.join();
}
void Screenshotter::Thread()
{
while (true)
{
std::unique_ptr<Job> job;
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [&] { return done || jobs.size(); });
if (done) break;
job = std::move(jobs.front());
jobs.pop();
}
Save(*job);
}
}
void Screenshotter::TakeScreenshot(const std::string& filename, glm::uvec2 size, KeyValuePairs&& keyValuePairs)
{
// - to do: reuse job objects (there's little need for dynamic allocation all the time)
std::unique_ptr<Job> job(new Job{});
job->keyValuePairs = keyValuePairs;
job->size = size;
auto& image = job->image;
auto& channels = job->channels = 3u;
image.resize(size.x * size.y * channels);
// Retrieve from OpenGL buffer.
//glBindFramebuffer(GL_FRAMEBUFFER, 0u);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, size.x, size.y, channels == 4u ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, image.data());
{
std::lock_guard<std::mutex> lk(m);
jobs.push(std::move(job));
auto& job = jobs.back();
job->filename = filename;
}
cv.notify_one();
}
void Screenshotter::Save(Job& job)
{
auto& image = job.image;
auto& size = job.size;
auto& channels = job.channels;
// Reverse vertically.
for (auto y = 0u; y < size.y / 2u; ++y)
{
for (auto x = 0u; x < size.x; ++x)
{
for (auto c = 0u; c < channels; ++c)
{
auto i0 = (y * size.x + x) * channels + c;
auto i1 = ((size.y - 1u - y) * size.x + x) * channels + c;
auto temp = image[i0];
image[i0] = image[i1];
image[i1] = temp;
}
}
}
// Encode and save PNG.
// - to do: possibly do this in another thread instead
std::vector<unsigned char> png;
lodepng::State state;
if (false) // - to do: make this configurable
{
// Aim for best compression.
state.encoder.filter_palette_zero = 0; //We try several filter types, including zero, allow trying them all on palette images too.
state.encoder.add_id = false; //Don't add LodePNG version chunk to save more bytes
state.encoder.text_compression = 1; //Not needed because we don't add text chunks, but this demonstrates another optimization setting
state.encoder.zlibsettings.nicematch = 258; //Set this to the max possible, otherwise it can hurt compression
state.encoder.zlibsettings.lazymatching = 1; //Definitely use lazy matching for better compression
state.encoder.zlibsettings.windowsize = 32768; //Use maximum possible window size for best compression
}
// Set up colour types.
state.info_png.color.colortype = LCT_RGB;
state.info_png.color.bitdepth = 8;
state.info_raw.colortype = LCT_RGB;
state.info_raw.bitdepth = 8;
state.encoder.auto_convert = 0;
// Add custom data (key/value strings).
for (auto entry : job.keyValuePairs)
{
lodepng_add_text(&state.info_png, entry.first.c_str(), entry.second.c_str());
}
unsigned error = lodepng::encode(png, image, size.x, size.y, state);
if (!error) lodepng::save_file(png, job.filename.c_str());
if (error) std::cout << "PNG encoder error " << error << ": " << lodepng_error_text(error) << std::endl;
}
}
| 34.483333 | 145 | 0.545191 | dat14jpe |
63230a259fe05b0d4ae620550ca29fcd2de20843 | 313 | cpp | C++ | src/mainApp.cpp | ChayanonPitak/Uics | 0d78f57adcb779aebced8088057555be7def78dc | [
"MIT"
] | 1 | 2021-03-14T07:25:40.000Z | 2021-03-14T07:25:40.000Z | src/mainApp.cpp | ChayanonPitak/Uics | 0d78f57adcb779aebced8088057555be7def78dc | [
"MIT"
] | 13 | 2021-02-21T14:53:19.000Z | 2021-03-18T15:52:51.000Z | src/mainApp.cpp | ChayanonPitak/Uics | 0d78f57adcb779aebced8088057555be7def78dc | [
"MIT"
] | 1 | 2021-07-03T04:36:04.000Z | 2021-07-03T04:36:04.000Z | #include "mainApp.h"
#include "mainFrame.h"
#include <wx/wxprec.h>
wxIMPLEMENT_APP(mainApp);
bool mainApp::OnInit()
{
wxInitAllImageHandlers();
mainFrame* _mainFrame = new mainFrame();
_mainFrame->SetIcons(wxIconBundle("..\\resources\\icon.png", wxBITMAP_TYPE_PNG));
_mainFrame->Show(true);
return true;
} | 20.866667 | 82 | 0.738019 | ChayanonPitak |
63230eb064852458e2ae1afa5b139f4557eedace | 898 | cpp | C++ | src/main.cpp | jklee95/PBDEnergyProjection | 8608e2428d1e84fe129c28b1410940d6c66f85bb | [
"MIT"
] | 1 | 2022-01-25T07:26:24.000Z | 2022-01-25T07:26:24.000Z | src/main.cpp | jklee95/PBDEnergyProjection | 8608e2428d1e84fe129c28b1410940d6c66f85bb | [
"MIT"
] | null | null | null | src/main.cpp | jklee95/PBDEnergyProjection | 8608e2428d1e84fe129c28b1410940d6c66f85bb | [
"MIT"
] | null | null | null | #pragma once
// Console window is displayed in debug mode.
#ifdef _DEBUG
#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console")
#endif
#include "SimulationManager.h" // This includes Win32App.h
using namespace DXViewer::xmint3;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd)
{
int x = 8;
int y = 16;
float dt = 0.01f;
SimulationManager* sim = new SimulationManager(x, y, dt);
DX12App* dxapp = new DX12App();
dxapp->setCameraProperties(
PROJ::ORTHOGRAPHIC,
static_cast<float>(max_element(sim->iGetObjectCount())) * 0.015f,
2.0f, 0.0f, 0.0f);
dxapp->setBackgroundColor(DirectX::Colors::Black);
Win32App winApp(500, 500);
winApp.setWinName(L"PBD Energy Projection");
winApp.setWinOffset(400, 200);
winApp.initialize(hInstance, dxapp, sim);
return winApp.run();
} | 28.0625 | 90 | 0.694878 | jklee95 |
63231d3bb143da4450b56d8fa900de2afac244f3 | 4,080 | cc | C++ | tests/libport/containers.cc | jcbaillie/libport | b8192b177ae0ae63979c17ea7685a8617b03e11f | [
"BSD-3-Clause"
] | 3 | 2015-05-29T09:35:32.000Z | 2021-02-23T07:45:01.000Z | tests/libport/containers.cc | jcbaillie/libport | b8192b177ae0ae63979c17ea7685a8617b03e11f | [
"BSD-3-Clause"
] | 2 | 2019-01-31T10:23:47.000Z | 2019-01-31T10:35:06.000Z | tests/libport/containers.cc | jcbaillie/libport | b8192b177ae0ae63979c17ea7685a8617b03e11f | [
"BSD-3-Clause"
] | 7 | 2015-01-29T20:49:06.000Z | 2019-04-24T04:06:22.000Z | /*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/containers.hh>
#include <libport/unit-test.hh>
using libport::test_suite;
static void
check_operator_lt_lt()
{
typedef std::vector<std::string> string_list;
string_list s1, s2;
s1 << "a" << "b";
BOOST_CHECK_EQUAL(s1.size(), 2u);
BOOST_CHECK_EQUAL(s1[0], "a");
BOOST_CHECK_EQUAL(s1[1], "b");
s2 << "c" << "d";
s1 << s2;
BOOST_CHECK_EQUAL(s1.size(), 4u);
BOOST_CHECK_EQUAL(s1[2], "c");
BOOST_CHECK_EQUAL(s1[3], "d");
typedef std::set<std::string> string_set;
string_set s3;
s3 << s1;
BOOST_CHECK_EQUAL(s3.size(), 4u);
s3 << s1;
BOOST_CHECK_EQUAL(s3.size(), 4u);
typedef boost::unordered_set<std::string> boost_string_set;
boost_string_set s4;
BOOST_CHECK_EQUAL(s4.size(), 0u);
s4 << "a";
s4 << "b";
BOOST_CHECK_EQUAL(s4.size(), 2u);
s4 << "b";
BOOST_CHECK_EQUAL(s4.size(), 2u);
}
class logging_string: public std::string
{
public:
logging_string(const char* v)
: std::string(v)
{}
};
unsigned logging_string_comparisons = 0;
bool operator == (const logging_string& lhs, const logging_string& rhs)
{
++logging_string_comparisons;
return std::operator == (reinterpret_cast<const std::string&>(lhs),
reinterpret_cast<const std::string&>(rhs));
}
static void check_find_vector()
{
typedef std::vector<logging_string> container_type;
logging_string a("a");
logging_string b("b");
logging_string c("c");
container_type cont;
cont << a << b << c;
BOOST_CHECK_EQUAL(cont.size(), 3u);
logging_string_comparisons = 0;
container_type::iterator it(libport::find(cont, logging_string("b")));
BOOST_CHECK(it == cont.begin() + 1);
BOOST_CHECK_EQUAL(logging_string_comparisons, 2u);
logging_string_comparisons = 0;
container_type::iterator end(libport::find(cont, logging_string("d")));
BOOST_CHECK(end == cont.end());
BOOST_CHECK_EQUAL(logging_string_comparisons, 3u);
}
static void check_find_unordered_set()
{
typedef boost::unordered_set<logging_string> container_type;
logging_string a("a");
logging_string b("b");
logging_string c("c");
container_type cont;
cont << a << b << c;
BOOST_CHECK_EQUAL(cont.size(), 3u);
logging_string_comparisons = 0;
container_type::iterator it(libport::find(cont, logging_string("b")));
BOOST_CHECK(it != cont.end());
BOOST_CHECK_EQUAL(logging_string_comparisons, 1u);
logging_string_comparisons = 0;
container_type::iterator end(libport::find(cont, logging_string("d")));
BOOST_CHECK(end == cont.end());
BOOST_CHECK_EQUAL(logging_string_comparisons, 0u);
}
static void check_find_std_set()
{
typedef std::set<logging_string> container_type;
logging_string a("a");
logging_string b("b");
logging_string c("c");
logging_string d("d");
logging_string e("e");
container_type cont;
cont << a << b << c << d << e;
BOOST_CHECK_EQUAL(cont.size(), 5u);
logging_string_comparisons = 0;
container_type::iterator it(libport::find(cont, logging_string("e")));
BOOST_CHECK(it != cont.end());
BOOST_CHECK_LT(logging_string_comparisons, 5u);
logging_string_comparisons = 0;
container_type::iterator end(libport::find(cont, logging_string("f")));
BOOST_CHECK(end == cont.end());
BOOST_CHECK_LT(logging_string_comparisons, 5u);
}
static void check_strings()
{
std::string digits = "0123456789";
BOOST_CHECK(libport::has(digits, '0'));
BOOST_CHECK(!libport::has(digits, 'a'));
}
test_suite*
init_test_suite()
{
test_suite* suite = BOOST_TEST_SUITE("libport.containers test suite");
suite->add(BOOST_TEST_CASE(check_operator_lt_lt));
suite->add(BOOST_TEST_CASE(check_find_vector));
suite->add(BOOST_TEST_CASE(check_find_unordered_set));
suite->add(BOOST_TEST_CASE(check_find_std_set));
suite->add(BOOST_TEST_CASE(check_strings));
return suite;
}
| 27.2 | 73 | 0.706127 | jcbaillie |
632435e2806fcbfa4fc92254289c0fee4a01762b | 5,269 | hpp | C++ | include/base_pxfoundations/foundation/PsSortInternals.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | include/base_pxfoundations/foundation/PsSortInternals.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | include/base_pxfoundations/foundation/PsSortInternals.hpp | DeanoC/base_pxfoundations | 8150e24a606b184781bf1552e09f17c03e67e501 | [
"BSD-3-Clause"
] | null | null | null | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PSFOUNDATION_PSSORTINTERNALS_H
#define PSFOUNDATION_PSSORTINTERNALS_H
/** \addtogroup foundation
@{
*/
#include "foundation/PxAssert.h"
#include "foundation/PxIntrinsics.h"
#include "PsBasicTemplates.h"
#include "PsUserAllocated.h"
namespace physx {
namespace shdfnd {
namespace internal {
template<class T, class Predicate>
PX_INLINE void median3(T *elements, int32_t first, int32_t last, Predicate &compare) {
/*
This creates sentinels because we know there is an element at the start minimum(or equal)
than the pivot and an element at the end greater(or equal) than the pivot. Plus the
median of 3 reduces the chance of degenerate behavour.
*/
int32_t mid = (first + last) / 2;
if (compare(elements[mid], elements[first]))
swap(elements[first], elements[mid]);
if (compare(elements[last], elements[first]))
swap(elements[first], elements[last]);
if (compare(elements[last], elements[mid]))
swap(elements[mid], elements[last]);
// keep the pivot at last-1
swap(elements[mid], elements[last - 1]);
}
template<class T, class Predicate>
PX_INLINE int32_t
partition(T
* elements,
int32_t first, int32_t
last,
Predicate &compare
) {
median3(elements, first, last, compare
);
/*
WARNING: using the line:
T partValue = elements[last-1];
and changing the scan loops to:
while(comparator.greater(partValue, elements[++i]));
while(comparator.greater(elements[--j], partValue);
triggers a compiler optimizer bug on xenon where it stores a double to the stack for partValue
then loads it as a single...:-(
*/
int32_t i = first; // we know first is less than pivot(but i gets pre incremented)
int32_t j = last - 1; // pivot is in last-1 (but j gets pre decremented)
for(;;) {
while(
compare(elements[++i], elements[last - 1]
));
while(
compare(elements[last - 1], elements[--j]
));
if(i >= j)
break;
PX_ASSERT(i
<=
last &&j
>= first);
swap(elements[i], elements[j]
);
}
// put the pivot in place
PX_ASSERT(i
<=
last &&first
<= (last - 1));
swap(elements[i], elements[last - 1]
);
return
i;
}
template<class T, class Predicate>
PX_INLINE void smallSort(T *elements, int32_t first, int32_t last, Predicate &compare) {
// selection sort - could reduce to fsel on 360 with floats.
for (int32_t i = first; i < last; i++) {
int32_t m = i;
for (int32_t j = i + 1; j <= last; j++)
if (compare(elements[j], elements[m]))
m = j;
if (m != i)
swap(elements[m], elements[i]);
}
}
template<class Allocator>
class Stack {
Allocator mAllocator;
uint32_t mSize, mCapacity;
int32_t *mMemory;
bool mRealloc;
public:
Stack(int32_t *memory, uint32_t capacity, const Allocator &inAllocator)
: mAllocator(inAllocator), mSize(0), mCapacity(capacity), mMemory(memory), mRealloc(false) {
}
~Stack() {
if (mRealloc)
mAllocator.deallocate(mMemory);
}
void grow() {
mCapacity *= 2;
int32_t *newMem =
reinterpret_cast<int32_t *>(mAllocator.allocate(sizeof(int32_t) * mCapacity, __FILE__, __LINE__));
intrinsics::memCopy(newMem, mMemory, mSize * sizeof(int32_t));
if (mRealloc)
mAllocator.deallocate(mMemory);
mRealloc = true;
mMemory = newMem;
}
PX_INLINE void push(int32_t start, int32_t end) {
if (mSize >= mCapacity - 1)
grow();
mMemory[mSize++] = start;
mMemory[mSize++] = end;
}
PX_INLINE void pop(int32_t &start, int32_t &end) {
PX_ASSERT(!empty());
end = mMemory[--mSize];
start = mMemory[--mSize];
}
PX_INLINE bool empty() {
return mSize == 0;
}
};
} // namespace internal
} // namespace shdfnd
} // namespace physx
#endif // #ifndef PSFOUNDATION_PSSORTINTERNALS_H
| 27.442708 | 102 | 0.719681 | DeanoC |
632a1a8bdb863989ef53c67fc4cbb70db70f285c | 928 | cc | C++ | third_party/NNPACK/test/max-pooling-output/vgg-a.cc | gautamkmr/caffe2 | cde7f21d1e34ec714bc08dbfab945a1ad30e92ff | [
"MIT"
] | 1,695 | 2016-03-24T18:37:49.000Z | 2022-03-21T19:18:13.000Z | third_party/NNPACK/test/max-pooling-output/vgg-a.cc | gautamkmr/caffe2 | cde7f21d1e34ec714bc08dbfab945a1ad30e92ff | [
"MIT"
] | 200 | 2016-03-24T18:50:49.000Z | 2022-01-08T21:15:43.000Z | third_party/NNPACK/test/max-pooling-output/vgg-a.cc | gautamkmr/caffe2 | cde7f21d1e34ec714bc08dbfab945a1ad30e92ff | [
"MIT"
] | 355 | 2016-03-24T19:09:37.000Z | 2022-02-14T09:58:32.000Z | #include <gtest/gtest.h>
#include <nnpack.h>
#include <testers/pooling.h>
#include <models/vgg-a.h>
/*
* VGG model A pool1 layer
*/
TEST(MaxPooling2x2, pool1) {
VGG_A::pool1()
.batchSize(64)
.testOutput();
}
/*
* VGG model A pool2 layer
*/
TEST(MaxPooling2x2, pool2) {
VGG_A::pool2()
.batchSize(64)
.testOutput();
}
/*
* VGG model A pool3 layer
*/
TEST(MaxPooling2x2, pool3) {
VGG_A::pool3()
.batchSize(64)
.testOutput();
}
/*
* VGG model A pool4 layer
*/
TEST(MaxPooling2x2, pool4) {
VGG_A::pool4()
.batchSize(64)
.testOutput();
}
/*
* VGG model A pool5 layer
*/
TEST(MaxPooling2x2, pool5) {
VGG_A::pool5()
.batchSize(64)
.testOutput();
}
int main(int argc, char* argv[]) {
const enum nnp_status init_status = nnp_initialize();
assert(init_status == nnp_status_success);
setenv("TERM", "xterm-256color", 0);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 14.276923 | 54 | 0.65194 | gautamkmr |
632a58b26141bab2df1347a041a015b87ccb8009 | 3,764 | cpp | C++ | tests/libcxx/ctor.brace-init.cpp | clayne/tight_pair | 1ba432f8130ee24698486569bb66f31b04d448e5 | [
"MIT"
] | 20 | 2017-10-19T23:30:52.000Z | 2021-12-23T06:00:21.000Z | tests/libcxx/ctor.brace-init.cpp | clayne/tight_pair | 1ba432f8130ee24698486569bb66f31b04d448e5 | [
"MIT"
] | 15 | 2018-12-05T03:46:53.000Z | 2021-09-11T11:36:29.000Z | tests/libcxx/ctor.brace-init.cpp | clayne/tight_pair | 1ba432f8130ee24698486569bb66f31b04d448e5 | [
"MIT"
] | 4 | 2018-12-06T02:33:00.000Z | 2020-08-01T05:35:34.000Z | /*
* Copyright (c) 2021 Morwenn
* SPDX-License-Identifier: MIT
*/
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <catch2/catch.hpp>
#include <tight_pair.h>
namespace
{
struct ExplicitT
{
constexpr explicit ExplicitT(int x): value(x) {}
constexpr explicit ExplicitT(ExplicitT const& o): value(o.value) {}
int value;
};
struct ImplicitT
{
constexpr ImplicitT(int x): value(x) {}
constexpr ImplicitT(ImplicitT const& o): value(o.value) {}
int value;
};
template<typename T, typename=decltype(cruft::tight_pair<T, T>({}, {}))>
constexpr bool can_construct_with_brace_init(int) { return true; }
template<typename T>
constexpr bool can_construct_with_brace_init(...) { return false; }
template<typename T, typename=decltype(cruft::tight_pair(T{}, {}))>
constexpr bool can_construct_with_ctad_brace_init(int) { return true; }
template<typename T>
constexpr bool can_construct_with_ctad_brace_init(...) { return false; }
struct BraceInit { BraceInit() = default; };
struct NoBraceInit { NoBraceInit(int); };
struct ExplicitBraceInit { explicit ExplicitBraceInit() = default; };
constexpr int explicit_vs_implicit_brace_init(cruft::tight_pair<ExplicitBraceInit, ExplicitBraceInit>) { return 1; }
constexpr int explicit_vs_implicit_brace_init(cruft::tight_pair<BraceInit, BraceInit>) { return 2; }
constexpr bool test()
{
using cruft::get;
// Explicit constructor
{
constexpr cruft::tight_pair<ExplicitT, BraceInit> p1(ExplicitT{42}, {});
static_assert(get<0>(p1).value == 42);
constexpr cruft::tight_pair<ExplicitT, BraceInit> p2{ExplicitT{42}, {}};
static_assert(get<0>(p2).value == 42);
}
{
constexpr cruft::tight_pair<BraceInit, ExplicitT> p1({}, ExplicitT{42});
static_assert(get<1>(p1).value == 42);
constexpr cruft::tight_pair<BraceInit, ExplicitT> p2{{}, ExplicitT{42}};
static_assert(get<1>(p2).value == 42);
}
{
cruft::tight_pair<BraceInit, BraceInit> p{{}, {}};
(void)p;
}
// Implicit constructor
{
constexpr cruft::tight_pair<ImplicitT, BraceInit> p = {42, {}};
static_assert(get<0>(p).value == 42);
}
{
constexpr cruft::tight_pair<BraceInit, ImplicitT> p = {{}, 42};
static_assert(get<1>(p).value == 42);
}
{
cruft::tight_pair<BraceInit, BraceInit> p = {{}, {}};
(void)p;
}
// SFINAE-friendliness of some invalid cases
{
static_assert( can_construct_with_brace_init<BraceInit>(0));
static_assert(not can_construct_with_brace_init<NoBraceInit>(0));
// CTAD with {} should never work, since we can't possibly deduce the types
static_assert(not can_construct_with_ctad_brace_init<BraceInit>(0));
static_assert(not can_construct_with_ctad_brace_init<int>(0));
}
#ifndef __GNUC__
// Make sure there is no ambiguity between the explicit and the non-explicit constructors
{
static_assert(explicit_vs_implicit_brace_init({{}, {}}) == 2);
}
#endif
return true;
}
}
TEST_CASE( "test constructor brace init" )
{
static_assert(test());
}
| 33.309735 | 120 | 0.593252 | clayne |
632adab311863609d20723efe439dc8030fa0e2e | 27,707 | cc | C++ | chrome/renderer/render_thread.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/renderer/render_thread.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/renderer/render_thread.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/render_thread.h"
#include <v8.h>
#include <algorithm>
#include <map>
#include <vector>
#if defined(USE_SYSTEM_SQLITE)
#include <sqlite3.h>
#else
#include "third_party/sqlite/preprocessed/sqlite3.h"
#endif
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/nullable_string16.h"
#include "base/process_util.h"
#include "base/shared_memory.h"
#include "base/stats_table.h"
#include "base/string_util.h"
#include "base/thread_local.h"
#include "chrome/common/appcache/appcache_dispatcher.h"
#include "chrome/common/child_process_logging.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/db_message_filter.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/common/url_constants.h"
#include "chrome/plugin/npobject_util.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#endif
#include "chrome/renderer/devtools_agent_filter.h"
#include "chrome/renderer/extension_groups.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/extension_process_bindings.h"
#include "chrome/renderer/extensions/js_only_v8_extensions.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/renderer/external_extension.h"
#include "chrome/renderer/loadtimes_extension_bindings.h"
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/render_view_visitor.h"
#include "chrome/renderer/renderer_webkitclient_impl.h"
#include "chrome/renderer/renderer_web_database_observer.h"
#include "chrome/renderer/spellchecker/spellcheck.h"
#include "chrome/renderer/user_script_slave.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_platform_file.h"
#include "third_party/tcmalloc/chromium/src/google/malloc_extension.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCache.h"
#include "third_party/WebKit/WebKit/chromium/public/WebColor.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCrossOriginPreflightResultCache.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFontCache.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/WebKit/chromium/public/WebStorageEventDispatcher.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/extensions/v8/benchmarking_extension.h"
#include "webkit/extensions/v8/gears_extension.h"
#include "webkit/extensions/v8/interval_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#if defined(OS_MACOSX)
#include "chrome/app/breakpad_mac.h"
#endif
using WebKit::WebCache;
using WebKit::WebCrossOriginPreflightResultCache;
using WebKit::WebFontCache;
using WebKit::WebRuntimeFeatures;
using WebKit::WebSecurityPolicy;
using WebKit::WebScriptController;
using WebKit::WebString;
using WebKit::WebStorageEventDispatcher;
using WebKit::WebView;
namespace {
static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;
static const double kInitialIdleHandlerDelayS = 1.0 /* seconds */;
static const double kInitialExtensionIdleHandlerDelayS = 5.0 /* seconds */;
static const int64 kMaxExtensionIdleHandlerDelayS = 5*60 /* seconds */;
static base::LazyInstance<base::ThreadLocalPointer<RenderThread> > lazy_tls(
base::LINKER_INITIALIZED);
#if defined(OS_POSIX)
class SuicideOnChannelErrorFilter : public IPC::ChannelProxy::MessageFilter {
void OnChannelError() {
// On POSIX, at least, one can install an unload handler which loops
// forever and leave behind a renderer process which eats 100% CPU forever.
//
// This is because the terminate signals (ViewMsg_ShouldClose and the error
// from the IPC channel) are routed to the main message loop but never
// processed (because that message loop is stuck in V8).
//
// One could make the browser SIGKILL the renderers, but that leaves open a
// large window where a browser failure (or a user, manually terminating
// the browser because "it's stuck") will leave behind a process eating all
// the CPU.
//
// So, we install a filter on the channel so that we can process this event
// here and kill the process.
#if defined(OS_MACOSX)
// TODO(viettrungluu): crbug.com/28547: The following is needed, as a
// stopgap, to avoid leaking due to not releasing Breakpad properly.
// TODO(viettrungluu): Investigate why this is being called.
if (IsCrashReporterEnabled()) {
LOG(INFO) << "Cleaning up Breakpad.";
DestructCrashReporter();
} else {
LOG(INFO) << "Breakpad not enabled; no clean-up needed.";
}
#endif // OS_MACOSX
_exit(0);
}
};
#endif
class RenderViewZoomer : public RenderViewVisitor {
public:
RenderViewZoomer(const std::string& host, int zoom_level)
: host_(host),
zoom_level_(zoom_level) {
}
virtual bool Visit(RenderView* render_view) {
WebView* webview = render_view->webview(); // Guaranteed non-NULL.
if (GURL(webview->mainFrame()->url()).host() == host_)
webview->setZoomLevel(false, zoom_level_);
return true;
}
private:
std::string host_;
int zoom_level_;
DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer);
};
} // namespace
// When we run plugins in process, we actually run them on the render thread,
// which means that we need to make the render thread pump UI events.
RenderThread::RenderThread() {
Init();
}
RenderThread::RenderThread(const std::string& channel_name)
: ChildThread(channel_name) {
Init();
}
void RenderThread::Init() {
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
// If you are running plugins in this thread you need COM active but in
// the normal case you don't.
if (RenderProcess::InProcessPlugins())
CoInitialize(0);
#endif
std::string type_str = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessType);
is_extension_process_ = type_str == switches::kExtensionProcess;
plugin_refresh_allowed_ = true;
cache_stats_task_pending_ = false;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_s_ = is_extension_process_ ?
kInitialExtensionIdleHandlerDelayS : kInitialIdleHandlerDelayS;
task_factory_.reset(new ScopedRunnableMethodFactory<RenderThread>(this));
visited_link_slave_.reset(new VisitedLinkSlave());
user_script_slave_.reset(new UserScriptSlave());
dns_master_.reset(new RenderDnsMaster());
histogram_snapshots_.reset(new RendererHistogramSnapshots());
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
devtools_agent_filter_ = new DevToolsAgentFilter();
AddFilter(devtools_agent_filter_.get());
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
spellchecker_.reset(new SpellCheck());
#if defined(OS_POSIX)
suicide_on_channel_error_filter_ = new SuicideOnChannelErrorFilter;
AddFilter(suicide_on_channel_error_filter_.get());
#endif
}
RenderThread::~RenderThread() {
// Shutdown in reverse of the initialization order.
RemoveFilter(devtools_agent_filter_.get());
RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
if (webkit_client_.get())
WebKit::shutdown();
lazy_tls.Pointer()->Set(NULL);
// TODO(port)
#if defined(OS_WIN)
// Clean up plugin channels before this thread goes away.
PluginChannelBase::CleanupChannels();
// Don't call COM if the renderer is in the sandbox.
if (RenderProcess::InProcessPlugins())
CoUninitialize();
#endif
}
RenderThread* RenderThread::current() {
return lazy_tls.Pointer()->Get();
}
void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
channel()->AddFilter(filter);
}
void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
channel()->RemoveFilter(filter);
}
void RenderThread::WidgetHidden() {
DCHECK(hidden_widget_count_ < widget_count_);
hidden_widget_count_++;
if (!is_extension_process() &&
widget_count_ && hidden_widget_count_ == widget_count_)
ScheduleIdleHandler(kInitialIdleHandlerDelayS);
}
void RenderThread::WidgetRestored() {
DCHECK(hidden_widget_count_ > 0);
hidden_widget_count_--;
if (!is_extension_process())
idle_timer_.Stop();
}
void RenderThread::Resolve(const char* name, size_t length) {
return dns_master_->Resolve(name, length);
}
void RenderThread::SendHistograms(int sequence_number) {
return histogram_snapshots_->SendHistograms(sequence_number);
}
void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
visited_link_slave_->Init(table);
}
void RenderThread::OnAddVisitedLinks(
const VisitedLinkSlave::Fingerprints& fingerprints) {
for (size_t i = 0; i < fingerprints.size(); ++i)
WebView::updateVisitedLinkState(fingerprints[i]);
}
void RenderThread::OnResetVisitedLinks() {
WebView::resetVisitedLinkState();
}
void RenderThread::OnSetZoomLevelForCurrentHost(const std::string& host,
int zoom_level) {
RenderViewZoomer zoomer(host, zoom_level);
RenderView::ForEach(&zoomer);
}
void RenderThread::OnUpdateUserScripts(
base::SharedMemoryHandle scripts) {
DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
user_script_slave_->UpdateScripts(scripts);
UpdateActiveExtensions();
}
void RenderThread::OnSetExtensionFunctionNames(
const std::vector<std::string>& names) {
ExtensionProcessBindings::SetFunctionNames(names);
}
void RenderThread::OnPageActionsUpdated(
const std::string& extension_id,
const std::vector<std::string>& page_actions) {
ExtensionProcessBindings::SetPageActions(extension_id, page_actions);
}
void RenderThread::OnExtensionSetAPIPermissions(
const std::string& extension_id,
const std::vector<std::string>& permissions) {
ExtensionProcessBindings::SetAPIPermissions(extension_id, permissions);
// This is called when starting a new extension page, so start the idle
// handler ticking.
ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayS);
UpdateActiveExtensions();
}
void RenderThread::OnExtensionSetHostPermissions(
const GURL& extension_url, const std::vector<URLPattern>& permissions) {
ExtensionProcessBindings::SetHostPermissions(extension_url, permissions);
}
void RenderThread::OnDOMStorageEvent(
const ViewMsg_DOMStorageEvent_Params& params) {
if (!dom_storage_event_dispatcher_.get())
dom_storage_event_dispatcher_.reset(WebStorageEventDispatcher::create());
dom_storage_event_dispatcher_->dispatchStorageEvent(params.key_,
params.old_value_, params.new_value_, params.origin_, params.url_,
params.storage_type_ == DOM_STORAGE_LOCAL);
}
void RenderThread::OnControlMessageReceived(const IPC::Message& msg) {
// App cache messages are handled by a delegate.
if (appcache_dispatcher_->OnMessageReceived(msg))
return;
IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_Add, OnAddVisitedLinks)
IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_Reset, OnResetVisitedLinks)
IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentHost,
OnSetZoomLevelForCurrentHost)
IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
IPC_MESSAGE_HANDLER(ViewMsg_SetCSSColors, OnSetCSSColors)
// TODO(port): removed from render_messages_internal.h;
// is there a new non-windows message I should add here?
IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ViewMsg_GetRendererHistograms,
OnGetRendererHistograms)
#if defined(USE_TCMALLOC)
IPC_MESSAGE_HANDLER(ViewMsg_GetRendererTcmalloc,
OnGetRendererTcmalloc)
#endif
IPC_MESSAGE_HANDLER(ViewMsg_GetV8HeapStats, OnGetV8HeapStats)
IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_UpdatedScripts,
OnUpdateUserScripts)
// TODO(rafaelw): create an ExtensionDispatcher that handles extension
// messages seperates their handling from the RenderThread.
IPC_MESSAGE_HANDLER(ViewMsg_ExtensionMessageInvoke,
OnExtensionMessageInvoke)
IPC_MESSAGE_HANDLER(ViewMsg_Extension_SetFunctionNames,
OnSetExtensionFunctionNames)
IPC_MESSAGE_HANDLER(ViewMsg_PurgeMemory, OnPurgeMemory)
IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache,
OnPurgePluginListCache)
IPC_MESSAGE_HANDLER(ViewMsg_Extension_UpdatePageActions,
OnPageActionsUpdated)
IPC_MESSAGE_HANDLER(ViewMsg_Extension_SetAPIPermissions,
OnExtensionSetAPIPermissions)
IPC_MESSAGE_HANDLER(ViewMsg_Extension_SetHostPermissions,
OnExtensionSetHostPermissions)
IPC_MESSAGE_HANDLER(ViewMsg_DOMStorageEvent,
OnDOMStorageEvent)
#if defined(IPC_MESSAGE_LOG_ENABLED)
IPC_MESSAGE_HANDLER(ViewMsg_SetIPCLoggingEnabled,
OnSetIPCLoggingEnabled)
#endif
IPC_MESSAGE_HANDLER(ViewMsg_SpellChecker_Init,
OnInitSpellChecker)
IPC_MESSAGE_HANDLER(ViewMsg_SpellChecker_WordAdded,
OnSpellCheckWordAdded)
IPC_MESSAGE_HANDLER(ViewMsg_SpellChecker_EnableAutoSpellCorrect,
OnSpellCheckEnableAutoSpellCorrect)
IPC_END_MESSAGE_MAP()
}
void RenderThread::OnSetNextPageID(int32 next_page_id) {
// This should only be called at process initialization time, so we shouldn't
// have to worry about thread-safety.
RenderView::SetNextPageID(next_page_id);
}
// Called when to register CSS Color name->system color mappings.
// We update the colors one by one and then tell WebKit to refresh all render
// views.
void RenderThread::OnSetCSSColors(
const std::vector<CSSColors::CSSColorMapping>& colors) {
EnsureWebKitInitialized();
size_t num_colors = colors.size();
scoped_array<WebKit::WebColorName> color_names(
new WebKit::WebColorName[num_colors]);
scoped_array<WebKit::WebColor> web_colors(new WebKit::WebColor[num_colors]);
size_t i = 0;
for (std::vector<CSSColors::CSSColorMapping>::const_iterator it =
colors.begin();
it != colors.end();
++it, ++i) {
color_names[i] = it->first;
web_colors[i] = it->second;
}
WebKit::setNamedColors(color_names.get(), web_colors.get(), num_colors);
}
void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
const RendererPreferences& renderer_prefs,
const WebPreferences& webkit_prefs,
int32 view_id) {
EnsureWebKitInitialized();
// When bringing in render_view, also bring in webkit's glue and jsbindings.
RenderView::Create(
this, parent_hwnd, MSG_ROUTING_NONE, renderer_prefs,
webkit_prefs, new SharedRenderViewCounter(0), view_id);
}
void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
size_t max_dead_capacity,
size_t capacity) {
EnsureWebKitInitialized();
WebCache::setCapacities(
min_dead_capacity, max_dead_capacity, capacity);
}
void RenderThread::OnGetCacheResourceStats() {
EnsureWebKitInitialized();
WebCache::ResourceTypeStats stats;
WebCache::getResourceTypeStats(&stats);
Send(new ViewHostMsg_ResourceTypeStats(stats));
}
void RenderThread::OnGetRendererHistograms(int sequence_number) {
SendHistograms(sequence_number);
}
#if defined(USE_TCMALLOC)
void RenderThread::OnGetRendererTcmalloc() {
std::string result;
char buffer[1024 * 32];
base::ProcessId pid = base::GetCurrentProcId();
MallocExtension::instance()->GetStats(buffer, sizeof(buffer));
result.append(buffer);
Send(new ViewHostMsg_RendererTcmalloc(pid, result));
}
#endif
void RenderThread::OnGetV8HeapStats() {
v8::HeapStatistics heap_stats;
v8::V8::GetHeapStatistics(&heap_stats);
Send(new ViewHostMsg_V8HeapStats(heap_stats.total_heap_size(),
heap_stats.used_heap_size()));
}
void RenderThread::InformHostOfCacheStats() {
EnsureWebKitInitialized();
WebCache::UsageStats stats;
WebCache::getUsageStats(&stats);
Send(new ViewHostMsg_UpdatedCacheStats(stats));
cache_stats_task_pending_ = false;
}
void RenderThread::InformHostOfCacheStatsLater() {
// Rate limit informing the host of our cache stats.
if (cache_stats_task_pending_)
return;
cache_stats_task_pending_ = true;
MessageLoop::current()->PostDelayedTask(FROM_HERE,
task_factory_->NewRunnableMethod(
&RenderThread::InformHostOfCacheStats),
kCacheStatsDelayMS);
}
void RenderThread::CloseIdleConnections() {
Send(new ViewHostMsg_CloseIdleConnections());
}
void RenderThread::SetCacheMode(bool enabled) {
Send(new ViewHostMsg_SetCacheMode(enabled));
}
void RenderThread::UpdateActiveExtensions() {
// In single-process mode, the browser process reports the active extensions.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess))
return;
std::set<std::string> active_extensions;
user_script_slave_->GetActiveExtensions(&active_extensions);
ExtensionProcessBindings::GetActiveExtensions(&active_extensions);
child_process_logging::SetActiveExtensions(active_extensions);
}
static void* CreateHistogram(
const char *name, int min, int max, size_t buckets) {
if (min <= 0)
min = 1;
scoped_refptr<Histogram> histogram = Histogram::FactoryGet(
name, min, max, buckets, Histogram::kUmaTargetedHistogramFlag);
// We'll end up leaking these histograms, unless there is some code hiding in
// there to do the dec-ref.
// TODO(jar): Handle reference counting in webkit glue.
histogram->AddRef();
return histogram.get();
}
static void AddHistogramSample(void* hist, int sample) {
Histogram* histogram = static_cast<Histogram *>(hist);
histogram->Add(sample);
}
void RenderThread::EnsureWebKitInitialized() {
if (webkit_client_.get())
return;
// For extensions, we want to ensure we call the IdleHandler every so often,
// even if the extension keeps up activity.
if (is_extension_process()) {
forced_idle_timer_.Start(
base::TimeDelta::FromSeconds(kMaxExtensionIdleHandlerDelayS),
this, &RenderThread::IdleHandler);
}
v8::V8::SetCounterFunction(StatsTable::FindLocation);
v8::V8::SetCreateHistogramFunction(CreateHistogram);
v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
webkit_client_.reset(new RendererWebKitClientImpl);
WebKit::initialize(webkit_client_.get());
WebScriptController::enableV8SingleThreadMode();
// chrome: pages should not be accessible by normal content, and should
// also be unable to script anything but themselves (to help limit the damage
// that a corrupt chrome: page could cause).
WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme));
WebSecurityPolicy::registerURLSchemeAsLocal(chrome_ui_scheme);
WebSecurityPolicy::registerURLSchemeAsNoAccess(chrome_ui_scheme);
// print: pages should be not accessible by normal context.
WebString print_ui_scheme(ASCIIToUTF16(chrome::kPrintScheme));
WebSecurityPolicy::registerURLSchemeAsLocal(print_ui_scheme);
WebSecurityPolicy::registerURLSchemeAsNoAccess(print_ui_scheme);
#if defined(OS_WIN)
// We don't yet support Gears on non-Windows, so don't tell pages that we do.
WebScriptController::registerExtension(extensions_v8::GearsExtension::Get());
#endif
WebScriptController::registerExtension(
extensions_v8::IntervalExtension::Get());
WebScriptController::registerExtension(
extensions_v8::LoadTimesExtension::Get());
WebScriptController::registerExtension(
extensions_v8::ExternalExtension::Get());
const WebKit::WebString kExtensionScheme =
WebKit::WebString::fromUTF8(chrome::kExtensionScheme);
WebScriptController::registerExtension(
ExtensionProcessBindings::Get(), kExtensionScheme);
WebScriptController::registerExtension(
BaseJsV8Extension::Get(), EXTENSION_GROUP_CONTENT_SCRIPTS);
WebScriptController::registerExtension(
BaseJsV8Extension::Get(), kExtensionScheme);
WebScriptController::registerExtension(
JsonSchemaJsV8Extension::Get(), EXTENSION_GROUP_CONTENT_SCRIPTS);
WebScriptController::registerExtension(JsonSchemaJsV8Extension::Get(),
kExtensionScheme);
WebScriptController::registerExtension(
EventBindings::Get(), EXTENSION_GROUP_CONTENT_SCRIPTS);
WebScriptController::registerExtension(EventBindings::Get(),
kExtensionScheme);
WebScriptController::registerExtension(
RendererExtensionBindings::Get(), EXTENSION_GROUP_CONTENT_SCRIPTS);
WebScriptController::registerExtension(
RendererExtensionBindings::Get(), kExtensionScheme);
WebScriptController::registerExtension(
ExtensionApiTestV8Extension::Get(), kExtensionScheme);
WebScriptController::registerExtension(
ExtensionApiTestV8Extension::Get(), EXTENSION_GROUP_CONTENT_SCRIPTS);
renderer_web_database_observer_.reset(new RendererWebDatabaseObserver(this));
WebKit::WebDatabase::setObserver(renderer_web_database_observer_.get());
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableBenchmarking)) {
WebScriptController::registerExtension(
extensions_v8::BenchmarkingExtension::Get());
}
if (command_line.HasSwitch(switches::kPlaybackMode) ||
command_line.HasSwitch(switches::kRecordMode) ||
command_line.HasSwitch(switches::kNoJsRandomness)) {
WebScriptController::registerExtension(
extensions_v8::PlaybackExtension::Get());
}
WebRuntimeFeatures::enableMediaPlayer(
RenderProcess::current()->initialized_media_library());
WebRuntimeFeatures::enableSockets(
!command_line.HasSwitch(switches::kDisableWebSockets));
WebRuntimeFeatures::enableDatabase(
!command_line.HasSwitch(switches::kDisableDatabases));
WebRuntimeFeatures::enableApplicationCache(
command_line.HasSwitch(switches::kEnableApplicationCache));
#if defined(OS_WIN)
// We don't yet support notifications on non-Windows.
WebRuntimeFeatures::enableNotifications(
!command_line.HasSwitch(switches::kDisableDesktopNotifications));
#endif
WebRuntimeFeatures::enableLocalStorage(
!command_line.HasSwitch(switches::kDisableLocalStorage));
WebRuntimeFeatures::enableSessionStorage(
command_line.HasSwitch(switches::kEnableSessionStorage));
}
void RenderThread::IdleHandler() {
#if defined(OS_WIN) && defined(USE_TCMALLOC)
MallocExtension::instance()->ReleaseFreeMemory();
#endif
LOG(INFO) << "RenderThread calling v8 IdleNotification for " << this;
v8::V8::IdleNotification();
// Schedule next invocation.
// Dampen the delay using the algorithm:
// delay = delay + 1 / (delay + 2)
// Using floor(delay) has a dampening effect such as:
// 1s, 1, 1, 2, 2, 2, 2, 3, 3, ...
// Note that idle_notification_delay_in_s_ would be reset to
// kInitialIdleHandlerDelayS in RenderThread::WidgetHidden.
ScheduleIdleHandler(idle_notification_delay_in_s_ +
1.0 / (idle_notification_delay_in_s_ + 2.0));
if (is_extension_process()) {
// Dampen the forced delay as well if the extension stays idle for long
// periods of time.
int64 forced_delay_s =
std::max(static_cast<int64>(idle_notification_delay_in_s_),
kMaxExtensionIdleHandlerDelayS);
forced_idle_timer_.Stop();
forced_idle_timer_.Start(
base::TimeDelta::FromSeconds(forced_delay_s),
this, &RenderThread::IdleHandler);
}
}
void RenderThread::ScheduleIdleHandler(double initial_delay_s) {
idle_notification_delay_in_s_ = initial_delay_s;
idle_timer_.Stop();
idle_timer_.Start(
base::TimeDelta::FromSeconds(static_cast<int64>(initial_delay_s)),
this, &RenderThread::IdleHandler);
}
void RenderThread::OnExtensionMessageInvoke(const std::string& function_name,
const ListValue& args) {
RendererExtensionBindings::Invoke(function_name, args, NULL);
// Reset the idle handler each time there's any activity like event or message
// dispatch, for which Invoke is the chokepoint.
if (is_extension_process())
ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayS);
}
void RenderThread::OnPurgeMemory() {
spellchecker_.reset(new SpellCheck());
EnsureWebKitInitialized();
// Clear the object cache (as much as possible; some live objects cannot be
// freed).
WebCache::clear();
// Clear the font/glyph cache.
WebFontCache::clear();
// Clear the Cross-Origin Preflight cache.
WebCrossOriginPreflightResultCache::clear();
// Release all freeable memory from the SQLite process-global page cache (a
// low-level object which backs the Connection-specific page caches).
while (sqlite3_release_memory(std::numeric_limits<int>::max()) > 0) {
}
// Repeatedly call the V8 idle notification until it returns true ("nothing
// more to free"). Note that it makes more sense to do this than to implement
// a new "delete everything" pass because object references make it difficult
// to free everything possible in just one pass.
while (!v8::V8::IdleNotification()) {
}
#if defined(OS_WIN) && defined(USE_TCMALLOC)
// Tell tcmalloc to release any free pages it's still holding.
MallocExtension::instance()->ReleaseFreeMemory();
#endif
}
void RenderThread::OnPurgePluginListCache(bool reload_pages) {
EnsureWebKitInitialized();
// The call below will cause a GetPlugins call with refresh=true, but at this
// point we already know that the browser has refreshed its list, so disable
// refresh temporarily to prevent each renderer process causing the list to be
// regenerated.
plugin_refresh_allowed_ = false;
WebKit::resetPluginCache(reload_pages);
plugin_refresh_allowed_ = true;
}
void RenderThread::OnInitSpellChecker(
IPC::PlatformFileForTransit bdict_file,
const std::vector<std::string>& custom_words,
const std::string& language,
bool auto_spell_correct) {
spellchecker_->Init(IPC::PlatformFileForTransitToPlatformFile(bdict_file),
custom_words, language);
spellchecker_->EnableAutoSpellCorrect(auto_spell_correct);
}
void RenderThread::OnSpellCheckWordAdded(const std::string& word) {
spellchecker_->WordAdded(word);
}
void RenderThread::OnSpellCheckEnableAutoSpellCorrect(bool enable) {
spellchecker_->EnableAutoSpellCorrect(enable);
}
| 37.290713 | 89 | 0.751976 | rwatson |
632dce8665923163268a3209671695bfc84a2064 | 448 | cc | C++ | Semaphore.cc | mjhough/shopify-scraper | eeddd252881bd0d53eae0ab67c98d5f871f10dff | [
"MIT"
] | 2 | 2020-02-22T09:28:31.000Z | 2020-08-27T12:26:35.000Z | Semaphore.cc | mjhough/shopify-scraper | eeddd252881bd0d53eae0ab67c98d5f871f10dff | [
"MIT"
] | null | null | null | Semaphore.cc | mjhough/shopify-scraper | eeddd252881bd0d53eae0ab67c98d5f871f10dff | [
"MIT"
] | 1 | 2022-01-25T07:15:23.000Z | 2022-01-25T07:15:23.000Z | #include "Semaphore.h"
Semaphore::Semaphore(int count) {
this->count = count;
}
void Semaphore::post() {
std::unique_lock<std::mutex> lock(mtx);
count++;
cv.notify_one();
}
void Semaphore::wait() {
std::unique_lock<std::mutex> lock(mtx);
while(count == 0) {
cv.wait(lock);
}
count--;
}
bool Semaphore::try_wait() {
std::unique_lock<std::mutex> lock(mtx);
if (count) {
count--;
return true;
}
return false;
}
| 15.448276 | 41 | 0.613839 | mjhough |
63306eab4231ddadc694dd8465a9771f2e866cdf | 2,928 | cpp | C++ | Button.cpp | alejandrocoria/MinerDisplay | e333c0d352965edf0d98024db254384e1f553314 | [
"MIT"
] | null | null | null | Button.cpp | alejandrocoria/MinerDisplay | e333c0d352965edf0d98024db254384e1f553314 | [
"MIT"
] | null | null | null | Button.cpp | alejandrocoria/MinerDisplay | e333c0d352965edf0d98024db254384e1f553314 | [
"MIT"
] | null | null | null | #include "Button.h"
#include <SFML/Graphics/RenderTarget.hpp>
#include <cmath>
Button::Button(const sf::Font* font):
font(font) {
text.setCharacterSize(16);
text.setFont(*font);
}
void Button::processEvents(const sf::Event& event) {
switch (event.type) {
case sf::Event::MouseButtonPressed:
if (rectangle.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y)) {
setSate(State::Pressed);
} else {
setSate(State::Normal);
}
break;
case sf::Event::MouseButtonReleased:
if (rectangle.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y)) {
if (state == State::Pressed) {
setSate(State::Hovered);
if (callback) {
callback();
}
}
} else {
setSate(State::Normal);
}
break;
case sf::Event::MouseMoved:
if (rectangle.getGlobalBounds().contains(event.mouseMove.x, event.mouseMove.y)) {
if (state == State::Normal) {
setSate(State::Hovered);
}
} else {
if (state == State::Hovered) {
setSate(State::Normal);
}
}
break;
default:
break;
}
}
void Button::setText(const sf::String& text) {
this->text.setString(text);
dirty = true;
}
void Button::setColors(sf::Color normal, sf::Color hovered, sf::Color pressed, sf::Color text) {
this->normal = normal;
this->hovered = hovered;
this->pressed = pressed;
this->text.setFillColor(text);
updateRectangleColor();
}
void Button::setSize(sf::Vector2f size) {
this->size = size;
dirty = true;
}
void Button::setPosition(sf::Vector2f position) {
this->position = position;
dirty = true;
}
void Button::setCallback(std::function<void()> fn) {
callback = std::move(fn);
}
void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const {
if (dirty) {
dirty = false;
sf::Vector2f center = position + size / 2.f;
rectangle.setPosition(position);
rectangle.setSize(size);
text.setPosition({std::round(center.x - text.getGlobalBounds().width / 2.f), std::round(center.y - 10.f)});
}
target.draw(rectangle, states);
target.draw(text, states);
}
void Button::setSate(State newState) {
if (newState == state) {
return;
}
state = newState;
updateRectangleColor();
}
void Button::updateRectangleColor() {
if (state == State::Normal) {
rectangle.setFillColor(normal);
} else if (state == State::Hovered) {
rectangle.setFillColor(hovered);
} else if (state == State::Pressed) {
rectangle.setFillColor(pressed);
}
}
| 26.378378 | 115 | 0.557036 | alejandrocoria |
6333522daaeb66929f021a8c92aa2286f05b56a5 | 744 | cpp | C++ | July LeetCode Challenge/Day_22.cpp | mishrraG/100DaysOfCode | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 13 | 2020-08-10T14:06:37.000Z | 2020-09-24T14:21:33.000Z | July LeetCode Challenge/Day_22.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | null | null | null | July LeetCode Challenge/Day_22.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 1 | 2020-05-31T21:09:14.000Z | 2020-05-31T21:09:14.000Z | class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
if (root == NULL) {
return vector<vector<int> > ();
}
vector<vector<int> > result;
queue<TreeNode*> nodesQueue;
nodesQueue.push(root);
bool leftToRight = true;
while ( !nodesQueue.empty()) {
int size = nodesQueue.size();
vector<int> row(size);
for (int i = 0; i < size; i++) {
TreeNode* node = nodesQueue.front();
nodesQueue.pop();
int index = (leftToRight) ? i : (size - 1 - i);
row[index] = node->val;
if (node->left) {
nodesQueue.push(node->left);
}
if (node->right) {
nodesQueue.push(node->right);
}
}
leftToRight = !leftToRight;
result.push_back(row);
}
return result;
}
}; | 22.545455 | 56 | 0.596774 | mishrraG |
6333c0855bd17963f575ef2fcc52a098d99449a3 | 6,809 | cpp | C++ | interval_shim.cpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 2 | 2019-11-23T12:35:49.000Z | 2022-02-10T08:27:54.000Z | interval_shim.cpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 8 | 2019-11-15T08:13:48.000Z | 2020-04-29T00:35:42.000Z | interval_shim.cpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | null | null | null | #include "interval_shim.hpp"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#include "test_driver.h"
int main(int argc, char* argv[])
{ // parse options
char buf[100];
STRING_LITERAL_TO_STDOUT("starting main\n");
const interval_shim::interval ref_pi(M_PI, nextafter(M_PI, 4)); // CRC Handbook says floating point representation of M_PI is "low"; this brackets
INFORM(interval_shim::pi);
INFORM(ref_pi);
INFORM(interval_shim::pi.lower() == ref_pi.lower() ? "true" : "false");
INFORM(interval_shim::pi.upper() == ref_pi.upper() ? "true" : "false");
const interval_shim::interval ref_sqrt_2 = sqrt(interval_shim::interval(2));
INFORM(ref_sqrt_2);
INFORM(nextafter(ref_sqrt_2.lower(),2) == ref_sqrt_2.upper() ? "true" : "false");
INFORM(interval_shim::SQRT2.lower() == ref_sqrt_2.lower() ? "true" : "false");
INFORM(interval_shim::SQRT2.upper() == ref_sqrt_2.upper() ? "true" : "false");
INFORM(square(interval_shim::SQRT2).contains(2) ? "true" : "false");
const interval_shim::interval ref_sqrt_3 = sqrt(interval_shim::interval(3));
INFORM(ref_sqrt_3);
INFORM(nextafter(ref_sqrt_3.lower(), 3) == ref_sqrt_3.upper() ? "true" : "false");
INFORM(interval_shim::SQRT3.lower() == ref_sqrt_3.lower() ? "true" : "false");
INFORM(interval_shim::SQRT3.upper() == ref_sqrt_3.upper() ? "true" : "false");
INFORM(square(interval_shim::SQRT3).contains(3) ? "true" : "false");
constexpr const auto one_f = zaimoni::binary<float>(1);
constexpr const auto one_d = zaimoni::binary<double>(1);
constexpr const auto one_ld = zaimoni::binary<long double>(1);
INFORM("binary<float>(1)");
INFORM(one_f._x);
INFORM(one_f.sign);
INFORM(one_f.exp);
INFORM(one_f.exponent());
INFORM(one_f.mant);
INFORM(one_f.mantissa());
INFORM("binary<double>(1)");
INFORM(one_d._x);
INFORM(one_d.sign);
INFORM(one_d.exp);
INFORM(one_d.exponent());
INFORM(one_d.mant);
INFORM(one_d.mantissa());
INFORM("binary<long double>(1)");
INFORM(one_ld._x);
INFORM(one_ld.sign);
INFORM(one_ld.exp);
INFORM(one_ld.exponent());
INFORM(one_ld.mant);
INFORM(one_ld.mantissa());
constexpr const auto neg_one_f = zaimoni::binary<float>(-1);
constexpr const auto neg_one_d = zaimoni::binary<double>(-1);
constexpr const auto neg_one_ld = zaimoni::binary<long double>(-1);
INFORM("binary<float>(-1)");
INFORM(neg_one_f._x);
INFORM(neg_one_f.sign);
INFORM(neg_one_f.exp);
INFORM(neg_one_f.exponent());
INFORM(neg_one_f.mant);
INFORM(neg_one_f.mantissa());
INFORM("binary<double>(-1)");
INFORM(neg_one_d._x);
INFORM(neg_one_d.sign);
INFORM(neg_one_d.exp);
INFORM(neg_one_d.exponent());
INFORM(neg_one_d.mant);
INFORM(neg_one_d.mantissa());
INFORM("binary<long double>(-1)");
INFORM(neg_one_ld._x);
INFORM(neg_one_ld.sign);
INFORM(neg_one_ld.exp);
INFORM(neg_one_ld.exponent());
INFORM(neg_one_ld.mant);
INFORM(neg_one_ld.mantissa());
constexpr const auto inf_f = zaimoni::binary<float>(std::numeric_limits<float>::infinity());
constexpr const auto inf_d = zaimoni::binary<double>(std::numeric_limits<double>::infinity());
constexpr const auto inf_ld = zaimoni::binary<long double>(std::numeric_limits<long double>::infinity());
INFORM("binary<float>(inf)");
INFORM(inf_f._x);
INFORM(inf_f.sign);
INFORM(inf_f.exp);
INFORM(inf_f.exponent());
INFORM(inf_f.mant);
INFORM(inf_f.mantissa());
INFORM("binary<double>(inf)");
INFORM(inf_d._x);
INFORM(inf_d.sign);
INFORM(inf_d.exp);
INFORM(inf_d.exponent());
INFORM(inf_d.mant);
INFORM(inf_d.mantissa());
INFORM("binary<long double>(inf)");
INFORM(inf_ld._x);
INFORM(inf_ld.sign);
INFORM(inf_ld.exp);
INFORM(inf_ld.exponent());
INFORM(inf_ld.mant);
INFORM(inf_ld.mantissa());
// most significant bit: qNaN
constexpr const auto qnan_f = zaimoni::binary<float>(std::numeric_limits<float>::quiet_NaN());
constexpr const auto qnan_d = zaimoni::binary<double>(std::numeric_limits<double>::quiet_NaN());
constexpr const auto qnan_ld = zaimoni::binary<long double>(std::numeric_limits<long double>::quiet_NaN());
INFORM("binary<float>(qnan)");
INFORM(qnan_f._x);
INFORM(qnan_f.sign);
INFORM(qnan_f.exp);
INFORM(qnan_f.exponent());
INFORM(qnan_f.mant);
INFORM(qnan_f.mantissa());
INFORM("binary<double>(qnan)");
INFORM(qnan_d._x);
INFORM(qnan_d.sign);
INFORM(qnan_d.exp);
INFORM(qnan_d.exponent());
INFORM(qnan_d.mant);
INFORM(qnan_d.mantissa());
INFORM("binary<long double>(qnan)");
INFORM(qnan_ld._x);
INFORM(qnan_ld.sign);
INFORM(qnan_ld.exp);
INFORM(qnan_ld.exponent());
INFORM(qnan_ld.mant);
INFORM(qnan_ld.mantissa());
// least significant bit: sNaN
constexpr const auto snan_f = zaimoni::binary<float>(std::numeric_limits<float>::signaling_NaN());
constexpr const auto snan_d = zaimoni::binary<double>(std::numeric_limits<double>::signaling_NaN());
constexpr const auto snan_ld = zaimoni::binary<long double>(std::numeric_limits<long double>::signaling_NaN());
INFORM("binary<float>(snan)");
INFORM(snan_f._x);
INFORM(snan_f.sign);
INFORM(snan_f.exp);
INFORM(snan_f.exponent());
INFORM(snan_f.mant);
INFORM(snan_f.mantissa());
INFORM("binary<double>(snan)");
INFORM(snan_d._x);
INFORM(snan_d.sign);
INFORM(snan_d.exp);
INFORM(snan_d.exponent());
INFORM(snan_d.mant);
INFORM(snan_d.mantissa());
INFORM("binary<long double>(snan)");
INFORM(snan_ld._x);
INFORM(snan_ld.sign);
INFORM(snan_ld.exp);
INFORM(snan_ld.exponent());
INFORM(snan_ld.mant);
INFORM(snan_ld.mantissa());
INFORM("zaimoni::isFinite");
// constexpr const auto is_finite_constexpr = zaimoni::isFinite(one_d._x);
INC_INFORM("1:");
INC_INFORM(zaimoni::isFinite(one_f._x) ? " true" : " false");
INC_INFORM(zaimoni::isFinite(one_d._x) ? " true" : " false");
INFORM(zaimoni::isFinite(one_ld._x) ? " true" : " false");
INC_INFORM("-1:");
INC_INFORM(zaimoni::isFinite(neg_one_f._x) ? " true" : " false");
INC_INFORM(zaimoni::isFinite(neg_one_d._x) ? " true" : " false");
INFORM(zaimoni::isFinite(neg_one_ld._x) ? " true" : " false");
INC_INFORM("inf:");
INC_INFORM(zaimoni::isFinite(inf_f._x) ? " true" : " false");
INC_INFORM(zaimoni::isFinite(inf_d._x) ? " true" : " false");
INFORM(zaimoni::isFinite(inf_ld._x) ? " true" : " false");
INC_INFORM("qNaN:");
INC_INFORM(zaimoni::isFinite(qnan_f._x) ? " true" : " false");
INC_INFORM(zaimoni::isFinite(qnan_d._x) ? " true" : " false");
INFORM(zaimoni::isFinite(qnan_ld._x) ? " true" : " false");
INC_INFORM("sNaN:");
INC_INFORM(zaimoni::isFinite(snan_f._x) ? " true" : " false");
INC_INFORM(zaimoni::isFinite(snan_d._x) ? " true" : " false");
INFORM(zaimoni::isFinite(snan_ld._x) ? " true" : " false");
STRING_LITERAL_TO_STDOUT("tests finished\n");
}
| 36.026455 | 148 | 0.689382 | zaimoni |
63353bcc292e4c3ab006782fb536e8cb6f3b157f | 196,967 | cpp | C++ | source/D2Common/src/Items/Items.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | 1 | 2022-03-20T12:12:15.000Z | 2022-03-20T12:12:15.000Z | source/D2Common/src/Items/Items.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | null | null | null | source/D2Common/src/Items/Items.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | 1 | 2022-03-20T12:12:18.000Z | 2022-03-20T12:12:18.000Z | #include "D2Items.h"
#include <Units/Item.h>
#include "D2BitManip.h"
#include "D2Composit.h"
#include "D2DataTbls.h"
#include "D2Inventory.h"
#include "D2ItemMods.h"
#include "D2QuestRecord.h"
#include "D2Seed.h"
#include "D2States.h"
#include "D2StatList.h"
#include "Units/Units.h"
#include <D2CMP.h>
#include <DataTbls/MonsterIds.h>
//D2Common.0x6FD98380 (#10687)
void __stdcall ITEMS_AllocItemData(void* pMemPool, D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItem->pItemData = (D2ItemDataStrc*)FOG_AllocServerMemory(pMemPool, sizeof(D2ItemDataStrc), __FILE__, __LINE__, 0);
if (!pItem->pItemData)
{
//FOG_10024_PacketAssertion("Out of Memory in ITEMSDataInit()", __FILE__, __LINE__);
exit(-1);
}
memset(pItem->pItemData, 0x00, sizeof(D2ItemDataStrc));
pItem->pItemData->dwOwnerGUID = -1;
}
}
//D2Common.0x6FD983F0 (#10688)
void __stdcall ITEMS_FreeItemData(void* pMemPool, D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
INVENTORY_RemoveItem(pItem);
if (pItem->pItemData)
{
FOG_FreeServerMemory(pMemPool, pItem->pItemData, __FILE__, __LINE__, 0);
}
}
}
//D2Common.0x6FD98430 (#10689)
uint8_t __stdcall ITEMS_GetBodyLocation(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nBodyLoc;
}
return BODYLOC_NONE;
}
//D2Common.0x6FD98450 (#10690)
void __stdcall ITEMS_SetBodyLocation(D2UnitStrc* pItem, uint8_t nBodyLoc)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
if (pItem->pItemData)
{
pItem->pItemData->nBodyLoc = nBodyLoc;
}
}
}
//D2Common.0x6FD98470 (#10691)
D2SeedStrc* __stdcall ITEMS_GetItemSeed(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return &pItem->pItemData->pSeed;
}
return NULL;
}
//D2Common.0x6FD98490 (#10692)
void __stdcall ITEMS_InitItemSeed(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
SEED_InitSeed(&pItem->pItemData->pSeed);
}
}
//D2Common.0x6FD984B0 (#10693)
int __stdcall ITEMS_GetItemStartSeed(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwInitSeed;
}
return 0;
}
//D2Common.0x6FD984D0 (#10694)
void __stdcall ITEMS_SetItemStartSeed(D2UnitStrc* pItem, int nSeed)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->dwInitSeed = nSeed;
}
//D2Common.0x6FD98550 (#10695)
int __stdcall ITEMS_GetItemQuality(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwQualityNo;
}
return ITEMQUAL_NORMAL;
}
//D2Common.0x6FD98580 (#10696)
void __stdcall ITEMS_SetItemQuality(D2UnitStrc* pItem, int nQuality)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->dwQualityNo = nQuality;
}
}
//D2Common.0x6FD985A0 (#10699)
uint16_t __stdcall ITEMS_GetPrefixId(D2UnitStrc* pItem, int nPrefixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wMagicPrefix[nPrefixNo];
}
return 0;
}
//D2Common.0x6FD985D0 (#10700)
void __stdcall ITEMS_AssignPrefix(D2UnitStrc* pItem, uint16_t nPrefix, int nPrefixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wMagicPrefix[nPrefixNo] = nPrefix;
}
}
//D2Common.0x6FD98600 (#10697)
uint16_t __stdcall ITEMS_GetAutoAffix(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wAutoAffix;
}
return 0;
}
//D2Common.0x6FD98630 (#10698)
void __stdcall ITEMS_SetAutoAffix(D2UnitStrc* pItem, uint16_t nAffix)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wAutoAffix = nAffix;
}
}
//D2Common.0x6FD98650 (#10701)
uint16_t __stdcall ITEMS_GetSuffixId(D2UnitStrc* pItem, int nSuffixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wMagicSuffix[nSuffixNo];
}
return 0;
}
//D2Common.0x6FD98680 (#10702)
void __stdcall ITEMS_AssignSuffix(D2UnitStrc* pItem, uint16_t nSuffix, int nSuffixNo)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wMagicSuffix[nSuffixNo] = nSuffix;
}
}
//D2Common.0x6FD986B0 (#10703)
uint16_t __stdcall ITEMS_GetRarePrefixId(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wRarePrefix;
}
return 0;
}
//D2Common.0x6FD986E0 (#10704)
void __stdcall ITEMS_AssignRarePrefix(D2UnitStrc* pItem, uint16_t nPrefix)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wRarePrefix = nPrefix;
}
}
//D2Common.0x6FD98700 (#10705)
uint16_t __stdcall ITEMS_GetRareSuffixId(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->wRareSuffix;
}
return 0;
}
//D2Common.0x6FD98730 (#10706)
void __stdcall ITEMS_AssignRareSuffix(D2UnitStrc* pItem, uint16_t nSuffix)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->wRareSuffix = nSuffix;
}
}
//D2Common.0x6FD98750 (#10707)
BOOL __stdcall ITEMS_CheckItemFlag(D2UnitStrc* pItem, uint32_t dwFlag, int nLine, char* szFile)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwItemFlags & dwFlag;
}
return 0;
}
//D2Common.0x6FD98780 (#10708)
void __stdcall ITEMS_SetItemFlag(D2UnitStrc* pItem, uint32_t dwFlag, BOOL bSet)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (bSet)
{
pItem->pItemData->dwItemFlags |= dwFlag;
}
else
{
pItem->pItemData->dwItemFlags &= ~dwFlag;
}
}
}
//D2Common.0x6FD987C0 (#10709)
uint32_t __stdcall ITEMS_GetItemFlags(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwItemFlags;
}
return 0;
}
//D2Common.0x6FD987E0 (#10710)
BOOL __stdcall ITEMS_CheckItemCMDFlag(D2UnitStrc* pItem, int nFlag)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwCommandFlags & nFlag;
}
return 0;
}
//D2Common.0x6FD98810 (#10711)
void __stdcall ITEMS_SetItemCMDFlag(D2UnitStrc* pItem, int nFlag, BOOL bSet)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (bSet)
{
pItem->pItemData->dwCommandFlags |= nFlag;
}
else
{
pItem->pItemData->dwCommandFlags &= ~nFlag;
}
}
}
//D2Common.0x6FD98850 (#10712)
uint32_t __stdcall ITEMS_GetItemCMDFlags(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwCommandFlags;
}
return 0;
}
//D2Common.0x6FD98870 (#10717)
int __stdcall ITEMS_GetItemLevel(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (pItem->pItemData->dwItemLevel < 1)
{
pItem->pItemData->dwItemLevel = 1;
}
return pItem->pItemData->dwItemLevel;
}
return 1;
}
//D2Common.0x6FD988B0 (#10718)
void __stdcall ITEMS_SetItemLevel(D2UnitStrc* pItem, int nItemLevel)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
if (nItemLevel < 1)
{
nItemLevel = 1;
}
pItem->pItemData->dwItemLevel = nItemLevel;
}
}
//D2Common.0x6FD988E0 (#10719)
uint8_t __stdcall ITEMS_GetInvPage(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nInvPage;
}
return -1;
}
//D2Common.0x6FD98900 (#10720)
void __stdcall ITEMS_SetInvPage(D2UnitStrc* pItem, uint8_t nPage)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nInvPage = nPage;
}
}
//D2Common.0x6FD98920 (#10721)
uint8_t __stdcall ITEMS_GetCellOverlap(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nCellOverlap;
}
return -1;
}
//D2Common.0x6FD98940 (#10722)
void __stdcall ITEMS_SetCellOverlap(D2UnitStrc* pItem, int nCellOverlap)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nCellOverlap = nCellOverlap;
}
}
//D2Common.0x6FD98960 (#10853)
uint8_t __stdcall ITEMS_GetItemCell(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nItemCell;
}
return -1;
}
//D2Common.0x6FD98980 (#10854)
void __stdcall ITEMS_SetItemCell(D2UnitStrc* pItem, int nItemCell)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nItemCell = nItemCell;
}
}
//D2Common.0x6FD989A0 (#10723)
char* __stdcall ITEMS_GetEarName(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->szPlayerName;
}
return NULL;
}
//D2Common.0x6FD989C0 (#10724)
void __stdcall ITEMS_SetEarName(D2UnitStrc* pItem, char* szName)
{
int nCounter = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
do
{
pItem->pItemData->szPlayerName[nCounter] = szName[nCounter];
++nCounter;
}
while (szName[nCounter -1]);
}
}
//D2Common.0x6FD989F0 (#10725)
uint8_t __stdcall ITEMS_GetEarLevel(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nEarLvl;
}
return 1;
}
//D2Common.0x6FD98A10 (#10726)
void __stdcall ITEMS_SetEarLevel(D2UnitStrc* pItem, uint8_t nLevel)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nEarLvl = nLevel;
}
}
//D2Common.0x6FD98A30 (#10727)
uint8_t __stdcall ITEMS_GetVarGfxIndex(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->nInvGfxIdx;
}
return 0;
}
//D2Common.0x6FD98A50 (#10728)
void __stdcall ITEMS_SetVarGfxIndex(D2UnitStrc* pItem, uint8_t nIndex)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->nInvGfxIdx = nIndex;
}
}
//D2Common.0x6FD98A70 (#10777)
BOOL __stdcall ITEMS_IsRepairable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
int nItemType = 0;
int nCounter = 0;
int nStats = 0;
D2StatStrc pStat[64] = {};
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_IDENTIFIED && !(pItem->pItemData->dwItemFlags & IFLAG_ETHEREAL))
{
nStats = D2Common_11270(pItem, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats > 0)
{
while ((uint8_t)pStat[nCounter].nValue >= (pStat[nCounter].nValue >> 8))
{
++nCounter;
if (nCounter >= nStats)
{
break;
}
}
if (nCounter < nStats)
{
return TRUE;
}
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] < 0)
{
return FALSE;
}
if (pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nRepair)
{
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType < 0)
{
if (!pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
return TRUE;
}
return FALSE;
}
if (nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nRepair)
{
if (ITEMS_CheckItemTypeIfThrowable(ITEMS_GetItemType(pItem)) && ITEMS_CheckIfStackable(pItem) && !ITEMS_CheckItemFlag(pItem, IFLAG_ETHEREAL, __LINE__, __FILE__))
{
return TRUE;
}
}
}
if (!pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
return TRUE;
}
}
}
}
return FALSE;
}
//D2Common.0x6FD98C60 (#10780)
uint32_t __stdcall ITEMS_GetAmmoTypeFromItemType(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->wShoots;
}
}
return 0;
}
//D2Common.0x6FD98CA0 (#10781)
uint32_t __stdcall ITEMS_GetAmmoType(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_GetAmmoTypeFromItemType(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD98D20 (#10782)
uint32_t __stdcall ITEMS_GetQuiverTypeFromItemType(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->wQuiver;
}
}
return 0;
}
//D2Common.0x6FD98D60 (#10783)
uint32_t __stdcall ITEMS_GetQuiverType(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_GetQuiverTypeFromItemType(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD98DE0 (#10784)
uint32_t __stdcall ITEMS_GetAutoStackFromItemType(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
{
return pItemTypesTxtRecord->nAutoStack;
}
}
return 0;
}
//D2Common.0x6FD98E20 (#10785)
uint32_t __stdcall ITEMS_GetAutoStack(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_GetAutoStackFromItemType(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD98EA0 (#10786)
uint32_t __stdcall ITEMS_GetReload(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nReload;
}
}
}
return 0;
}
//D2Common.0x6FD98F20 (#10787)
uint32_t __stdcall ITEMS_GetReEquip(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nReEquip;
}
}
}
return 0;
}
//D2Common.0x6FD98FA0 (#10788)
uint8_t __stdcall ITEMS_GetStorePage(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nStorePage;
}
}
}
return -1;
}
//D2Common.0x6FD99020 (#10789)
uint8_t __stdcall ITEMS_GetVarInvGfxCount(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nVarInvGfx;
}
}
}
return 0;
}
//D2Common.0x6FD990A0 (#10790)
char* __stdcall ITEMS_GetVarInvGfxString(D2UnitStrc* pItem, int nId)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
if (nId < 0)
{
nId = 0;
}
if (nId >= pItemTypesTxtRecord->nVarInvGfx - 1)
{
nId = pItemTypesTxtRecord->nVarInvGfx - 1;
}
return pItemTypesTxtRecord->szInvGfx[nId];
}
}
}
return &sgptDataTables->szDefaultString;
}
//D2Common.0x6FD99140 (#10792)
BOOL __stdcall ITEMS_CanBeRare(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nRare;
}
}
}
return 0;
}
//D2Common.0x6FD991C0 (#10791)
BOOL __stdcall ITEMS_CanBeMagic(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nMagic;
}
}
}
return 0;
}
//D2Common.0x6FD99240 (#10793)
BOOL __stdcall ITEMS_CanBeNormal(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nNormal;
}
}
}
return 0;
}
//D2Common.0x6FD992C0 (#10744)
uint32_t __stdcall ITEMS_GetWeaponClassCode(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
return pItemsTxtRecord->dwWeapClass;
}
}
return 0;
}
//D2Common.0x6FD992F0 (#10745)
uint32_t __stdcall ITEMS_Get2HandWeaponClassCode(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwWeapClass2Hand;
}
//D2Common.0x6FD99370 (#10746)
uint32_t __stdcall ITEMS_GetBaseCode(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwCode;
}
//D2Common.0x6FD993F0 (#10747)
uint32_t __stdcall ITEMS_GetAltGfx(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->dwAlternateGfx)
{
return pItemsTxtRecord->dwAlternateGfx;
}
else
{
return pItemsTxtRecord->dwCode;
}
}
//D2Common.0x6FD99480 (#10748)
uint8_t __stdcall ITEMS_GetComponent(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nComponent;
}
//D2Common.0x6FD99500 (#10749)
void __stdcall ITEMS_GetDimensions(D2UnitStrc* pItem, uint8_t* pWidth, uint8_t* pHeight, char* szFile, int nLine)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
*pWidth = pItemsTxtRecord->nInvWidth;
*pHeight = pItemsTxtRecord->nInvHeight;
}
}
}
//D2Common.0x6FD99540 (#10750)
void __stdcall ITEMS_GetAllowedBodyLocations(D2UnitStrc* pItem, uint8_t* pBodyLoc1, uint8_t* pBodyLoc2)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
*pBodyLoc1 = pItemTypesTxtRecord->nBodyLoc1;
*pBodyLoc2 = pItemTypesTxtRecord->nBodyLoc2;
return;
}
}
}
*pBodyLoc1 = 0;
*pBodyLoc2 = 0;
}
//D2Common.0x6FD995D0 (#10751)
uint32_t __stdcall ITEMS_GetItemType(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2_ASSERT(pItem);
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->wType[0];
}
return 0;
}
//D2Common.0x6FD99640 (#10752)
uint32_t __stdcall ITEMS_GetItemTypeFromItemId(uint32_t dwItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(dwItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->wType[0];
}
//D2Common.0x6FD99680 (#10753)
uint8_t __stdcall ITEMS_GetItemQlvl(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nLevel;
}
//D2Common.0x6FD99700 (#10754)
int __stdcall ITEMS_CheckIfFlagIsSet(int nFlags, int nFlag)
{
return nFlags & nFlag;
}
//D2Common.0x6FD99710 (#10755)
void __stdcall ITEMS_SetOrRemoveFlag(int* pFlags, int nFlag, BOOL bSet)
{
if (bSet)
{
*pFlags |= nFlag;
}
else
{
*pFlags &= ~nFlag;
}
}
static int ITEMS_GetBonusStatFromSockets(D2UnitStrc* pItem, D2C_ItemStats stat)
{
int nStatBonusFromSockets = 0;
if (pItem->dwUnitType == UNIT_ITEM)
{
if (ITEMS_CheckIfSocketableByItemId(pItem->dwClassId))
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pItem->pInventory); i != NULL; i = INVENTORY_GetNextItem(i))
{
i = INVENTORY_UnitIsItem(i);
if (pItem->dwAnimMode == IMODE_EQUIP)
{
nStatBonusFromSockets += STATLIST_GetUnitStatUnsigned(i, stat, 0);
}
}
}
}
return nStatBonusFromSockets;
}
static bool ITEMS_CheckStatRequirement(D2UnitStrc* pItem, D2UnitStrc* pUnit, D2C_ItemStats stat, BOOL bEquipping, int nStatWithPctBonus)
{
BOOL bStatReqMet = FALSE;
const int nUnitStat = STATLIST_GetUnitStatUnsigned(pUnit, stat, 0);
if (nUnitStat > 0 && nUnitStat >= nStatWithPctBonus)
{
bStatReqMet = TRUE;
// Note: Owner was not checked in the original game for STAT_DEXTERITY
if (bEquipping && STATLIST_GetOwner(pItem, 0))
{
const int nStatBonusFromSockets = ITEMS_GetBonusStatFromSockets(pItem, stat);
if ((nUnitStat - nStatBonusFromSockets) <= 0 || (nUnitStat - nStatBonusFromSockets) < nStatWithPctBonus)
{
bStatReqMet = FALSE;
}
}
}
return bStatReqMet;
}
//D2Common.0x6FD99740 (#10756)
BOOL __stdcall ITEMS_CheckRequirements(D2UnitStrc* pItem, D2UnitStrc* pUnit, BOOL bEquipping, BOOL* bStrength, BOOL* bDexterity, BOOL* bLevel)
{
if (bStrength)
{
*bStrength = FALSE;
}
if (bDexterity)
{
*bDexterity = FALSE;
}
if (bLevel)
{
*bLevel = FALSE;
}
if (pItem == NULL || pItem->dwUnitType != UNIT_ITEM)
{
return FALSE;
}
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return FALSE;
}
BOOL bIdentified = FALSE;
const D2ItemDataStrc* pItemData = pItem->pItemData;
if (pItemData)
{
bIdentified = pItemData->dwItemFlags & IFLAG_IDENTIFIED;
}
else
{
bIdentified = FALSE;
}
const int nBaseReqStr = pItemsTxtRecord->wReqStr;
const int nBaseReqDex = pItemsTxtRecord->wReqDex;
int nReqStrBonus = 0;
int nReqDexBonus = 0;
if (int nReqPctBonus = STATLIST_GetUnitStatSigned(pItem, STAT_ITEM_REQ_PERCENT, 0))
{
// It seems the original game has some additional logic to handle overflow here
nReqStrBonus = nBaseReqStr * int64_t(nReqPctBonus) / 100;
nReqDexBonus = nBaseReqDex * int64_t(nReqPctBonus) / 100;
}
if (pItemData && pItemData->dwItemFlags & IFLAG_ETHEREAL)
{
nReqStrBonus -= 10;
nReqDexBonus -= 10;
}
const BOOL bStrReqMet = ITEMS_CheckStatRequirement(pItem, pUnit, STAT_STRENGTH, bEquipping, nBaseReqStr + nReqStrBonus);
const BOOL bDexReqMet = ITEMS_CheckStatRequirement(pItem, pUnit, STAT_DEXTERITY, bEquipping, nBaseReqDex + nReqDexBonus);
BOOL bLevelReqMet = FALSE;
const int nLevelReq = ITEMS_GetLevelRequirement(pItem, pUnit);
bLevelReqMet = nLevelReq == -1 || STATLIST_GetUnitStatUnsigned(pUnit, STAT_LEVEL, 0) >= nLevelReq;
if (bStrength)
{
*bStrength = bStrReqMet;
}
if (bDexterity)
{
*bDexterity = bDexReqMet;
}
if (bLevel)
{
*bLevel = bLevelReqMet;
}
if (bStrReqMet && bDexReqMet && bLevelReqMet && bIdentified)
{
if (pItemsTxtRecord->wType[0] == ITEMTYPE_BOOK && STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0) <= 0)
{
return FALSE;
}
const int nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
const D2ItemTypesTxt* pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(nItemType);
if (!pItemTypesTxtRecord || pItemTypesTxtRecord->nClass >= NUMBER_OF_PLAYERCLASSES)
{
return TRUE;
}
const int nClassReq = pItemTypesTxtRecord->nClass;
if (!pUnit)
{
return FALSE;
}
if (pUnit->dwUnitType == UNIT_MONSTER && nClassReq == PCLASS_BARBARIAN)
{
const int nMonsterId = pUnit->dwClassId;
if (nMonsterId >= MONSTER_ACT5HIRE1 && nMonsterId <= MONSTER_ACT5HIRE2)
{
return TRUE;
}
}
if (pUnit->dwUnitType == UNIT_PLAYER && nClassReq == pUnit->dwClassId)
{
return TRUE;
}
}
return FALSE;
}
//D2Common.0x6FD99BC0 (#10741)
BOOL __stdcall ITEMS_GetQuestFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
if (ITEMS_CheckItemTypeIdByItemId(nItemId, ITEMTYPE_ANY_ARMOR) || ITEMS_CheckItemTypeIdByItemId(nItemId, ITEMTYPE_WEAPON))
{
if (pItemsTxtRecord->dwUberCode == pItemsTxtRecord->dwCode || pItemsTxtRecord->dwUltraCode == pItemsTxtRecord->dwCode)
{
if (pItemsTxtRecord->wType[0] != ITEMTYPE_MISSILE_POTION)
{
return !pItemsTxtRecord->nQuest;
}
}
}
return 0;
}
//D2Common.0x6FD99C60 (#10742)
BOOL __stdcall ITEMS_GetQuest(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetQuestFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD99D40 (#10743)
uint32_t __stdcall ITEMS_GetNormalCode(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->dwNormCode)
{
return pItemsTxtRecord->dwNormCode;
}
else
{
return pItemsTxtRecord->dwCode;
}
}
//D2Common.0x6FD99DB0
int __fastcall ITEMS_GetRequiredLevel(D2UnitStrc* pItem, D2UnitStrc* pPlayer)
{
D2UniqueItemsTxt* pUniqueItemsTxtRecord = NULL;
D2MagicAffixTxt* pAutoAffixTxtRecord = NULL;
D2MagicAffixTxt* pPrefixTxtRecord = NULL;
D2MagicAffixTxt* pSuffixTxtRecord = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
int nRequiredLevelForSocketables = 0;
int nRequiredLevelForSkill = 0;
int nLevelRequirement = 0;
int nRequiredLevel = 0;
int nCraftBonus = 0;
D2StatStrc pStat[64] = {};
if (!pItem || pItem->dwUnitType != UNIT_ITEM || !pItem->pItemData)
{
return 0;
}
nRequiredLevel = 0;
switch (pItem->pItemData->dwQualityNo)
{
case ITEMQUAL_MAGIC:
pPrefixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicPrefix[0]);
pSuffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicSuffix[0]);
pAutoAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wAutoAffix);
if (pPrefixTxtRecord)
{
nLevelRequirement = pPrefixTxtRecord->nClass != -1 && pPlayer && pPrefixTxtRecord->nClass == pPlayer->dwClassId ? pPrefixTxtRecord->nClassLevelReq : pPrefixTxtRecord->nLevelReq;
if (nLevelRequirement >= 0)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pSuffixTxtRecord)
{
nLevelRequirement = pSuffixTxtRecord->nClass != -1 && pPlayer && pSuffixTxtRecord->nClass == pPlayer->dwClassId ? pSuffixTxtRecord->nClassLevelReq : pSuffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pAutoAffixTxtRecord)
{
nLevelRequirement = pAutoAffixTxtRecord->nClass != -1 && pPlayer && pAutoAffixTxtRecord->nClass == pPlayer->dwClassId ? pAutoAffixTxtRecord->nClassLevelReq : pAutoAffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
break;
case ITEMQUAL_RARE:
for(int i = 0; i < 3; ++i)
{
pPrefixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicPrefix[i]);
pSuffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicSuffix[i]);
if (pPrefixTxtRecord)
{
nLevelRequirement = pPrefixTxtRecord->nClass != -1 && pPlayer && pPrefixTxtRecord->nClass == pPlayer->dwClassId ? pPrefixTxtRecord->nClassLevelReq : pPrefixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pSuffixTxtRecord)
{
nLevelRequirement = pSuffixTxtRecord->nClass != -1 && pPlayer && pSuffixTxtRecord->nClass == pPlayer->dwClassId ? pSuffixTxtRecord->nClassLevelReq : pSuffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
}
pAutoAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wAutoAffix);
if (pAutoAffixTxtRecord)
{
nLevelRequirement = pAutoAffixTxtRecord->nClass != -1 && pPlayer && pAutoAffixTxtRecord->nClass == pPlayer->dwClassId ? pAutoAffixTxtRecord->nClassLevelReq : pAutoAffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
break;
case ITEMQUAL_CRAFT:
nCraftBonus = 10;
for (int i = 0; i < 3; ++i)
{
pPrefixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicPrefix[i]);
pSuffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->pItemData->wMagicSuffix[i]);
if (pPrefixTxtRecord)
{
nCraftBonus += 3;
nLevelRequirement = pPrefixTxtRecord->nClass != -1 && pPlayer && pPrefixTxtRecord->nClass == pPlayer->dwClassId ? pPrefixTxtRecord->nClassLevelReq : pPrefixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
if (pSuffixTxtRecord)
{
nCraftBonus += 3;
nLevelRequirement = pSuffixTxtRecord->nClass != -1 && pPlayer && pSuffixTxtRecord->nClass == pPlayer->dwClassId ? pSuffixTxtRecord->nClassLevelReq : pSuffixTxtRecord->nLevelReq;
if (nRequiredLevel <= nLevelRequirement)
{
nRequiredLevel = nLevelRequirement;
}
}
}
nRequiredLevel += nCraftBonus;
if (nRequiredLevel >= DATATBLS_GetMaxLevel(0))
{
nRequiredLevel = DATATBLS_GetMaxLevel(0) - 1;
}
break;
case ITEMQUAL_UNIQUE:
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nUniqueItemsTxtRecordCount)
{
pUniqueItemsTxtRecord = &sgptDataTables->pUniqueItemsTxt[pItem->pItemData->dwFileIndex];
if (pUniqueItemsTxtRecord)
{
if (pPlayer)
{
if ((ITEMS_CheckUnitFlagEx(pPlayer, UNITFLAGEX_ISEXPANSION) || ITEMS_GetItemFormat(pItem) >= 1) && (int)pUniqueItemsTxtRecord->wLvlReq >= 0)
{
nRequiredLevel = pUniqueItemsTxtRecord->wLvlReq;
}
}
else
{
if ((int)pUniqueItemsTxtRecord->wLvlReq >= 0)
{
nRequiredLevel = pUniqueItemsTxtRecord->wLvlReq;
}
}
}
}
break;
case ITEMQUAL_SET:
pSetItemsTxtRecord = ITEMS_GetSetItemsTxtRecord(ITEMS_GetFileIndex(pItem));
if (pSetItemsTxtRecord && pSetItemsTxtRecord->wLvlReq >= 0)
{
nRequiredLevel = pSetItemsTxtRecord->wLvlReq;
}
break;
default:
break;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
if (pItemsTxtRecord->nLevelReq > nRequiredLevel)
{
nRequiredLevel = pItemsTxtRecord->nLevelReq;
}
}
if (pItem->pInventory)
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pItem->pInventory); i; i = INVENTORY_GetNextItem(i))
{
if (!INVENTORY_UnitIsItem(i))
{
break;
}
nRequiredLevelForSocketables = ITEMS_GetRequiredLevel(i, pPlayer);
if (nRequiredLevel <= nRequiredLevelForSocketables)
{
nRequiredLevel = nRequiredLevelForSocketables;
}
}
}
for (int i = 0; i < D2Common_11270(pItem, STAT_ITEM_SINGLESKILL, pStat, ARRAY_SIZE(pStat)); ++i)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[i].nLayer);
if (pSkillsTxtRecord)
{
if (pSkillsTxtRecord->wReqLevel > nRequiredLevel)
{
nRequiredLevel = pSkillsTxtRecord->wReqLevel;
}
}
}
for (int i = 0; i < D2Common_11270(pItem, STAT_ITEM_NONCLASSSKILL, pStat, ARRAY_SIZE(pStat)); ++i)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[i].nLayer);
if (pSkillsTxtRecord)
{
if (!pPlayer || pPlayer->dwUnitType || pSkillsTxtRecord->nCharClass < 0 || pSkillsTxtRecord->nCharClass >= 7 || (pPlayer->dwClassId & 0xFF) != pSkillsTxtRecord->nCharClass)
{
nRequiredLevelForSkill = pSkillsTxtRecord->wReqLevel + 6;
}
else
{
nRequiredLevelForSkill = pSkillsTxtRecord->wReqLevel;
}
if (nRequiredLevelForSkill > nRequiredLevel)
{
nRequiredLevel = nRequiredLevelForSkill;
}
}
}
nRequiredLevel += STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_LEVELREQ, 0);
if (nRequiredLevel <= 0)
{
nRequiredLevel = 0;
}
return nRequiredLevel;
}
//D2Common.0x6FD9A3F0 (#10757)
int __stdcall ITEMS_GetLevelRequirement(D2UnitStrc* pItem, D2UnitStrc* pUnit)
{
return ITEMS_GetRequiredLevel(pItem, pUnit);
}
//D2Common.0x6FD9A400 (#10758)
BOOL __stdcall ITEMS_CheckBodyLocation(D2UnitStrc* pItem, uint8_t nBodyLoc)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
uint8_t nBodyLoc1 = 0;
uint8_t nBodyLoc2 = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
nBodyLoc1 = pItemTypesTxtRecord->nBodyLoc1;
nBodyLoc2 = pItemTypesTxtRecord->nBodyLoc2;
}
}
if (nBodyLoc1 == nBodyLoc || nBodyLoc2 == nBodyLoc
|| (nBodyLoc == BODYLOC_SWRARM || nBodyLoc == BODYLOC_SWLARM) && (nBodyLoc1 == BODYLOC_RARM || nBodyLoc2 == BODYLOC_RARM || nBodyLoc1 == BODYLOC_LARM || nBodyLoc2 == BODYLOC_LARM))
{
return TRUE;
}
}
else
{
FOG_WriteToLogFile(" ----- JONM NOTE: Would have crashed, see code at ITEMSCheckBodyLocation. From FILE: %s LINE: %d", __FILE__, __LINE__);
}
return FALSE;
}
//D2Common.0x6FD9A4F0 (#10762)
int __stdcall ITEMS_CheckItemTypeIfThrowable(int nItemType)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nThrowable;
}
}
return 0;
}
//D2Common.0x6FD9A530 (#10759)
int __stdcall ITEMS_CheckIfThrowable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return ITEMS_CheckItemTypeIfThrowable(pItemsTxtRecord->wType[0]);
}
return 0;
}
//D2Common.0x6FD9A5B0 (#10760)
int __stdcall ITEMS_GetMissileType(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->wMissileType;
}
return -1;
}
//D2Common.0x6FD9A5E0 (#10761)
uint8_t __stdcall ITEMS_GetMeleeRange(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->nRangeAdder;
}
return 0;
}
//D2Common.0x6FD9A610 (#10763)
BOOL __stdcall ITEMS_CheckWeaponClassByItemId(int nItemId, int nWeapClass)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwWeapClass == nWeapClass;
}
//D2Common.0x6FD9A660 (#10764)
BOOL __stdcall ITEMS_CheckWeaponClass(D2UnitStrc* pItem, int nWeapClass)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_CheckWeaponClassByItemId(pItem->dwClassId, nWeapClass);
}
return 0;
}
//D2Common.0x6FD9A6C0 (#10766)
uint32_t __stdcall ITEMS_CheckWeaponIfTwoHandedByItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->n2Handed;
}
//D2Common.0x6FD9A700 (#10765)
uint32_t __stdcall ITEMS_CheckWeaponIfTwoHanded(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_CheckWeaponIfTwoHandedByItemId(pItem->dwClassId);
}
return 0;
}
//D2Common.0x6FD9A750 (#10767)
uint32_t __stdcall ITEMS_CheckIfStackable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nStackable;
}
return 0;
}
//D2Common.0x6FD9A7A0 (#10768)
uint32_t __stdcall ITEMS_CheckIfBeltable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nBeltable;
}
}
}
return 0;
}
//D2Common.0x6FD9A820 (#10769)
BOOL __stdcall ITEMS_ComparePotionTypes(D2UnitStrc* pItem1, D2UnitStrc* pItem2)
{
static const int szHealthPotCodes[] =
{
' 1ph', ' 2ph', ' 3ph', ' 4ph', ' 5ph'
};
static const int szManaPotCodes[] =
{
' 1pm', ' 2pm', ' 3pm', ' 4pm', ' 5pm'
};
static const int szRejuvPotCodes[] =
{
' lvr', ' svr'
};
D2ItemsTxt* pItemsTxtRecord1 = NULL;
D2ItemsTxt* pItemsTxtRecord2 = NULL;
int nCounter = 0;
bool bPot1 = false;
bool bPot2 = false;
if (pItem1 && pItem2)
{
if (pItem1->dwClassId == pItem2->dwClassId)
{
return TRUE;
}
pItemsTxtRecord1 = DATATBLS_GetItemsTxtRecord(pItem1->dwClassId);
pItemsTxtRecord2 = DATATBLS_GetItemsTxtRecord(pItem2->dwClassId);
bPot1 = false;
bPot2 = false;
nCounter = 0;
do
{
if (!bPot1 && pItemsTxtRecord1->dwCode == szHealthPotCodes[nCounter])
{
bPot1 = true;
}
if (!bPot2 && pItemsTxtRecord2->dwCode == szHealthPotCodes[nCounter])
{
bPot2 = true;
}
if (bPot1 && bPot2)
{
return TRUE;
}
++nCounter;
}
while (nCounter < ARRAY_SIZE(szHealthPotCodes));
bPot1 = false;
bPot2 = false;
nCounter = 0;
do
{
if (!bPot1 && pItemsTxtRecord1->dwCode == szManaPotCodes[nCounter])
{
bPot1 = true;
}
if (!bPot2 && pItemsTxtRecord2->dwCode == szManaPotCodes[nCounter])
{
bPot2 = true;
}
if (bPot1 && bPot2)
{
return TRUE;
}
++nCounter;
}
while (nCounter < ARRAY_SIZE(szManaPotCodes));
bPot1 = false;
bPot2 = false;
nCounter = 0;
do
{
if (!bPot1 && pItemsTxtRecord1->dwCode == szRejuvPotCodes[nCounter])
{
bPot1 = true;
}
if (!bPot2 && pItemsTxtRecord2->dwCode == szRejuvPotCodes[nCounter])
{
bPot2 = true;
}
if (bPot1 && bPot2)
{
return TRUE;
}
++nCounter;
}
while (nCounter < ARRAY_SIZE(szRejuvPotCodes));
}
return FALSE;
}
//D2Common.0x6FD9A960 (#10770)
BOOL __stdcall ITEMS_CheckIfAutoBeltable(D2InventoryStrc* pInventory, D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nAutoBelt || INVENTORY_HasSimilarPotionInBelt(pInventory, pItem) != -1;
}
//D2Common.0x6FD9AA00 (#10771)
BOOL __stdcall ITEMS_CheckIfUseable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nUseable;
}
else
{
FOG_WriteToLogFile(" ----- JONM NOTE: Would have crashed, see code at ITEMSIsUseable. From FILE: %s LINE: %d", __FILE__, __LINE__);
return 0;
}
}
//D2Common.0x6FD9AA70 (#10772)
int __stdcall ITEMS_GetUniqueColumnFromItemsTxt(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nUnique;
}
//D2Common.0x6FD9AB00 (#10773)
BOOL __stdcall ITEMS_IsQuestItem(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nQuest;
}
//D2Common.0x6FD9AB90
int __fastcall ITEMS_CalculateAdditionalCostsForChargedSkills(D2UnitStrc* pUnit, int nBaseCost)
{
D2SkillsTxt* pSkillsTxtRecord = NULL;
int nCounter = 0;
int nSkillId = 0;
int nValue = 0;
int nStats = 0;
int nCost = 0;
int nBase = 0;
int nAdd = 0;
int nMax = 0;
D2StatStrc pStat[64] = {};
nStats = D2Common_11270(pUnit, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats > 0)
{
do
{
nSkillId = pStat[nCounter].nLayer >> sgptDataTables->nStuff;
nMax = pStat[nCounter].nValue >> 8;
nValue = pStat[nCounter].nValue & 0xFF;
if (nValue < nMax)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(nSkillId);
if (pSkillsTxtRecord)
{
nBase = nBaseCost * ((pStat[nCounter].nLayer & sgptDataTables->nShiftedStuff) + 2 * pSkillsTxtRecord->wReqLevel / 6 + 2);
if (nBase > 65535 && pSkillsTxtRecord->nCostMult)
{
nAdd = pSkillsTxtRecord->nCostMult * nBase / 1024;
}
else
{
nAdd = nBase * pSkillsTxtRecord->nCostMult / 1024;
}
nCost += (pSkillsTxtRecord->nCostAdd + nAdd) * (nMax - nValue) / nMax;
}
}
++nCounter;
}
while (nCounter < nStats);
return nCost;
}
return 0;
}
//D2Common.0x6FD9ACE0
void __fastcall ITEMS_CalculateAdditionalCostsForBonusStats(D2UnitStrc* pItem, int* pSellCost, int* pBuyCost, int* pRepCost, unsigned int nDivisor)
{
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
unsigned int nSell = 0;
unsigned int nBuy = 0;
unsigned int nRep = 0;
int nBonusValue = 0;
int nSkillId = 0;
int nCounter = 0;
int nStatId = 0;
int nStats = 0;
int nValue = 0;
int dw1 = 0;
int dw2 = 0;
int dw3 = 0;
D2StatStrc pStat[511] = {};
nStats = STATLIST_GetFullStatsDataFromUnit(pItem, pStat, ARRAY_SIZE(pStat));
while (nCounter < nStats)
{
nStatId = pStat[nCounter].nStat;
nBonusValue = STATLIST_GetUnitStatBonus(pItem, nStatId, pStat[nCounter].nLayer);
if (nBonusValue)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(nStatId);
if (pItemStatCostTxtRecord)
{
if (pItemStatCostTxtRecord->nValShift)
{
nBonusValue >>= pItemStatCostTxtRecord->nValShift;
}
switch (pItemStatCostTxtRecord->nEncode)
{
case 1:
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[nCounter].nLayer);
if (pSkillsTxtRecord)
{
if (nBonusValue * *pSellCost > 65535 && pSkillsTxtRecord->nCostMult)
{
nSell += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nBonusValue * *pSellCost / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nBonusValue * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nBonusValue * *pRepCost / 1024;
}
else
{
nSell += pSkillsTxtRecord->nCostAdd + nBonusValue * *pSellCost * pSkillsTxtRecord->nCostMult / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + nBonusValue * pSkillsTxtRecord->nCostMult * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + nBonusValue * pSkillsTxtRecord->nCostMult * *pRepCost / 1024;
}
}
break;
case 2:
case 3:
nSkillId = pStat[nCounter].nLayer >> sgptDataTables->nStuff;
nValue = pStat[nCounter].nLayer & sgptDataTables->nShiftedStuff;
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(nSkillId);
if (nValue * *pSellCost > 65535 && pSkillsTxtRecord->nCostMult)
{
nSell += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nValue * *pSellCost / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nValue * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * nValue * *pRepCost / 1024;
}
else
{
nSell += pSkillsTxtRecord->nCostAdd + nValue * *pSellCost * pSkillsTxtRecord->nCostMult / 1024;
nBuy += pSkillsTxtRecord->nCostAdd + nValue * pSkillsTxtRecord->nCostMult * *pBuyCost / 4096;
nRep += pSkillsTxtRecord->nCostAdd + nValue * pSkillsTxtRecord->nCostMult * *pRepCost / 1024;
}
break;
case 4:
D2COMMON_10843_GetByTimeAdjustment(nBonusValue, 0, 0, &dw1, &dw2, &dw3);
nValue = (dw2 + dw3) / 2;
if (nValue * *pSellCost > 65535 && pItemStatCostTxtRecord->dwMultiply)
{
nSell += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nValue * *pSellCost / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nValue * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nValue * *pRepCost / 1024;
}
else
{
nSell += pItemStatCostTxtRecord->dwAdd + nValue * *pSellCost * pItemStatCostTxtRecord->dwMultiply / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + nValue * pItemStatCostTxtRecord->dwMultiply * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + nValue * pItemStatCostTxtRecord->dwMultiply * *pRepCost / 1024;
}
break;
default:
if (nBonusValue * *pSellCost > 65535 && pItemStatCostTxtRecord->dwMultiply)
{
nSell += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nBonusValue * *pSellCost / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nBonusValue * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + pItemStatCostTxtRecord->dwMultiply * nBonusValue * *pRepCost / 1024;
}
else
{
nSell += pItemStatCostTxtRecord->dwAdd + nBonusValue * *pSellCost * pItemStatCostTxtRecord->dwMultiply / 1024;
nBuy += pItemStatCostTxtRecord->dwAdd + nBonusValue * pItemStatCostTxtRecord->dwMultiply * *pBuyCost / 1024;
nRep += pItemStatCostTxtRecord->dwAdd + nBonusValue * pItemStatCostTxtRecord->dwMultiply * *pRepCost / 1024;
}
break;
}
}
}
++nCounter;
}
*pSellCost += nSell / nDivisor;
*pBuyCost += nBuy / nDivisor;
*pRepCost += nRep / nDivisor;
}
//TODO: Check Calculations for unnamed variables, contains some small (rounding?) errors
//D2Common.0x6FD9B1C0
int __fastcall ITEMS_CalculateTransactionCost(D2UnitStrc* pPlayer, D2UnitStrc* pItem, int nDifficulty, D2BitBufferStrc* pQuestFlags, int nVendorId, int nTransactionType)
{
D2UniqueItemsTxt* pUniqueItemsTxtRecord = NULL;
D2MagicAffixTxt* pMagicAffixTxtRecord = NULL;
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2MonStatsTxt* pMonStatsTxtRecord = NULL;
D2ItemsTxt* pUltraItemsTxtRecord = NULL;
D2ItemsTxt* pUberItemsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2BooksTxt* pBooksTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
D2NpcTxt* pNpcTxtRecord = NULL;
D2UnitStrc* pSocketable = NULL;
int nSocketableCost = 0;
int nReducePricePct = 0;
int nStackQuantity = 0;
int nArmorClass = 0;
int nDurability = 0;
int nFileIndex = 0;
int nUltraCost = 0;
int nUberCost = 0;
int nItemType = 0;
int nQuantity = 0;
int nMaxStack = 0;
int nSellCost = 0;
int nBuyCost = 0;
int nRepCost = 0;
int nDivisor = 0;
int nMaxDura = 0;
int nQuality = 0;
int nItemId = 0;
int nLevel = 0;
int nStack = 0;
int nCost = 0;
int nBase = 0;
int nSell = 0;
int nBuy = 0;
int nRep = 0;
int v30 = 0, v27 = 0, v22 = 0, v23 = 0; //TODO: Rename
if (!pPlayer || !pItem || pItem->dwUnitType != UNIT_ITEM || !pItem->pItemData)
{
return 0x7FFFFFFF;
}
pItemData = pItem->pItemData;
nLevel = STATLIST_GetUnitStatUnsigned(pPlayer, STAT_LEVEL, 0);
if (nTransactionType == 3 && !ITEMS_IsRepairable(pItem))
{
return 0;
}
if (pItemData->dwItemFlags & IFLAG_STARTITEM)
{
return 1;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
nQuantity = STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0);
if (nQuantity <= 0)
{
nQuantity = 1;
}
nReducePricePct = STATLIST_GetUnitStatUnsigned(pPlayer, STAT_ITEM_REDUCEDPRICES, 0);
if (nReducePricePct >= 99)
{
nReducePricePct = 99;
}
if (nTransactionType != 2)
{
nSellCost = 0;
nBuyCost = 0;
nRepCost = 0;
nDivisor = 1;
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
nSellCost = pItemsTxtRecord->dwCost * pItemData->nEarLvl;
nBuyCost = nSellCost;
}
else
{
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BODY_PART))
{
nFileIndex = pItemData->dwFileIndex;
pMonStatsTxtRecord = DATATBLS_GetMonStatsTxtRecord(nFileIndex);
if (pMonStatsTxtRecord)
{
nSellCost = 8 * pMonStatsTxtRecord->nLevel[nDifficulty];
}
nSellCost += pItemsTxtRecord->dwCost;
nBuyCost = nSellCost;
}
else
{
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
pBooksTxtRecord = DATATBLS_GetBooksTxtRecord(pItemData->wMagicSuffix[0]);
D2_ASSERT(pBooksTxtRecord);
nSellCost = pItemsTxtRecord->dwCost + nQuantity * pBooksTxtRecord->dwCostPerCharge;
nBuyCost = nSellCost;
}
else
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(ITEMS_GetItemTypeFromItemId(pItem->dwClassId));
if (pItemTypesTxtRecord && pItemTypesTxtRecord->wQuiver)
{
nSellCost = nQuantity * pItemsTxtRecord->dwCost / 1024;
nBuyCost = nSellCost;
nStackQuantity = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nStackQuantity >= 511)
{
nStackQuantity = 511;
}
nRepCost = nStackQuantity * pItemsTxtRecord->dwCost / 1024;
}
else
{
if (!pItemsTxtRecord->nStackable)
{
nSellCost = pItemsTxtRecord->dwCost;
nBuyCost = nSellCost;
nRepCost = nSellCost;
}
else
{
nSellCost = pItemsTxtRecord->dwCost;
nBuyCost = nSellCost;
nRepCost = nSellCost;
nDivisor = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nDivisor < 511)
{
if (nDivisor <= 1)
{
nDivisor = 1;
}
}
else
{
nDivisor = 511;
}
}
}
}
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR))
{
nArmorClass = STATLIST_GetUnitBaseStat(pItem, STAT_ARMORCLASS, 0);
if (pItemsTxtRecord->dwMaxAc - pItemsTxtRecord->dwMinAc != -1)
{
if (pItemsTxtRecord->dwMaxAc)
{
nSellCost = nArmorClass * pItemsTxtRecord->dwCost / pItemsTxtRecord->dwMaxAc;
nBuyCost = nArmorClass * pItemsTxtRecord->dwCost / pItemsTxtRecord->dwMaxAc;
nRepCost = nArmorClass * pItemsTxtRecord->dwCost / pItemsTxtRecord->dwMaxAc;
}
}
}
nQuality = pItemData->dwQualityNo;
if (nQuality < ITEMQUAL_MAGIC || nQuality > ITEMQUAL_TEMPERED)
{
ITEMS_CalculateAdditionalCostsForItemSkill(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
}
if (pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wAutoAffix);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell = pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy = pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep = pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell = pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy = pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep = pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
switch (nQuality)
{
case ITEMQUAL_RARE:
case ITEMQUAL_CRAFT:
for (int i = 0; i < 3; ++i)
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicPrefix[i]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicSuffix[i]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
}
ITEMS_CalculateAdditionalCostsForBonusStats(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
break;
case ITEMQUAL_UNIQUE:
if (pItemData->dwFileIndex >= 0 && pItemData->dwFileIndex < sgptDataTables->nUniqueItemsTxtRecordCount)
{
pUniqueItemsTxtRecord = &sgptDataTables->pUniqueItemsTxt[pItemData->dwFileIndex];
if (pUniqueItemsTxtRecord)
{
if (nSellCost > 65535 && pUniqueItemsTxtRecord->dwCostMult)
{
nSell += pUniqueItemsTxtRecord->dwCostAdd + pUniqueItemsTxtRecord->dwCostMult * nSellCost / 1024;
nBuy += pUniqueItemsTxtRecord->dwCostAdd + pUniqueItemsTxtRecord->dwCostMult * nBuyCost / 1024;
nRep += pUniqueItemsTxtRecord->dwCostAdd + pUniqueItemsTxtRecord->dwCostMult * nRepCost / 1024;
}
else
{
nSell += pUniqueItemsTxtRecord->dwCostAdd + nSellCost * pUniqueItemsTxtRecord->dwCostMult / 1024;
nBuy += pUniqueItemsTxtRecord->dwCostAdd + nBuyCost * pUniqueItemsTxtRecord->dwCostMult / 1024;
nRep += pUniqueItemsTxtRecord->dwCostAdd + nRepCost * pUniqueItemsTxtRecord->dwCostMult / 1024;
break;
}
}
}
//TODO: Not sure if it was intended to have no break here
case ITEMQUAL_MAGIC:
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicPrefix[0]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItemData->wMagicSuffix[0]);
if (pMagicAffixTxtRecord)
{
if (nSellCost > 65535 && pMagicAffixTxtRecord->dwMultiply)
{
nSell += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nSellCost / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nBuyCost / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + pMagicAffixTxtRecord->dwMultiply * nRepCost / 1024;
}
else
{
nSell += pMagicAffixTxtRecord->dwAdd + nSellCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nBuy += pMagicAffixTxtRecord->dwAdd + nBuyCost * pMagicAffixTxtRecord->dwMultiply / 1024;
nRep += pMagicAffixTxtRecord->dwAdd + nRepCost * pMagicAffixTxtRecord->dwMultiply / 1024;
}
}
ITEMS_CalculateAdditionalCostsForBonusStats(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
break;
case ITEMQUAL_SUPERIOR:
case ITEMQUAL_TEMPERED:
ITEMS_CalculateAdditionalCostsForBonusStats(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
break;
case ITEMQUAL_SET:
if (pItemData->dwFileIndex >= 0 && pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[pItemData->dwFileIndex];
if (pSetItemsTxtRecord)
{
if (nSellCost > 65535 && pSetItemsTxtRecord->dwCostMult)
{
nSell += pSetItemsTxtRecord->dwCostAdd + pSetItemsTxtRecord->dwCostMult * nSellCost / 1024;
nBuy += pSetItemsTxtRecord->dwCostAdd + pSetItemsTxtRecord->dwCostMult * nBuyCost / 1024;
nRep += pSetItemsTxtRecord->dwCostAdd + pSetItemsTxtRecord->dwCostMult * nRepCost / 1024;
}
else
{
nSell += pSetItemsTxtRecord->dwCostAdd + nSellCost * pSetItemsTxtRecord->dwCostMult / 1024;
nBuy += pSetItemsTxtRecord->dwCostAdd + nBuyCost * pSetItemsTxtRecord->dwCostMult / 1024;
nRep += pSetItemsTxtRecord->dwCostAdd + nRepCost * pSetItemsTxtRecord->dwCostMult / 1024;
}
}
}
break;
case ITEMQUAL_INFERIOR:
nSell = nSellCost / -2;
nBuy = nBuyCost / -2;
nRep = nRepCost / -2;
break;
default:
break;
}
nSellCost += nSell / nDivisor;
nBuyCost += nBuy / nDivisor;
nRepCost += nRep / nDivisor;
if (nQuality >= ITEMQUAL_MAGIC && nQuality <= ITEMQUAL_TEMPERED)
{
ITEMS_CalculateAdditionalCostsForItemSkill(pItem, &nSellCost, &nBuyCost, &nRepCost, nDivisor);
}
}
if (pItem->pInventory)
{
pSocketable = INVENTORY_GetFirstItem(pItem->pInventory);
while (pSocketable)
{
if (INVENTORY_UnitIsItem(pSocketable))
{
nSocketableCost = DATATBLS_GetItemsTxtRecord(pSocketable->dwClassId)->dwCost / 2;
nSellCost += nSocketableCost;
nBuyCost += nSocketableCost;
nRepCost += nSocketableCost;
}
pSocketable = INVENTORY_GetNextItem(pSocketable);
}
}
if (pItemData->dwItemFlags & IFLAG_ETHEREAL)
{
nBuyCost /= 4;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nClass < 7)
{
nBuyCost /= 4;
}
}
if (nTransactionType == 1)
{
if (pItemData->dwItemFlags & IFLAG_ETHEREAL && !pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) <= 0)
{
nBuyCost = 0;
}
}
}
else if (nTransactionType == 3)
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(pItemsTxtRecord->wType[0]);
if (!pItemTypesTxtRecord || !pItemTypesTxtRecord->wQuiver || !pItemTypesTxtRecord->nThrowable)
{
if (!pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
nDurability = STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0);
nMaxDura = STATLIST_GetMaxDurabilityFromUnit(pItem);
if (nMaxDura && nDurability < nMaxDura)
{
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_REPLENISH_DURABILITY, 0))
{
if (nDurability < nMaxDura - 1)
{
nRepCost *= (nMaxDura - 1) / nMaxDura;
}
else
{
nRepCost = 0;
}
}
else
{
nRepCost *= (nMaxDura - nDurability) / nMaxDura;
}
}
else
{
nRepCost = 0;
}
}
}
}
pNpcTxtRecord = DATATBLS_GetNpcTxtRecord(nVendorId);
D2_ASSERT(pNpcTxtRecord);
if (nSellCost <= 65535 || !pNpcTxtRecord->dwSellMult)
{
nSellCost = nSellCost * pNpcTxtRecord->dwSellMult / 1024;
}
else
{
nSellCost = pNpcTxtRecord->dwSellMult * nSellCost / 1024;
}
if (nBuyCost <= 65535 || !pNpcTxtRecord->dwSellMult)//TODO: Probably Copy-Paste Error by Blizzard, should be dwBuyMult
{
nBuyCost = nBuyCost * pNpcTxtRecord->dwBuyMult / 1024;
}
else
{
nBuyCost = nBuyCost / 1024 * pNpcTxtRecord->dwBuyMult;
}
if (nRepCost <= 65535 || !pNpcTxtRecord->dwRepMult)
{
nRepCost = nRepCost * pNpcTxtRecord->dwRepMult / 1024;
}
else
{
nRepCost = pNpcTxtRecord->dwRepMult * nRepCost / 1024;
}
for (int i = 0; i < 3; ++i)
{
if (pNpcTxtRecord->dwQuestFlag[i] && (QUESTRECORD_GetQuestState(pQuestFlags, pNpcTxtRecord->dwQuestFlag[i], QFLAG_REWARDGRANTED) == 1
|| QUESTRECORD_GetQuestState(pQuestFlags, pNpcTxtRecord->dwQuestFlag[i], QFLAG_REWARDPENDING) == 1))
{
if (nSellCost > 65535 && pNpcTxtRecord->dwQuestSellMult[i])
{
nSellCost = pNpcTxtRecord->dwQuestSellMult[i] * nSellCost / 1024;
}
else
{
nSellCost = nSellCost * pNpcTxtRecord->dwQuestSellMult[i] / 1024;
}
if (nBuyCost > 65535 && pNpcTxtRecord->dwQuestBuyMult[i])
{
nBuyCost = pNpcTxtRecord->dwQuestBuyMult[i] * nBuyCost / 1024;
}
else
{
nBuyCost = nBuyCost * pNpcTxtRecord->dwQuestBuyMult[i] / 1024;
}
if (nRepCost > 65535 && pNpcTxtRecord->dwQuestRepMult[i])
{
nRepCost = pNpcTxtRecord->dwQuestRepMult[i] * nRepCost / 1024;
}
else
{
nRepCost = nRepCost * pNpcTxtRecord->dwQuestRepMult[i] / 1024;
}
}
}
if (!ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(pItemsTxtRecord->wType[0]);
if (!pItemTypesTxtRecord || !pItemTypesTxtRecord->wQuiver)
{
nSellCost *= nQuantity;
if (pItemsTxtRecord->nStackable && ITEMS_IsRepairable(pItem))
{
nMaxStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nMaxStack >= 511)
{
nMaxStack = 511;
}
if (nQuantity < nMaxStack && !STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_REPLENISH_QUANTITY, 0))
{
nRepCost *= (nMaxStack - nQuantity);
}
else
{
nRepCost = 0;
}
nBuyCost *= (nMaxStack - nRepCost);
}
else
{
nBuyCost *= nQuantity;
}
}
}
nCost = nBuyCost;
if (nTransactionType == 3)
{
if (!(pItemData->dwItemFlags & IFLAG_ETHEREAL))
{
nRepCost += ITEMS_CalculateAdditionalCostsForChargedSkills(pItem, 10000);
}
}
if (nCost > pNpcTxtRecord->nMaxBuy[nDifficulty])
{
nCost = pNpcTxtRecord->nMaxBuy[nDifficulty];
}
if (nTransactionType != 1)
{
if (nTransactionType == 3)
{
nCost = nRepCost - DATATBLS_CalculatePercentage(nRepCost, nReducePricePct, 100);
}
else
{
nCost = nSellCost - DATATBLS_CalculatePercentage(nSellCost, nReducePricePct, 100);
}
}
if (nCost < 1)
{
nCost = 1;
}
return nCost;
}
else
{
if (pItemData->wItemFormat >= 1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(DATATBLS_GetItemIdFromItemCode(pItemsTxtRecord->dwNormCode ? pItemsTxtRecord->dwNormCode : pItemsTxtRecord->dwCode));
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->dwCode == ' nir' || pItemsTxtRecord->dwCode == ' uma')
{
nCost = pItemsTxtRecord->dwGambleCost;
}
else
{
nStack = pItemsTxtRecord->dwMinStack + pItemsTxtRecord->dwMaxStack;
v27 = ((signed int)nStack - HIDWORD(nStack)) >> 1;
if (v27 < 1)
{
v27 = 1;
}
if (pItemsTxtRecord->dwUberCode && pItemsTxtRecord->dwUberCode != ' 0')
{
pUberItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwUberCode, &nItemId);
if (pUberItemsTxtRecord)
{
v30 = 100 * (nLevel - pUberItemsTxtRecord->nLevel);
v23 = (((signed int)v30 - HIDWORD(v30)) >> 1) + 1;
if (v23 < 0)
{
v23 = 0;
}
nUberCost = pUberItemsTxtRecord->dwCost;
}
}
if (pItemsTxtRecord->dwUltraCode && pItemsTxtRecord->dwUltraCode != ' 0')
{
pUltraItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwUltraCode, &nItemId);
if (pUltraItemsTxtRecord)
{
v30 = 100 * (nLevel - pUltraItemsTxtRecord->nLevel);
v22 = (((BYTE4(v30) & 3) + (signed int)v30) >> 2) + 1;
if (v22 < 0)
{
v22 = 0;
}
nUltraCost = pUltraItemsTxtRecord->dwCost;
}
}
nBase = v23 * nUberCost + v22 * nUltraCost + (v27 * pItemsTxtRecord->dwCost) * (10000 - v22 - v23);
if (nLevel < 5)
{
nLevel = 5;
}
nCost = ((2 * nLevel + 1) / 3 + 20) * (nBase / 10000 + (250 * (nLevel + ((pItemsTxtRecord->nLevel - 45) > 0 ? (pItemsTxtRecord->nLevel - 45) : 0) - (int)pItemsTxtRecord->nLevel / 2)) / 3) / 15;
}
if (nReducePricePct)
{
return nCost - DATATBLS_CalculatePercentage(nCost, nReducePricePct, 100);
}
else
{
return nCost;
}
}
else
{
return DATATBLS_GetItemsTxtRecord(DATATBLS_GetItemIdFromItemCode(pItemsTxtRecord->dwNormCode ? pItemsTxtRecord->dwNormCode : pItemsTxtRecord->dwCode))->dwGambleCost;
}
}
}
//D2Common.0x6FD9CB50
void __fastcall ITEMS_CalculateAdditionalCostsForItemSkill(D2UnitStrc* pItem, int* pSellCost, int* pBuyCost, int* pRepCost, unsigned int nDivisor)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
unsigned int nSell = 0;
unsigned int nBuy = 0;
unsigned int nRep = 0;
int nStats = 0;
D2StatStrc pStat[64] = {};
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nStaffMods != 7)
{
nStats = D2Common_11270(pItem, STAT_ITEM_SINGLESKILL, pStat, ARRAY_SIZE(pStat));
for (int nStatId = 0; nStatId < nStats; ++nStatId)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(pStat[nStatId].nLayer);
if (pSkillsTxtRecord)
{
if (*pSellCost > 65535 && pSkillsTxtRecord->nCostMult)
{
nSell += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + *pSellCost * pSkillsTxtRecord->nCostMult / 1024);
nBuy += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + *pBuyCost * pSkillsTxtRecord->nCostMult / 4096);
nRep += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + *pRepCost * pSkillsTxtRecord->nCostMult / 1024);
}
else
{
nSell += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * *pSellCost / 1024);
nBuy += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * *pBuyCost / 4096);
nRep += (2 * pStat[nStatId].nValue - 1) * (pSkillsTxtRecord->nCostAdd + pSkillsTxtRecord->nCostMult * *pRepCost / 1024);
}
}
}
*pSellCost += nSell / nDivisor;
*pBuyCost += nBuy / nDivisor;
*pRepCost += nRep / nDivisor;
}
}
}
}
//D2Common.0x6FD9CDC0
int __fastcall ITEMS_CheckUnitFlagEx(D2UnitStrc* pUnit, int nFlag)
{
if (pUnit)
{
return (nFlag & pUnit->dwFlagEx) != 0;
}
return 0;
}
//D2Common.0x6FD9CDE0 (#10775)
int __stdcall ITEMS_GetTransactionCost(D2UnitStrc* pPlayer, D2UnitStrc* pItem, int nDifficulty, D2BitBufferStrc* pQuestFlags, int nVendorId, int nTransactionType)
{
return ITEMS_CalculateTransactionCost(pPlayer, pItem, nDifficulty, pQuestFlags, nVendorId, nTransactionType);
}
//D2Common.0x6FD9CE10 (#10794)
int __stdcall ITEMS_GetMaxStack(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwMaxStack;
}
//D2Common.0x6FD9CE50 (#10795)
int __stdcall ITEMS_GetTotalMaxStack(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
int nMaxStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nMaxStack >= 511)
{
nMaxStack = 511;
}
return nMaxStack;
}
//D2Common.0x6FD9CEF0 (#10798)
int __stdcall ITEMS_GetSpawnStackFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwSpawnStack;
}
//D2Common.0x6FD9CF30 (#10799)
int __stdcall ITEMS_GetSpawnStack(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetSpawnStackFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9CFB0 (#10796)
int __stdcall ITEMS_GetMinStackFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwMinStack;
}
//D2Common.0x6FD9CFF0 (#10797)
int __stdcall ITEMS_GetMinStack(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetMinStackFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9D070 (#10800) - Unused
int __stdcall ITEMS_CheckBitField1Flag8(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 8;
}
//D2Common.0x6FD9D0F0 (#10804)
int __stdcall ITEMS_GetSpellIcon(D2UnitStrc* pItem)
{
D2BooksTxt* pBooksTxtRecord = NULL;
uint16_t wBookId = 0;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL) || ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
wBookId = pItem->pItemData->wMagicSuffix[0];
}
else
{
wBookId = 0;
}
pBooksTxtRecord = DATATBLS_GetBooksTxtRecord(wBookId);
if (pBooksTxtRecord)
{
return pBooksTxtRecord->nSpellIcon;
}
else
{
return -1;
}
}
else
{
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nSpellIcon;
}
}
//D2Common.0x6FD9D1E0 (#10805)
uint8_t __stdcall ITEMS_GetDurWarnCount(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nDurWarning;
}
//D2Common.0x6FD9D260 (#10806)
uint8_t __stdcall ITEMS_GetQtyWarnCount(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nQuantityWarning;
}
//D2Common.0x6FD9D2E0 (#10807)
short __stdcall ITEMS_GetStrengthBonus(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->nStrBonus != 1)
{
return pItemsTxtRecord->nStrBonus;
}
}
return 100;
}
//D2Common.0x6FD9D310 (#10808)
short __stdcall ITEMS_GetDexBonus(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->nDexBonus != 1)
{
return pItemsTxtRecord->nDexBonus;
}
}
return 100;
}
//D2Common.0x6FD9D340 (#10809)
int __stdcall ITEMS_CheckIfSocketableByItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
if (pItemsTxtRecord)
{
return pItemsTxtRecord->nHasInv;
}
return 0;
}
//D2Common.0x6FD9D360 (#10810)
int __stdcall ITEMS_CheckIfSocketable(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_CheckIfSocketableByItemId(pItem->dwClassId);
}
return 0;
}
//D2Common.0x6FD9D390 (#10811)
BOOL __stdcall ITEMS_HasDurability(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && !pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem))
{
return STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0;
}
}
return FALSE;
}
//D2Common.0x6FD9D3F0 (#10813)
int __stdcall ITEMS_GetStaffMods(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nStaffMods;
}
}
}
return 7;
}
//D2Common.0x6FD9D470 (#10814)
uint8_t __stdcall ITEMS_GetAllowedGemSocketsFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
if (pItemsTxtRecord)
{
return pItemsTxtRecord->nGemSockets;
}
return 0;
}
//D2Common.0x6FD9D490 (#10815)
uint8_t __stdcall ITEMS_GetMaxSockets(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
uint8_t nMaxSockets = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
if (pItem->pItemData)
{
if (pItem->pItemData->dwItemLevel < 1)
{
pItem->pItemData->dwItemLevel = 1;
}
if (pItem->pItemData->dwItemLevel > 25)
{
if (pItem->pItemData->dwItemLevel > 40)
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
if (pItemsTxtRecord->nGemSockets < nMaxSockets)
{
return pItemsTxtRecord->nGemSockets;
}
else
{
return nMaxSockets;
}
}
}
}
return 0;
}
//D2Common.0x6FD9D580 (#10816)
int __stdcall ITEMS_GetSockets(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0);
}
//D2Common.0x6FD9D5E0 (#10817)
void __stdcall ITEMS_AddSockets(D2UnitStrc* pItem, int nSockets)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
uint32_t nQuality = 0;
int nCurrentSockets = 0;
int nMaxSockets = 0;
int nItemLevel = 0;
int nItemType = 0;
int nMaxSocks = 0;
uint8_t nGemSockets = 0;
uint8_t nHeight = 0;
uint8_t nWidth = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
nMaxSockets = 6;
nWidth = 0;
nHeight = 0;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
nWidth = pItemsTxtRecord->nInvWidth;
nHeight = pItemsTxtRecord->nInvHeight;
}
if (nWidth * nHeight <= 6)
{
nMaxSockets = nWidth * nHeight;
}
if (nWidth * nHeight)
{
if (pItem->pItemData)
{
nQuality = pItem->pItemData->dwQualityNo;
}
else
{
nQuality = ITEMQUAL_NORMAL;
}
switch (nQuality)
{
case ITEMQUAL_SET:
case ITEMQUAL_UNIQUE:
nCurrentSockets = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0);
if (nCurrentSockets <= 0)
{
if (nMaxSockets >= 1)
{
nMaxSockets = 1;
}
}
else
{
nSockets = nCurrentSockets;
}
break;
case ITEMQUAL_RARE:
if (nMaxSockets >= 2)
{
nMaxSockets = 2;
}
break;
case ITEMQUAL_MAGIC:
if (nMaxSockets >= 4)
{
nMaxSockets = 4;
}
break;
case ITEMQUAL_CRAFT:
case ITEMQUAL_TEMPERED:
if (nMaxSockets >= 3)
{
nMaxSockets = 3;
}
break;
default:
break;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
if (pItemsTxtRecord)
{
nGemSockets = pItemsTxtRecord->nGemSockets;
}
else
{
nGemSockets = 0;
}
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock1;
}
if (nGemSockets >= nMaxSocks)
{
nGemSockets = nMaxSocks;
}
}
}
if (nMaxSockets >= nGemSockets)
{
nMaxSockets = nGemSockets;
}
if (nSockets <= 1)
{
nSockets = 1;
}
if (nSockets >= nMaxSockets)
{
nSockets = nMaxSockets;
}
if (nSockets > 0)
{
if (pItem->pItemData)
{
pItem->pItemData->dwItemFlags |= IFLAG_SOCKETED;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_NUMSOCKETS, nSockets, 0);
}
}
}
}
//D2Common.0x6FD9D7C0 (#10818)
void __stdcall ITEMS_SetSockets(D2UnitStrc* pItem, int nSockets)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
int nMaxSockets = 0;
int nMaxSocks = 0;
int nItemLevel = 0;
int nItemType = 0;
uint8_t nAllowedSockets = 0;
uint8_t nWidth = 0;
uint8_t nHeight = 0;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
nMaxSockets = 6;
nWidth = 0;
nHeight = 0;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
nWidth = pItemsTxtRecord->nInvWidth;
nHeight = pItemsTxtRecord->nInvHeight;
}
if (nWidth * nHeight > 6)
{
if (nWidth * nHeight <= 6)
{
nMaxSockets = nWidth * nHeight;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
nAllowedSockets = ITEMS_GetAllowedGemSocketsFromItemId(pItem->dwClassId);
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSocks = pItemTypesTxtRecord->nMaxSock1;
}
if (nAllowedSockets >= nMaxSocks)
{
nAllowedSockets = nMaxSocks;
}
}
}
if (nMaxSockets >= nAllowedSockets)
{
nMaxSockets = nAllowedSockets;
}
if (nSockets <= 1)
{
nSockets = 1;
}
if (nSockets >= nMaxSockets)
{
nSockets = nMaxSockets;
}
if (pItem->pItemData)
{
pItem->pItemData->dwItemFlags |= IFLAG_SOCKETED;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_NUMSOCKETS, nSockets, 0);
}
}
}
//D2Common.0x6FD9D900 (#10819)
int __stdcall ITEMS_GetGemApplyTypeFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nGemApplyType;
}
//D2Common.0x6FD9D940 (#10820)
int __stdcall ITEMS_GetGemApplyType(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetGemApplyTypeFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9D9D0 (#10821)
BOOL __stdcall ITEMS_IsSocketFiller(D2UnitStrc* pItem)
{
return ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SOCKET_FILLER);
}
//D2Common.0x6FD9D9E0 (#10822)
const D2RunesTxt* __stdcall ITEMS_GetRunesTxtRecordFromItem(const D2UnitStrc* pItem)
{
if (!pItem)
{
return nullptr;
}
const bool isItemOfSpecialQuality = (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo >= ITEMQUAL_MAGIC && pItem->pItemData->dwQualityNo <= ITEMQUAL_TEMPERED);
// Note: The game specifically checks all the things above, which means we will enter the condition if dwUnitType == UNIT_ITEM
// While this is not really correct, this is what the game does, and it works because it expects the unit to be an item.
// and is using another function that checked if an item was special, which happened to check that the unit was indeed an item
if (isItemOfSpecialQuality)
{
return nullptr;
}
if (!DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->nQuest && pItem->pInventory)
{
int nSocketableIds[6] = {};
int nSocketedItems = 0;
for (D2UnitStrc* pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory); pInventoryItem && INVENTORY_UnitIsItem(pInventoryItem); pInventoryItem = INVENTORY_GetNextItem(pInventoryItem))
{
nSocketableIds[nSocketedItems] = pInventoryItem->dwClassId;
++nSocketedItems;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const int nSockets = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0);
if (nSockets != nSocketedItems)
{
return nullptr;
}
for (int i = 0; i < sgptDataTables->pRuneDataTables.nRunesTxtRecordCount; ++i)
{
const D2RunesTxt* pRunesTxtRecord = &sgptDataTables->pRuneDataTables.pRunesTxt[i];
if (pRunesTxtRecord->nComplete)
{
int nRuneCounter = 0;
bool bMatch = true;
while (nRuneCounter < 6 && pRunesTxtRecord->nRune[nRuneCounter] > 0)
{
if (nSocketedItems < nRuneCounter || nSocketableIds[nRuneCounter] != pRunesTxtRecord->nRune[nRuneCounter])
{
bMatch = false;
break;
}
++nRuneCounter;
}
if (bMatch)
{
// All runes are a match, now check if the item types correspond
bool isItemTypeExcluded = false;
for (int nETypeCounter = 0; nETypeCounter < 3 && pRunesTxtRecord->wEType[nETypeCounter]; ++nETypeCounter)
{
if (ITEMS_CheckItemTypeId(pItem, pRunesTxtRecord->wEType[nETypeCounter]))
{
isItemTypeExcluded = true;
break;
}
}
// Not an excluded type, check valid types
if (!isItemTypeExcluded)
{
for (int nITypeCounter = 0; nITypeCounter < 6 && pRunesTxtRecord->wIType[nITypeCounter]; ++nITypeCounter)
{
if (ITEMS_CheckItemTypeId(pItem, pRunesTxtRecord->wIType[nITypeCounter]))
{
return pRunesTxtRecord;
}
}
}
}
}
}
}
return nullptr;
}
static BOOL ITEMS_CheckTypeEquivalenceFromLUT(uint32_t* pEquivalenceLUT, uint32_t nItemType)
{
return pEquivalenceLUT[nItemType / 32] & gdwBitMasks[nItemType % 32];
}
static uint32_t* ITEMS_TypeEquivalenceLUT(int nItemTypeLUT)
{
return &sgptDataTables->pItemTypesEquivalenceLUTs[nItemTypeLUT * sgptDataTables->nItemTypesIndex];
}
//D2Common.0x6FD9DBA0 (#10729)
BOOL __stdcall ITEMS_CheckItemTypeIdByItemId(int nItemId, int nItemType)
{
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
if (ITEMS_CheckTypeEquivalenceFromLUT(ITEMS_TypeEquivalenceLUT(pItemsTxtRecord->wType[0]), nItemType))
{
return TRUE;
}
if (pItemsTxtRecord->wType[1] > 0 && pItemsTxtRecord->wType[1] < sgptDataTables->nItemTypesTxtRecordCount)
{
return ITEMS_CheckTypeEquivalenceFromLUT(ITEMS_TypeEquivalenceLUT(pItemsTxtRecord->wType[1]), nItemType);
}
}
}
return FALSE;
}
//D2Common.0x6FD9DC80 (#10730)
BOOL __stdcall ITEMS_CheckType(int nItemType1, int nItemType2)
{
if (nItemType1 >= 0 && nItemType1 < sgptDataTables->nItemTypesTxtRecordCount && nItemType2 >= 0 && nItemType2 < sgptDataTables->nItemTypesTxtRecordCount)
{
return ITEMS_CheckTypeEquivalenceFromLUT(ITEMS_TypeEquivalenceLUT(nItemType1), nItemType2);
}
return FALSE;
}
//D2Common.0x6FD9DCE0 (#10731)
BOOL __stdcall ITEMS_CheckItemTypeId(const D2UnitStrc* pItem, int nItemType)
{
if (pItem)
{
return ITEMS_CheckItemTypeIdByItemId(pItem->dwClassId, nItemType);
}
return FALSE;
}
//D2Common.0x6FD9DDD0 (#10803)
//TODO: Find a better name
int __stdcall ITEMS_CheckBitField1Flag1(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 1;
}
//D2Common.0x6FD9DE10 (#10802)
int __stdcall ITEMS_IsMetalItem(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 2;
}
//D2Common.0x6FD9DE50 (#10801) - Unused
int __stdcall ITEMS_CheckBitField1Flag4(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->dwBitField1 & 4;
}
//D2Common.0x6FD9DE90 (#10774)
BOOL __stdcall ITEMS_IsNotQuestItemByItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nQuest < 1 && pItemsTxtRecord->wType[0] != ITEMTYPE_QUEST;
}
//D2Common.0x6FD9DEE0 (#10732)
int __stdcall ITEMS_GetFileIndex(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
return pItem->pItemData->dwFileIndex;
}
//D2Common.0x6FD9DF60 (#10733)
void __stdcall ITEMS_SetFileIndex(D2UnitStrc* pItem, uint32_t dwFileIndex)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->dwFileIndex = dwFileIndex;
}
//D2Common.0x6FD9DFE0 (#11244)
void __stdcall ITEMS_GetRealmData(D2UnitStrc* pItem, int* pRealmData0, int* pRealmData1)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
*pRealmData0 = pItem->pItemData->dwRealmData[0];
*pRealmData1 = pItem->pItemData->dwRealmData[1];
}
else
{
*pRealmData0 = 0;
*pRealmData1 = 0;
}
}
//D2Common.0x6FD9E070 (#11245)
void __stdcall ITEMS_SetRealmData(D2UnitStrc* pItem, int a2, int a3)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->dwRealmData[0] = a2;
pItem->pItemData->dwRealmData[1] = a3;
}
}
//D2Common.0x6FD9E0A0 (#10734)
void __stdcall ITEMS_SetOwnerId(D2UnitStrc* pItem, int nOwnerGUID)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->dwOwnerGUID = nOwnerGUID;
}
//D2Common.0x6FD9E120 (#10735)
int __stdcall ITEMS_GetOwnerId(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
return pItem->pItemData->dwOwnerGUID;
}
//D2Common.0x6FD9E1A0 (#10736)
BOOL __stdcall ITEMS_IsBodyItem(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
if (pItemTypesTxtRecord->nBodyLoc1 || pItemTypesTxtRecord->nBodyLoc2)
{
return pItemTypesTxtRecord->nBody;
}
}
}
}
return FALSE;
}
//D2Common.0x6FD9E2A0 (#10738)
BOOL __stdcall ITEMS_IsClassValidByItemId(int nItemId)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord)
{
return pItemTypesTxtRecord->nClass < 7;
}
}
return FALSE;
}
//D2Common.0x6FD9E310 (#10737)
BOOL __stdcall ITEMS_IsClassValid(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
return ITEMS_IsClassValidByItemId(pItem->dwClassId);
}
return FALSE;
}
//D2Common.0x6FD9E390 (#10739)
int __stdcall ITEMS_GetClassOfClassSpecificItem(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] >= 0 && pItemsTxtRecord->wType[0] < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[pItemsTxtRecord->wType[0]];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nClass < 7)
{
return pItemTypesTxtRecord->nClass;
}
}
}
return 7;
}
//D2Common.0x6FD9E410 (#10823)
uint16_t __stdcall ITEMS_GetWeaponClassId(D2UnitStrc* pItem)
{
static const D2CompositStrc stru_6FDE3C08[8] =
{
{ ' wob', WEAPONCLASS_BOW },
{ ' sh1', WEAPONCLASS_1HS },
{ ' th1', WEAPONCLASS_1HT },
{ ' fts', WEAPONCLASS_STF },
{ ' sh2', WEAPONCLASS_2HS },
{ ' th2', WEAPONCLASS_2HT },
{ ' wbx', WEAPONCLASS_XBW },
{ ' 1th', WEAPONCLASS_HT1 },
};
D2ItemsTxt* pItemsTxtRecord = NULL;
int nCounter = 0;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem ? pItem->dwClassId : -1);
D2_ASSERT(pItemsTxtRecord);
while (pItemsTxtRecord->dwWeapClass != stru_6FDE3C08[nCounter].nWeaponClassCode)
{
++nCounter;
if (nCounter >= ARRAY_SIZE(stru_6FDE3C08))
{
return WEAPONCLASS_HTH;
}
}
return (uint16_t)stru_6FDE3C08[nCounter].nWeaponClassId;
}
//D2Common.0x6FD9E480 (#10824)
uint32_t __stdcall ITEMS_GetTransmogrifyFromItemId(int nItemId)
{
D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(nItemId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nTransmogrify != 0;
}
//D2Common.0x6FD9E4C0 (#10825)
uint32_t __stdcall ITEMS_GetTransmogrify(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return ITEMS_GetTransmogrifyFromItemId(pItem->dwClassId);
}
//D2Common.0x6FD9E550 (#10826)
int __stdcall ITEMS_IsMagSetRarUniCrfOrTmp(D2UnitStrc* pItem)
{
return pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo >= ITEMQUAL_MAGIC && pItem->pItemData->dwQualityNo <= ITEMQUAL_TEMPERED;
}
//D2Common.0x6FD9E580 (#10740)
BOOL __stdcall ITEMS_IsNotQuestItem(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
int nItemId = 0;
if (pItem)
{
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_NOSELL)
{
return FALSE;
}
nItemId = pItem->dwClassId;
}
else
{
nItemId = -1;
}
return ITEMS_IsNotQuestItemByItemId(nItemId);
}
//D2Common.0x6FD9E5F0 (#10827)
uint8_t __stdcall ITEMS_GetHitClassFromItem(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
return pItemsTxtRecord->nHitClass;
}
//D2Common.0x6FD9E670 (#10828)
int __stdcall ITEMS_Is1Or2Handed(D2UnitStrc* pPlayer, D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2_ASSERT(pItem);
D2_ASSERT(pPlayer);
if (pPlayer->dwUnitType || pPlayer->dwClassId != PCLASS_BARBARIAN)
{
return FALSE;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (!pItemsTxtRecord->n1or2Handed)
{
return FALSE;
}
return TRUE;
}
//D2Common.0x6FD9E710 (#10829)
uint8_t* __stdcall ITEMS_GetColor(D2UnitStrc* pPlayer, D2UnitStrc* pItem, uint8_t* pColor, int nTransType)
{
D2UniqueItemsTxt* pUniqueItemsTxtRecord = NULL;
D2MagicAffixTxt* pMagicAffixTxtRecord = NULL;
D2MagicAffixTxt* pAutoAffixTxtRecord = NULL;
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2ItemsTxt* pGemItemsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2StatesTxt* pStatesTxtRecord = NULL;
D2GemsTxt* pGemsTxtRecord = NULL;
D2UnitStrc* pInventoryItem = NULL;
int nItemQuality = 0;
int nGemSockets = 0;
int nMaxSockets = 0;
int nItemLevel = 0;
int nItemType = 0;
int nCounter = 0;
uint16_t nAutoAffix = 0;
if (!pItem)
{
return NULL;
}
if (pPlayer)
{
for (int i = 0; i < sgptDataTables->nColourStates; ++i)
{
if (STATES_CheckState(pPlayer, sgptDataTables->pColourStates[i]) && sgptDataTables->pColourStates[i] >= 0 && sgptDataTables->pColourStates[i] < sgptDataTables->nStatesTxtRecordCount)
{
pStatesTxtRecord = &sgptDataTables->pStatesTxt[sgptDataTables->pColourStates[i]];
if (pStatesTxtRecord && pStatesTxtRecord->nItemTrans < 21 && ITEMS_CheckItemTypeId(pItem, pStatesTxtRecord->wItemType))
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord)
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pStatesTxtRecord->nItemTrans);
}
}
}
}
}
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
nItemQuality = pItem->pItemData->dwQualityNo;
}
else
{
nItemQuality = ITEMQUAL_NORMAL;
}
switch (nItemQuality)
{
case ITEMQUAL_MAGIC:
case ITEMQUAL_RARE:
nCounter = 0;
do
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->dwUnitType == UNIT_ITEM && pItem->pItemData ? pItem->pItemData->wMagicSuffix[nCounter] : 0);
if (pMagicAffixTxtRecord && pMagicAffixTxtRecord->nTransformColor != -1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pMagicAffixTxtRecord->nTransformColor >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pMagicAffixTxtRecord->nTransformColor & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pMagicAffixTxtRecord->nTransformColor);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pMagicAffixTxtRecord->nTransformColor);
}
}
++nCounter;
}
while (nCounter < 3);
nCounter = 0;
do
{
pMagicAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(pItem->dwUnitType == UNIT_ITEM && pItem->pItemData ? pItem->pItemData->wMagicPrefix[nCounter] : 0);
if (pMagicAffixTxtRecord && pMagicAffixTxtRecord->nTransformColor != -1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pMagicAffixTxtRecord->nTransformColor >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pMagicAffixTxtRecord->nTransformColor & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pMagicAffixTxtRecord->nTransformColor);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pMagicAffixTxtRecord->nTransformColor);
}
}
++nCounter;
}
while (nCounter < 3);
break;
case ITEMQUAL_UNIQUE:
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return NULL;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nUniqueItemsTxtRecordCount)
{
pUniqueItemsTxtRecord = &sgptDataTables->pUniqueItemsTxt[pItem->pItemData->dwFileIndex];
if (pUniqueItemsTxtRecord)
{
if (nTransType)
{
if (pUniqueItemsTxtRecord->nInvTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pUniqueItemsTxtRecord->nChrTransform < 0 || pUniqueItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pUniqueItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pUniqueItemsTxtRecord->nInvTransform);
}
}
else
{
if (pUniqueItemsTxtRecord->nChrTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pUniqueItemsTxtRecord->nChrTransform < 0 || pUniqueItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pUniqueItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pUniqueItemsTxtRecord->nChrTransform);
}
}
}
}
return NULL;
case ITEMQUAL_SET:
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return NULL;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[pItem->pItemData->dwFileIndex];
if (pSetItemsTxtRecord)
{
if (nTransType)
{
if (pSetItemsTxtRecord->nInvTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pSetItemsTxtRecord->nChrTransform < 0 || pSetItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pSetItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pSetItemsTxtRecord->nInvTransform);
}
}
else
{
if (pSetItemsTxtRecord->nChrTransform >= 0)
{
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pSetItemsTxtRecord->nChrTransform < 0 || pSetItemsTxtRecord->nChrTransform >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pSetItemsTxtRecord->nChrTransform & 31) + 32 * pItemsTxtRecord->nTransform;
}
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pSetItemsTxtRecord->nChrTransform);
}
}
}
}
return NULL;
default:
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->nHasInv)
{
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord)
{
nGemSockets = ITEMS_GetAllowedGemSocketsFromItemId(pItem->dwClassId);
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
if (nGemSockets >= nMaxSockets)
{
nGemSockets = nMaxSockets;
}
if (nGemSockets && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)
{
pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory);
if (pInventoryItem && INVENTORY_UnitIsItem(pInventoryItem) && ITEMS_CheckItemTypeId(pInventoryItem, ITEMTYPE_GEM))
{
pGemItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pInventoryItem->dwClassId);
D2_ASSERT(pGemItemsTxtRecord);
pGemsTxtRecord = DATATBLS_GetGemsTxtRecord(pGemItemsTxtRecord->dwGemOffset);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pGemsTxtRecord->nTransForm >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pGemsTxtRecord->nTransForm & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pGemsTxtRecord->nTransForm);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pGemsTxtRecord->nTransForm);
}
}
}
}
}
}
}
break;
}
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
nAutoAffix = pItem->pItemData->wAutoAffix;
}
pAutoAffixTxtRecord = DATATBLS_GetMagicAffixTxtRecord(nAutoAffix);
if (pAutoAffixTxtRecord && pAutoAffixTxtRecord->nTransformColor != -1)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord->nTransform <= 0 || pItemsTxtRecord->nTransform >= 9 || pAutoAffixTxtRecord->nTransformColor >= 21)
{
*pColor = 0;
}
else
{
*pColor = (pAutoAffixTxtRecord->nTransformColor & 31) + 32 * pItemsTxtRecord->nTransform;
}
if (nTransType)
{
return D2CMP_MixPalette(pItemsTxtRecord->nInvTrans, pAutoAffixTxtRecord->nTransformColor);
}
else
{
return D2CMP_MixPalette(pItemsTxtRecord->nTransform, pAutoAffixTxtRecord->nTransformColor);
}
}
return NULL;
}
//D2Common.0x6FD9EE70
D2SetItemsTxt* __fastcall ITEMS_GetSetItemsTxtRecord(int nRecordId)
{
if (nRecordId >= 0 && nRecordId < sgptDataTables->nSetItemsTxtRecordCount)
{
return &sgptDataTables->pSetItemsTxt[nRecordId];
}
return NULL;
}
//D2Common.0x6FD9EEA0 (#10830)
BOOL __stdcall ITEMS_IsImbueable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2UnitStrc* pInventoryItem = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && pItemsTxtRecord->wType[0] != ITEMTYPE_GOLD)
{
if (!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_NOSELL))
{
if (pItemsTxtRecord->dwBitField1 & 1)
{
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(ITEMS_GetItemTypeFromItemId(pItem->dwClassId));
if (pItem->dwFlagEx & UNITFLAGEX_ISEXPANSION || !pItemTypesTxtRecord || !pItemTypesTxtRecord->nThrowable)
{
if (!pItemsTxtRecord->nQuest || pItemsTxtRecord->dwCode == ' gel')
{
pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory);
if (pInventoryItem)
{
while (!INVENTORY_UnitIsItem(pInventoryItem))
{
pInventoryItem = INVENTORY_GetNextItem(pInventoryItem);
if (!pInventoryItem)
{
if ((!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)) && (!pItem->pItemData || (pItem->pItemData->dwQualityNo >= 4 && pItem->pItemData->dwQualityNo <= 9)))
{
return TRUE;
}
break;
}
}
}
else
{
if ((!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)) && (!pItem->pItemData || (pItem->pItemData->dwQualityNo >= 4 && pItem->pItemData->dwQualityNo <= 9)))
{
return TRUE;
}
}
}
}
}
}
}
}
return FALSE;
}
//D2Common.0x6FD9F080 (#10832)
BOOL __stdcall ITEMS_IsPersonalizable(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2_ASSERT(pItem);
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] == ITEMTYPE_GOLD || pItemsTxtRecord->wType[0] == ITEMTYPE_BOW_QUIVER
|| pItemsTxtRecord->wType[0] == ITEMTYPE_CROSSBOW_QUIVER || pItemsTxtRecord->wType[0] == ITEMTYPE_PLAYER_BODY_PART)
{
return FALSE;
}
if (pItem->pItemData && (pItem->pItemData->dwItemFlags & IFLAG_NOSELL || pItem->pItemData->dwItemFlags & IFLAG_BROKEN))
{
return FALSE;
}
if (!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_PERSONALIZED))
{
if (!pItemsTxtRecord->nCompactSave)
{
return pItemsTxtRecord->nNameable != 0;
}
}
}
return FALSE;
}
//D2Common.0x6FD9F260 (#10831)
BOOL __stdcall ITEMS_IsSocketable(D2UnitStrc* pItem)
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2UnitStrc* pSocket = NULL;
uint8_t nAllowedSockets = 0;
int nMaxSockets = 0;
int nItemLevel = 0;
int nItemType = 0;
D2_ASSERT(pItem);
if (pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->wType[0] == ITEMTYPE_GOLD)
{
return FALSE;
}
if (pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_NOSELL)
{
return FALSE;
}
}
if (DATATBLS_GetItemsTxtRecord(pItem->dwClassId)->nQuest)
{
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (pItemsTxtRecord->dwCode != ' gel')
{
return FALSE;
}
}
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_BROKEN)
{
return FALSE;
}
pSocket = INVENTORY_GetFirstItem(pItem->pInventory);
if (pSocket)
{
while (!INVENTORY_UnitIsItem(pSocket))
{
pSocket = INVENTORY_GetNextItem(pSocket);
if (!pSocket)
{
break;
}
}
if (pSocket)
{
return FALSE;
}
}
if (pItem->dwUnitType != UNIT_ITEM || pItem->pItemData && pItem->pItemData->dwItemFlags & IFLAG_SOCKETED)
{
return FALSE;
}
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
if (nItemType < 0 || nItemType >= sgptDataTables->nItemTypesTxtRecordCount)
{
return FALSE;
}
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (!pItemTypesTxtRecord)
{
return FALSE;
}
nAllowedSockets = ITEMS_GetAllowedGemSocketsFromItemId(pItem->dwClassId);
nItemLevel = ITEMS_GetItemLevel(pItem);
if (nItemLevel > 25)
{
if (nItemLevel > 40)
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock40;
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock25;
}
}
else
{
nMaxSockets = pItemTypesTxtRecord->nMaxSock1;
}
if (nAllowedSockets >= nMaxSockets)
{
nAllowedSockets = nMaxSockets;
}
if (!nAllowedSockets)
{
return 0;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
return STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_NUMSOCKETS, 0) == 0;
}
//D2Common.0x6FD9F490 (#10877)
int __stdcall ITEMS_GetAllRepairCosts(D2GameStrc* pGame, D2UnitStrc* pUnit, int nNpcId, int nDifficulty, D2BitBufferStrc* pQuestFlags, void(__fastcall* pfCallback)(D2GameStrc*, D2UnitStrc*, D2UnitStrc*))
{
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2UnitStrc* pItem = NULL;
BOOL bCanBeRepaired = FALSE;
int nMaxDurability = 0;
int nRepairCosts = 0;
int nItemType = 0;
int nMaxStack = 0;
int nCounter = 0;
int nBodyLoc = 0;
int nStats = 0;
D2StatStrc pStat[64] = {};
if (!pUnit || !pUnit->pInventory)
{
return 0;
}
while (nBodyLoc < 13)
{
pItem = INVENTORY_GetItemFromBodyLoc(pUnit->pInventory, nBodyLoc);
if (pItem)
{
bCanBeRepaired = FALSE;
if (ITEMS_IsRepairable(pItem) && pItem->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (pItemsTxtRecord && !pItemsTxtRecord->nNoDurability && pItemsTxtRecord->nDurability && STATLIST_GetMaxDurabilityFromUnit(pItem) && STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_INDESCTRUCTIBLE, 0) <= 0)
{
nMaxDurability = STATLIST_GetMaxDurabilityFromUnit(pItem);
if (nMaxDurability && STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) != nMaxDurability)
{
bCanBeRepaired = TRUE;
}
}
}
if (pItem->dwUnitType == UNIT_ITEM)
{
nItemType = ITEMS_GetItemTypeFromItemId(pItem->dwClassId);
}
else
{
nItemType = 0;
}
if (nItemType >= 0 && nItemType < sgptDataTables->nItemTypesTxtRecordCount)
{
pItemTypesTxtRecord = &sgptDataTables->pItemTypesTxt[nItemType];
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nRepair && pItem->dwUnitType == UNIT_ITEM && ITEMS_CheckItemTypeIfThrowable(ITEMS_GetItemType(pItem)))
{
if (ITEMS_CheckIfStackable(pItem) && !ITEMS_CheckItemFlag(pItem, IFLAG_ETHEREAL, __LINE__, __FILE__))
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
nMaxStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nMaxStack >= 511)
{
nMaxStack = 511;
}
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0) < nMaxStack)
{
bCanBeRepaired = TRUE;
}
}
}
}
nStats = D2Common_11270(pItem, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats <= 0)
{
if (bCanBeRepaired)
{
nRepairCosts += ITEMS_CalculateTransactionCost(pUnit, pItem, nDifficulty, pQuestFlags, nNpcId, 3);
if (pfCallback)
{
pfCallback(pGame, pItem, pUnit);
}
}
}
else
{
nCounter = 0;
while ((uint8_t)pStat[nCounter].nValue >= pStat[nCounter].nValue >> 8)
{
++nCounter;
if (nCounter >= nStats)
{
if (bCanBeRepaired)
{
nRepairCosts += ITEMS_CalculateTransactionCost(pUnit, pItem, nDifficulty, pQuestFlags, nNpcId, 3);
if (pfCallback)
{
pfCallback(pGame, pItem, pUnit);
}
}
break;
}
}
}
}
++nBodyLoc;
}
return nRepairCosts;
}
//D2Common.0x6FD9F720 (#10833)
BOOL __stdcall ITEMS_AreStackablesEqual(D2UnitStrc* pItem1, D2UnitStrc* pItem2)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
if (!pItem1 || pItem1->dwUnitType != UNIT_ITEM || !pItem1->pItemData || !pItem2 || pItem2->dwUnitType != UNIT_ITEM || !pItem2->pItemData)
{
return FALSE;
}
if (pItem1->dwClassId != pItem2->dwClassId || pItem1->pItemData->dwQualityNo != pItem2->pItemData->dwQualityNo || pItem1->pItemData->dwFileIndex != pItem2->pItemData->dwFileIndex)
{
return FALSE;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem1->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (!pItemsTxtRecord->nStackable)
{
return FALSE;
}
if((ITEMS_CheckItemFlag(pItem1, IFLAG_ETHEREAL, __LINE__, __FILE__) != ITEMS_CheckItemFlag(pItem2, IFLAG_ETHEREAL, __LINE__, __FILE__))
|| !pItem1->pItemData->dwQualityNo || pItem1->pItemData->dwQualityNo > 3 && pItem1->pItemData->dwQualityNo <= 9
|| !pItem2->pItemData->dwQualityNo || pItem2->pItemData->dwQualityNo > 3 && pItem2->pItemData->dwQualityNo <= 9
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_MINDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_MINDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_MAXDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_MAXDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_SECONDARY_MINDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_SECONDARY_MINDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_SECONDARY_MAXDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_SECONDARY_MAXDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_ITEM_THROW_MINDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_ITEM_THROW_MINDAMAGE, 0)
|| STATLIST_GetUnitStatUnsigned(pItem1, STAT_ITEM_THROW_MAXDAMAGE, 0) != STATLIST_GetUnitStatUnsigned(pItem2, STAT_ITEM_THROW_MAXDAMAGE, 0))
{
return FALSE;
}
if (STATLIST_GetUnitStatUnsigned(pItem1, STAT_ITEM_NUMSOCKETS, 0) || STATLIST_GetUnitStatUnsigned(pItem2, STAT_ITEM_NUMSOCKETS, 0))
{
return FALSE;
}
else
{
return TRUE;
}
}
//D2Common.0x6FD9FA70 (#10834)
BOOL __stdcall ITEMS_CanItemBeUsedForThrowSkill(D2UnitStrc* pItem)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
int nStack = 0;
if (pItem)
{
if (STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0) > 0)
{
return TRUE;
}
if (STATLIST_GetUnitStatSigned(pItem, STAT_ITEM_THROWABLE, 0))
{
STATLIST_SetUnitStat(pItem, STAT_QUANTITY, 0, 0);
return TRUE;
}
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
nStack = STATLIST_GetUnitStatUnsigned(pItem, STAT_ITEM_EXTRA_STACK, 0) + pItemsTxtRecord->dwMaxStack;
if (nStack < 511 && nStack <= 0)
{
return TRUE;
}
}
return FALSE;
}
//D2Common.0x6FD9FB40 (#11079)
int __stdcall D2COMMON_11079_Return0(int a1, int a2)
{
REMOVE_LATER_WriteToLogFile("D2COMMON_11079_Return0: Useless");
return 0;
}
//D2Common.0x6FD9FB50 (#10836)
uint32_t __stdcall ITEMS_GetSetItemsMask(D2UnitStrc* pPlayer, D2UnitStrc* pSetItem, BOOL bSkipItem)
{
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
uint32_t nSetItemMask = 0;
int nFileIndex = 0;
if (!pPlayer || !pSetItem || pSetItem->dwUnitType != UNIT_ITEM || !pSetItem->pItemData || pSetItem->pItemData->dwQualityNo != ITEMQUAL_SET || !pPlayer->pInventory)
{
return 0;
}
nFileIndex = pSetItem->pItemData->dwFileIndex;
if (nFileIndex >= 0 && nFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nFileIndex];
if (pSetItemsTxtRecord && pSetItemsTxtRecord->nSetId >= 0 && pSetItemsTxtRecord->nSetId < sgptDataTables->nSetsTxtRecordCount && &sgptDataTables->pSetsTxt[pSetItemsTxtRecord->nSetId])
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pPlayer->pInventory); i; i = INVENTORY_GetNextItem(i))
{
if (INVENTORY_GetItemNodePage(i) == 3)
{
if (INVENTORY_UnitIsItem(i) && (bSkipItem || i != pSetItem))
{
pItemData = i->pItemData;
if (pItemData && pItemData->dwQualityNo == ITEMQUAL_SET && !(pItemData->dwItemFlags & IFLAG_NOEQUIP) && !(pItemData->dwItemFlags & IFLAG_BROKEN))
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex >= 0 && nFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nFileIndex];
if (pSetItemsTxtRecord && pSetItemsTxtRecord->nSetId == pSetItemsTxtRecord->nSetId)
{
nSetItemMask |= 1 << LOBYTE(pSetItemsTxtRecord->nSetItems);
}
}
}
}
}
}
return nSetItemMask;
}
}
return 0;
}
//D2Common.0x6FD9FD80 (#10838)
D2SetItemsTxt* __stdcall ITEMS_GetSetItemsTxtRecordFromItem(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo == ITEMQUAL_SET)
{
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
return &sgptDataTables->pSetItemsTxt[pItem->pItemData->dwFileIndex];
}
}
return NULL;
}
//D2Common.0x6FD9FE20 (#10839)
BOOL __stdcall ITEMS_CanBeEquipped(D2UnitStrc* pItem)
{
if (pItem)
{
if (pItem->dwUnitType != UNIT_ITEM || !pItem->pItemData)
{
return TRUE;
}
return (!(pItem->pItemData->dwItemFlags & IFLAG_BROKEN) && !(pItem->pItemData->dwItemFlags & IFLAG_NOEQUIP));
}
return FALSE;
}
//D2Common.0x6FD9FE70 (#10840)
BOOL __stdcall ITEMS_IsCharmUsable(D2UnitStrc* pItem, D2UnitStrc* pPlayer)
{
if (!pItem || pItem->dwUnitType == UNIT_ITEM && (pItem->pItemData && (pItem->pItemData->dwItemFlags & IFLAG_BROKEN || pItem->pItemData->dwItemFlags & IFLAG_NOEQUIP)))
{
return FALSE;
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_CHARM))
{
if (pItem->dwUnitType == UNIT_ITEM && pItem->pItemData->nInvPage == INVPAGE_INVENTORY)
{
return ITEMS_CheckRequirements(pItem, pPlayer, FALSE, NULL, NULL, NULL) != 0;
}
}
return FALSE;
}
//D2Common.0x6FD9FF00 (#10776)
int __stdcall ITEMS_GetNoOfUnidItems(D2UnitStrc* pUnit)
{
D2UnitStrc* pItem = NULL;
int nUnidItems = 0;
int nNodePage = 0;
pItem = INVENTORY_GetFirstItem(pUnit->pInventory);
if (pItem)
{
nUnidItems = 0;
while (INVENTORY_UnitIsItem(pItem))
{
if (!pItem->pItemData || !(pItem->pItemData->dwItemFlags & IFLAG_IDENTIFIED))
{
nNodePage = INVENTORY_GetItemNodePage(pItem);
if (nNodePage != 1)
{
if (nNodePage == 3)
{
++nUnidItems;
}
}
else
{
if (pItem->pItemData && (pItem->pItemData->nInvPage == INVPAGE_CUBE || pItem->pItemData->nInvPage == INVPAGE_INVENTORY))
{
++nUnidItems;
}
}
}
pItem = INVENTORY_GetNextItem(pItem);
if (!pItem)
{
return nUnidItems;
}
}
}
return 0;
}
//D2Common.0x6FD9FF90 (#10841)
int __stdcall ITEMS_GetBonusLifeBasedOnClass(D2UnitStrc* pPlayer, int nValue)
{
if (!pPlayer || pPlayer->dwUnitType != UNIT_PLAYER)
{
return 2 * nValue;
}
else
{
switch (pPlayer->dwClassId)
{
case PCLASS_AMAZON:
case PCLASS_PALADIN:
case PCLASS_ASSASSIN:
return nValue + (nValue >> 1);
case PCLASS_BARBARIAN:
return 2 * nValue;
default:
return nValue;
}
}
}
//D2Common.0x6FD9FFE0 (#10842)
int __stdcall ITEMS_GetBonusManaBasedOnClass(D2UnitStrc* pPlayer, int nValue)
{
if (pPlayer && pPlayer->dwUnitType == UNIT_PLAYER)
{
switch (pPlayer->dwClassId)
{
case PCLASS_SORCERESS:
case PCLASS_NECROMANCER:
case PCLASS_DRUID:
return 2 * nValue;
case PCLASS_AMAZON:
case PCLASS_PALADIN:
case PCLASS_ASSASSIN:
return nValue + (nValue >> 1);
default:
return nValue;
}
}
return nValue;
}
//D2Common.0x6FDA0030 (#10875)
uint16_t __stdcall ITEMS_GetItemFormat(D2UnitStrc* pItem)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
return pItem->pItemData->wItemFormat;
}
//D2Common.0x6FDA00B0 (#10876)
void __stdcall ITEMS_SetItemFormat(D2UnitStrc* pItem, uint16_t nItemFormat)
{
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
D2_ASSERT(pItem->pItemData);
pItem->pItemData->wItemFormat = nItemFormat;
}
//D2Common.0x6FDA0130 (#10878)
int __stdcall ITEMS_GetWeaponAttackSpeed(D2UnitStrc* pUnit, D2UnitStrc* pWeapon)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
int nWeaponClass = 0;
int v11 = 0;
int v13 = 0;
char szPath[8] = {};
int nLength = 0;
D2_ASSERT(pWeapon && pWeapon->dwUnitType == UNIT_ITEM);
D2_ASSERT(ITEMS_CheckItemTypeId(pWeapon, ITEMTYPE_WEAPON));
D2_ASSERT(pUnit);
if (pWeapon->dwUnitType == UNIT_ITEM)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pWeapon->dwClassId);
if (pItemsTxtRecord)
{
nWeaponClass = pItemsTxtRecord->dwWeapClass;
}
}
D2Common_10884_COMPOSIT_unk(pUnit, pUnit->dwClassId, PLRMODE_ATTACK1, pUnit->dwUnitType, pUnit->pInventory, szPath, &nWeaponClass, 0, 0);
if (D2Common_10641(szPath, &nLength, &v11, &v13))
{
D2_ASSERT(nLength);
return (nLength << 8) / (v11 * (STATLIST_GetUnitStatUnsigned(pWeapon, STAT_ATTACKRATE, 0) + STATLIST_GetUnitStatSigned(pWeapon, STAT_ITEM_FASTERATTACKRATE, 0) + 100) / 100);
}
return 45;
}
//D2Common.0x6FDA02B0 (#10879)
int __stdcall ITEMS_HasUsedCharges(D2UnitStrc* pItem, BOOL* pHasChargedSkills)
{
D2StatStrc pStat[64] = {};
int nCounter = 0;
int nStats = 0;
if (pHasChargedSkills)
{
*pHasChargedSkills = TRUE;
}
nStats = D2Common_11270(pItem, STAT_ITEM_CHARGED_SKILL, pStat, ARRAY_SIZE(pStat));
if (nStats <= 0)
{
return FALSE;
}
else
{
if (pHasChargedSkills)
{
nCounter = 0;
if (nStats > 0)
{
while ((uint8_t)pStat[nCounter].nValue >= (pStat[nCounter].nValue >> 8))
{
++nCounter;
if (nCounter >= nStats)
{
return TRUE;
}
}
*pHasChargedSkills = FALSE;
}
}
return TRUE;
}
}
//D2Common.0x6FDA0340 (#10880)
BOOL __stdcall ITEMS_IsEthereal(D2UnitStrc* pItem)
{
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
return pItem->pItemData->dwItemFlags & IFLAG_ETHEREAL;
}
return 0;
}
//D2Common.0x6FDA0370 (#10883)
BOOL __stdcall ITEMS_GetCompactItemDataFromBitstream(uint8_t* pBitstream, size_t nSize, BOOL bCheckForHeader, D2ItemSaveStrc* pItemSave)
{
D2BitBufferStrc pBuffer = {};
int dwCode = 0;
BITMANIP_Initialize(&pBuffer, pBitstream, nSize);
if (bCheckForHeader && BITMANIP_ReadSigned(&pBuffer, 16) != 'MJ')
{
return FALSE;
}
else
{
pItemSave->dwFlags = BITMANIP_Read(&pBuffer, 32);
BITMANIP_Read(&pBuffer, 10);
pItemSave->nAnimMode = (uint8_t)BITMANIP_Read(&pBuffer, 3);
if (pItemSave->nAnimMode == IMODE_ONGROUND || pItemSave->nAnimMode == IMODE_DROPPING)
{
pItemSave->nX = (uint16_t)BITMANIP_Read(&pBuffer, 16);
pItemSave->nY = (uint16_t)BITMANIP_Read(&pBuffer, 16);
}
else
{
pItemSave->nBodyloc = (uint8_t)BITMANIP_Read(&pBuffer, 4);
pItemSave->nX = (uint16_t)BITMANIP_Read(&pBuffer, 4);
pItemSave->nY = (uint16_t)BITMANIP_Read(&pBuffer, 4);
pItemSave->nStorePage = (uint8_t)BITMANIP_Read(&pBuffer, 3) - 1;
}
if (pItemSave->dwFlags & IFLAG_ISEAR)
{
dwCode = ' rae';
}
else
{
dwCode = BITMANIP_Read(&pBuffer, 32);
}
pItemSave->nClassId = DATATBLS_GetItemIdFromItemCode(dwCode);
if (!(pItemSave->dwFlags & (IFLAG_LOWQUALITY | IFLAG_COMPACTSAVE)))
{
pItemSave->nItemFileIndex = BITMANIP_Read(&pBuffer, 3);
}
else
{
pItemSave->nItemFileIndex = 0;
}
return TRUE;
}
}
//D2Common.0x6FDA0490 (#10882)
size_t __stdcall ITEMS_DecodeItemFromBitstream(D2UnitStrc* pItem, uint8_t* pBitstream, size_t nSize, BOOL bCheckForHeader, int* pSocketedItemCount, uint32_t dwVersion, BOOL* pFail)
{
D2BitBufferStrc pBuffer = {};
uint32_t dwFlags = 0;
BOOL bGamble = FALSE;
BITMANIP_Initialize(&pBuffer, pBitstream, nSize);
if (bCheckForHeader && BITMANIP_ReadSigned(&pBuffer, 16) != 'MJ')
{
*pFail = TRUE;
return 0;
}
*pFail = FALSE;
dwFlags = BITMANIP_Read(&pBuffer, 32);
if (dwFlags & IFLAG_LOWQUALITY)
{
bGamble = TRUE;
dwFlags &= ~IFLAG_LOWQUALITY;
}
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData)
{
pItem->pItemData->dwItemFlags = dwFlags;
pItem->pItemData->dwItemFlags &= ~IFLAG_INIT;
pItem->pItemData->dwItemLevel = 1;
for (int i = 0; i < 3; ++i)
{
pItem->pItemData->wMagicPrefix[i] = 0;
pItem->pItemData->wMagicSuffix[i] = 0;
}
pItem->pItemData->wRarePrefix = 0;
pItem->pItemData->wRareSuffix = 0;
}
if (dwFlags & IFLAG_COMPACTSAVE)
{
if (pSocketedItemCount)
{
*pSocketedItemCount = 0;
}
if (ITEMS_DecodeItemBitstreamCompact(pItem, &pBuffer, bCheckForHeader, dwVersion) <= 0)
{
*pFail = TRUE;
}
}
else
{
if (ITEMS_DecodeItemBitstreamComplete(pItem, &pBuffer, bCheckForHeader, bGamble, pSocketedItemCount, dwVersion) <= 0)
{
*pFail = TRUE;
}
}
return BITMANIP_GetSize(&pBuffer);
}
//D2Common.0x6FDA0620
int __fastcall ITEMS_DecodeItemBitstreamCompact(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bCheckForHeader, uint32_t dwVersion)
{
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
D2StatListStrc* pStatList = NULL;
int nBits = 0;
int nItemId = 0;
int nValue = 0;
uint32_t dwCode = 0;
char szChar = 0;
uint8_t nAnimMode = 0;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemData = pItem->pItemData;
D2_ASSERT(pItemData);
pItemData->wItemFormat = (uint16_t)BITMANIP_Read(pBuffer, 10);
nAnimMode = (uint8_t)BITMANIP_Read(pBuffer, 3);
if (nAnimMode == IMODE_ONGROUND || nAnimMode == IMODE_DROPPING)
{
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
}
else
{
pItemData->nBodyLoc = (uint8_t)BITMANIP_Read(pBuffer, 4);
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
pItemData->nInvPage = (uint8_t)BITMANIP_Read(pBuffer, 3) - 1;
}
UNITS_ChangeAnimMode(pItem, nAnimMode);
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 3);
pItemData->nEarLvl = (uint8_t)BITMANIP_Read(pBuffer, 7);
int i = 0;
do
{
szChar = (char)BITMANIP_Read(pBuffer, 7);
pItemData->szPlayerName[i] = szChar;
++i;
}
while (szChar);
}
else
{
dwCode = BITMANIP_Read(pBuffer, 32);
pItem->dwClassId = DATATBLS_GetItemIdFromItemCode(dwCode);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
if (BITMANIP_Read(pBuffer, 1))
{
nBits = 32;
}
else
{
nBits = 12;
}
STATLIST_SetUnitStat(pItem, STAT_GOLD, BITMANIP_Read(pBuffer, nBits), 0);
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL))
{
if (dwCode == ' cst')
{
pItemData->wMagicSuffix[0] = 0;
}
else if (dwCode == ' csi')
{
pItemData->wMagicSuffix[0] = 1;
}
}
}
if (dwVersion > 92)
{
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
pItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwCode, &nItemId);
if (!pItemsTxtRecord)
{
return -1;
}
if (pItemsTxtRecord->nQuest && pItemsTxtRecord->nQuestDiffCheck)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_QUESTITEMDIFFICULTY);
nValue = (BITMANIP_Read(pBuffer, pItemStatCostTxtRecord->nSaveBits) - pItemStatCostTxtRecord->dwSaveAdd) << pItemStatCostTxtRecord->nValShift;
pStatList = STATLIST_GetStatListFromUnitStateOrFlag(pItem, STATE_NONE, 0x40);
if (!pStatList)
{
pStatList = STATLIST_AllocStatList(pItem->pMemoryPool, 0x40, 0, UNIT_ITEM, pItem->dwUnitId);
D2COMMON_10475_PostStatToStatList(pItem, pStatList, 1);
}
if (pStatList)
{
STATLIST_SetStat(pStatList, STAT_QUESTITEMDIFFICULTY, nValue, 0);
}
}
}
if (bCheckForHeader && dwVersion > 86 && BITMANIP_Read(pBuffer, 1))
{
pItemData->dwRealmData[0] = BITMANIP_Read(pBuffer, 32);
pItemData->dwRealmData[1] = BITMANIP_Read(pBuffer, 32);
if (dwVersion > 93)
{
BITMANIP_Read(pBuffer, 32);
}
}
pItem->dwInitSeed = 0;
SEED_InitLowSeed(&pItem->pSeed, 0);
pItemData->dwItemLevel = 1;
pItemData->dwQualityNo = ITEMQUAL_NORMAL;
return 1;
}
//D2Common.0x6FDA0A20
int __fastcall ITEMS_DecodeItemBitstreamComplete(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bCheckForHeader, BOOL bGamble, int* pSocketedItems, uint32_t dwVersion)
{
static const int gnItemSetStates[] =
{
STATE_ITEMSET1, STATE_ITEMSET2, STATE_ITEMSET3, STATE_ITEMSET4, STATE_ITEMSET5
};
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2MagicAffixDataTbl* pMagicAffixDataTbl = NULL;
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2SkillsTxt* pSkillsTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2SetsTxt* pSetsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
D2StatListStrc* pStatList = NULL;
char* szName = NULL;
int nMagicPrefixOffset = 0;
int nAutoMagicOffset = 0;
int nSocketedItems = 0;
int nSetItemMask = 0;
int nSetRecordId = 0;
int nLastStatId = 0;
int nMaxSockets = 0;
int nStatLists = 0;
int nAnimMode = 0;
int nClassId = 0;
int nSkillId = 0;
int nStatId = 0;
int nState = 0;
int nValue = 0;
int nBits = 0;
int nFlag = 0;
int nMax = 0;
int v237, v238, v240, v241, v242, v243, v244, v245, v246, v247, v248, v249, v250, v251, v252; //TODO: Change names
uint32_t dwCode = 0;
char szChar = 0;
BOOL bRuneword = FALSE;
BOOL bError = FALSE;
BOOL b109 = FALSE;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemData = pItem->pItemData;
D2_ASSERT(pItemData);
pItemData->wItemFormat = (uint16_t)BITMANIP_Read(pBuffer, 10);
nAnimMode = BITMANIP_Read(pBuffer, 3);
if (nAnimMode == IMODE_ONGROUND || nAnimMode == IMODE_DROPPING)
{
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 16));
}
else
{
pItemData->nBodyLoc = (uint8_t)BITMANIP_Read(pBuffer, 4);
UNITS_SetXForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
UNITS_SetYForStaticUnit(pItem, BITMANIP_Read(pBuffer, 4));
pItemData->nInvPage = (uint8_t)(BITMANIP_Read(pBuffer, 3) - 1);
}
UNITS_ChangeAnimMode(pItem, nAnimMode);
dwCode = BITMANIP_Read(pBuffer, 32);
nClassId = DATATBLS_GetItemIdFromItemCode(dwCode);
if (nClassId >= 0)
{
pItem->dwClassId = nClassId;
}
if (bGamble)
{
pItemData->dwItemLevel = 1;
pItemData->dwQualityNo = ITEMQUAL_INFERIOR;
return 1;
}
nSocketedItems = BITMANIP_Read(pBuffer, 3);
if (pSocketedItems)
{
*pSocketedItems = nSocketedItems;
}
if (bCheckForHeader)
{
pItem->dwInitSeed = BITMANIP_Read(pBuffer, 32);
SEED_InitLowSeed(&pItem->pSeed, pItem->dwInitSeed);
}
pItemData->dwItemLevel = BITMANIP_Read(pBuffer, 7);
if (pItemData->dwItemLevel < 1)
{
pItemData->dwItemLevel = 1;
}
pItemData->dwQualityNo = BITMANIP_Read(pBuffer, 4);
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->nInvGfxIdx = (uint8_t)BITMANIP_Read(pBuffer, 3);
}
pMagicAffixDataTbl = DATATBLS_GetMagicAffixDataTables();
nMagicPrefixOffset = pMagicAffixDataTbl->pMagicPrefix - pMagicAffixDataTbl->pMagicAffixTxt;
nAutoMagicOffset = pMagicAffixDataTbl->pAutoMagic - pMagicAffixDataTbl->pMagicAffixTxt;
switch (dwVersion)
{
case 72:
case 73:
case 80:
case 81:
case 82:
nMagicPrefixOffset -= 661;
nAutoMagicOffset -= 1262;
break;
case 83:
case 84:
nMagicPrefixOffset -= 674;
nAutoMagicOffset -= 1265;
break;
case 85:
case 86:
case 87:
nMagicPrefixOffset -= 675;
nAutoMagicOffset -= 1266;
break;
case 88:
nMagicPrefixOffset -= 729;
nAutoMagicOffset -= 1440;
break;
default:
break;
}
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wAutoAffix = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (dwVersion > 88)
{
if (dwVersion <= 89)
{
++pItemData->wAutoAffix;
}
if (pItemData->wAutoAffix)
{
pItemData->wAutoAffix += nAutoMagicOffset;
}
}
else
{
pItemData->wAutoAffix = 0;
}
}
else
{
pItemData->wAutoAffix = 0;
}
switch (pItemData->dwQualityNo)
{
case ITEMQUAL_INFERIOR:
case ITEMQUAL_SUPERIOR:
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 3);
break;
}
case ITEMQUAL_NORMAL:
{
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_CHARM))
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wMagicPrefix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (pItemData->wMagicPrefix[0])
{
pItemData->wMagicPrefix[0] += nMagicPrefixOffset;
}
}
else
{
pItemData->wMagicSuffix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
}
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BODY_PART) && !ITEMS_CheckItemTypeId(pItem, ITEMTYPE_PLAYER_BODY_PART))
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 10);
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL) || ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
pItemData->wMagicSuffix[0] = (uint16_t)BITMANIP_Read(pBuffer, 5);
}
break;
}
case ITEMQUAL_RARE:
case ITEMQUAL_CRAFT:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->wRarePrefix = (uint16_t)BITMANIP_Read(pBuffer, 8);
pItemData->wRareSuffix = (uint16_t)BITMANIP_Read(pBuffer, 8);
}
for (int i = 0; i < 3; ++i)
{
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wMagicPrefix[i] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (dwVersion <= 89)
{
++pItemData->wMagicPrefix[i];
}
if (pItemData->wMagicPrefix[i])
{
pItemData->wMagicPrefix[i] += nMagicPrefixOffset;
}
}
else
{
pItemData->wMagicPrefix[i] = 0;
}
if (BITMANIP_Read(pBuffer, 1))
{
pItemData->wMagicSuffix[i] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (dwVersion <= 89)
{
++pItemData->wMagicSuffix[i];
}
}
else
{
pItemData->wMagicSuffix[i] = 0;
}
}
break;
}
case ITEMQUAL_TEMPERED:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->wRarePrefix = (uint16_t)BITMANIP_Read(pBuffer, 8);
pItemData->wRareSuffix = (uint16_t)BITMANIP_Read(pBuffer, 8);
}
break;
}
case ITEMQUAL_MAGIC:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->wMagicPrefix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
if (pItemData->wMagicPrefix[0])
{
pItemData->wMagicPrefix[0] += nMagicPrefixOffset;
}
pItemData->wMagicSuffix[0] = (uint16_t)BITMANIP_Read(pBuffer, 11);
}
break;
}
case ITEMQUAL_UNIQUE:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 12);
if (pItemData->dwFileIndex < 0 || pItemData->dwFileIndex >= sgptDataTables->nUniqueItemsTxtRecordCount)
{
pItemData->dwFileIndex = -1;
}
}
break;
}
case ITEMQUAL_SET:
{
if (bCheckForHeader || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
bError = TRUE;
nSetRecordId = BITMANIP_Read(pBuffer, 12);
if (dwVersion > 92)
{
if (nSetRecordId >= 0 && nSetRecordId < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nSetRecordId];
if (pSetItemsTxtRecord)
{
pItemData->dwFileIndex = pSetItemsTxtRecord->wSetItemId;
bError = FALSE;
}
}
}
else
{
if (nSetRecordId >= 0 && nSetRecordId < sgptDataTables->nSetsTxtRecordCount)
{
pSetsTxtRecord = &sgptDataTables->pSetsTxt[nSetRecordId];
if (pSetsTxtRecord)
{
for (int i = 0; i < pSetsTxtRecord->nSetItems; ++i)
{
if (pSetsTxtRecord->pSetItem[i]->szItemCode == dwCode)
{
pItemData->dwFileIndex = pSetsTxtRecord->pSetItem[i]->wSetItemId;
bError = FALSE;
break;
}
}
}
}
}
}
break;
}
default:
{
bError = TRUE;
break;
}
}
if (pItemData->dwItemFlags & IFLAG_RUNEWORD)
{
bRuneword = TRUE;
pItemData->wMagicPrefix[0] = (uint16_t)BITMANIP_Read(pBuffer, 16);
}
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
pItemData->dwFileIndex = BITMANIP_Read(pBuffer, 3);
pItemData->nEarLvl = (uint8_t)BITMANIP_Read(pBuffer, 7);
szName = pItemData->szPlayerName;
do
{
szChar = (char)BITMANIP_Read(pBuffer, 7);
*szName++ = szChar;
}
while (szChar);
}
else if (pItemData->dwItemFlags & IFLAG_PERSONALIZED)
{
szName = pItemData->szPlayerName;
do
{
szChar = (char)BITMANIP_Read(pBuffer, 7);
*szName++ = szChar;
}
while (szChar);
}
if (bCheckForHeader && dwVersion > 86 && BITMANIP_Read(pBuffer, 1))
{
pItemData->dwRealmData[0] = BITMANIP_Read(pBuffer, 32);
pItemData->dwRealmData[1] = BITMANIP_Read(pBuffer, 32);
if (dwVersion > 93)
{
BITMANIP_Read(pBuffer, 32);
}
}
if (dwVersion < 93)
{
b109 = TRUE;
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR))
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ARMORCLASS);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_ARMORCLASS, nValue, 0);
STATLIST_SetUnitStat(pItem, STAT_TOBLOCK, pItemsTxtRecord->nBlock, 0);
STATLIST_SetUnitStat(pItem, STAT_VELOCITYPERCENT, -pItemsTxtRecord->dwSpeed, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_MAXDURABILITY, nValue, 0);
if (nValue)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 95)
{
nBits = 8;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_DURABILITY, nValue, 0);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
STATLIST_SetUnitStat(pItem, STAT_ATTACKRATE, -pItemsTxtRecord->dwSpeed, 0);
if (pItemData->dwQualityNo == ITEMQUAL_INFERIOR)
{
if (pItemsTxtRecord->nMaxDam)
{
nValue = 3 * pItemsTxtRecord->nMaxDam / 4;
if (nValue < 2)
{
nValue = 2;
}
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->nMinDam)
{
nValue = 3 * pItemsTxtRecord->nMinDam / 4;
if (nValue < 1)
{
nValue = 1;
}
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->n2HandMaxDam)
{
nValue = 3 * pItemsTxtRecord->n2HandMaxDam / 4;
if (nValue < 2)
{
nValue = 2;
}
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->n2HandMinDam)
{
nValue = 3 * pItemsTxtRecord->n2HandMinDam / 4;
if (nValue < 1)
{
nValue = 1;
}
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, nValue, 0);
}
if (pItemsTxtRecord->nMaxMisDam)
{
nValue = 3 * pItemsTxtRecord->nMinMisDam / 4;
if (nValue < 1)
{
nValue = 1;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, nValue, 0);
nValue = 3 * pItemsTxtRecord->nMaxMisDam / 4;
if (nValue < 2)
{
nValue = 2;
}
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, nValue, 0);
}
}
else
{
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, pItemsTxtRecord->nMaxDam, 0);
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, pItemsTxtRecord->nMinDam, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, pItemsTxtRecord->n2HandMaxDam, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, pItemsTxtRecord->n2HandMinDam, 0);
if (pItemsTxtRecord->nMaxMisDam)
{
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, pItemsTxtRecord->nMinMisDam, 0);
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, pItemsTxtRecord->nMaxMisDam, 0);
}
}
if (pItemData->dwItemFlags & IFLAG_ETHEREAL)
{
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_MINDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_MAXDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MINDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MAXDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MINDAMAGE, 0) / 2, 0);
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, 3 * STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, 0) / 2, 0);
}
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_MAXDURABILITY, nValue, 0);
if (nValue)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 95)
{
nBits = 8;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetUnitStat(pItem, STAT_DURABILITY, nValue, 0);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
if (BITMANIP_Read(pBuffer, 1))
{
nBits = 32;
}
else
{
nBits = 12;
}
STATLIST_SetUnitStat(pItem, STAT_GOLD, BITMANIP_Read(pBuffer, nBits), 0);
}
if (pItemsTxtRecord->nStackable)
{
if (dwVersion > 80)
{
nBits = 9;
}
else
{
nBits = 8;
}
STATLIST_SetUnitStat(pItem, STAT_QUANTITY, BITMANIP_Read(pBuffer, nBits), 0);
}
if (pItemData->dwItemFlags & IFLAG_SOCKETED)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_NUMSOCKETS);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits));
nMaxSockets = pItemsTxtRecord->nInvWidth * pItemsTxtRecord->nInvHeight;
if (nMaxSockets > 0)
{
if (nMaxSockets > 6)
{
nMaxSockets = 6;
}
if (nMaxSockets > ITEMS_GetMaxSockets(pItem))
{
nMaxSockets = ITEMS_GetMaxSockets(pItem);
}
if (nValue < 1)
{
nValue = 1;
}
if (nValue > nMaxSockets)
{
nValue = nMaxSockets;
}
ITEMS_SetItemFlag(pItem, IFLAG_SOCKETED, TRUE);
STATLIST_SetUnitStat(pItem, STAT_ITEM_NUMSOCKETS, nValue, 0);
}
}
if (!bCheckForHeader && !(pItemData->dwItemFlags & IFLAG_IDENTIFIED))
{
return 2 * (bError == 0) - 1;
}
if (dwVersion > 84 && pItemData->dwQualityNo == ITEMQUAL_SET)
{
nStatLists = 5;
nSetItemMask = BITMANIP_Read(pBuffer, 5);
}
else
{
nStatLists = 0;
nSetItemMask = 0;
}
if (bRuneword)
{
++nStatLists;
}
for (int nStatListCounter = -1; nStatListCounter < nStatLists; ++nStatListCounter)
{
if (nStatListCounter < 0)
{
nState = 0;
nFlag = 0x40;
}
else if (bRuneword && nStatListCounter == nStatLists - 1)
{
nState = STATE_RUNEWORD;
nFlag = 0x40;
}
else if (nSetItemMask & (1 << nStatListCounter))
{
nState = gnItemSetStates[nStatListCounter];
nFlag = 0x2040;
}
else
{
continue;
}
pStatList = STATLIST_GetStatListFromUnitStateOrFlag(pItem, nState, nFlag);
if (!pStatList)
{
pStatList = STATLIST_AllocStatList(pItem->pMemoryPool, nFlag, 0, UNIT_ITEM, pItem->dwUnitId);
D2COMMON_10475_PostStatToStatList(pItem, pStatList, 1);
STATLIST_SetState(pStatList, nState);
}
nLastStatId = -1;
while (1)
{
nStatId = BITMANIP_Read(pBuffer, 9);
if (nStatId == 511)
{
break;
}
if (!nStatId && !nLastStatId)
{
bError = TRUE;
break;
}
nLastStatId = nStatId;
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(nStatId);
if (!pItemStatCostTxtRecord)
{
break;
}
switch (nStatId)
{
case STAT_STRENGTH:
case STAT_DEXTERITY:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, nStatId, nValue, 0);
break;
}
case STAT_VITALITY:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_VITALITY, nValue, 0);
if (dwVersion <= 85)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXHP);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAXHP, nValue << 8, 0);
}
break;
}
case STAT_ENERGY:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ENERGY, nValue, 0);
if (dwVersion <= 85)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXMANA);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAXMANA, nValue, 0); //TODO: nValue << 8?
}
break;
}
case STAT_ITEM_MAXDAMAGE_PERCENT:
{
ITEMS_SetDefenseOrDamage(pItem, STAT_ITEM_MAXDAMAGE_PERCENT);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_MAXDAMAGE_PERCENT, nValue, 0);
ITEMS_SetDefenseOrDamage(pItem, STAT_ITEM_MINDAMAGE_PERCENT);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_MINDAMAGE_PERCENT);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_MINDAMAGE_PERCENT, nValue, 0);
break;
}
case STAT_FIREMINDAM:
{
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 6;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_FIREMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_FIREMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_FIREMAXDAM, nValue, 0);
break;
}
case STAT_LIGHTMINDAM:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_LIGHTMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_LIGHTMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_LIGHTMAXDAM, nValue, 0);
break;
}
case STAT_MAGICMINDAM:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAGICMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAGICMAXDAM);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_MAGICMAXDAM, nValue, 0);
break;
}
case STAT_COLDMINDAM:
{
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_COLDMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_COLDMAXDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDLENGTH);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_COLDLENGTH, nValue, 0);
break;
}
case STAT_POISONMINDAM:
{
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 7;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISONMINDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONMAXDAM);
nBits = (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits);
if (dwVersion <= 81)
{
nBits = 8;
}
nValue = BITMANIP_Read(pBuffer, nBits) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISONMAXDAM, nValue, 0);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONLENGTH);
nValue = BITMANIP_Read(pBuffer, (b109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits)) - (b109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISONLENGTH, nValue, 0);
STATLIST_SetStatIfListIsValid(pStatList, STAT_POISON_COUNT, 1, 0);
break;
}
case STAT_ITEM_FREEZE:
{
if (dwVersion > 89)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_FREEZE, dwVersion, b109);
}
else
{
BITMANIP_Read(pBuffer, 16);
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_FREEZE, 1, 0);
}
break;
}
case STAT_ITEM_ADDCLASSSKILLS:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_ADDCLASSSKILLS, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 0);
}
break;
}
case STAT_UNSENTPARAM1:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_UNSENTPARAM1, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 3);
}
break;
}
case STAT_ITEM_ADDEXPERIENCE:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_ADDEXPERIENCE, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 2);
}
break;
}
case STAT_ITEM_HEALAFTERKILL:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_HEALAFTERKILL, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 1);
}
break;
}
case STAT_ITEM_REDUCEDPRICES:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_REDUCEDPRICES, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 4);
}
break;
}
case STAT_ATTACK_VS_MONTYPE:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ATTACK_VS_MONTYPE, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 5);
}
break;
}
case STAT_DAMAGE_VS_MONTYPE:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_DAMAGE_VS_MONTYPE, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ADDCLASSSKILLS, BITMANIP_Read(pBuffer, 3), 6);
}
break;
}
case STAT_ITEM_ADDSKILL_TAB:
case STAT_UNUSED189:
case STAT_UNUSED190:
case STAT_UNUSED191:
case STAT_UNUSED192:
case STAT_UNUSED193:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10848(BITMANIP_Read(pBuffer, 10), &v238, &v237, &nValue);
if (nValue > 7)
{
nValue = 7;
}
STATLIST_SetStat(pStatList, STAT_ITEM_ADDSKILL_TAB, nValue, v237 + 8 * v238);
}
break;
}
case STAT_ITEM_ELEMSKILL:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, STAT_ITEM_ELEMSKILL, dwVersion, b109);
}
else
{
STATLIST_SetStat(pStatList, STAT_ITEM_ELEMSKILL, BITMANIP_Read(pBuffer, 4), 1);
}
break;
}
case STAT_ITEM_SINGLESKILL:
case STAT_ITEM_RESTINPEACE:
case STAT_CURSE_RESISTANCE:
case STAT_FADE:
case STAT_ARMOR_OVERRIDE_PERCENT:
case STAT_UNUSED183:
case STAT_UNUSED184:
case STAT_UNUSED185:
case STAT_UNUSED186:
case STAT_UNUSED187:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10844_ITEMMODS_First(BITMANIP_Read(pBuffer, 14), &nSkillId, &nValue);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_SINGLESKILL);
if (pItemStatCostTxtRecord)
{
nMax = (1 << pItemStatCostTxtRecord->nSaveBits) - 1;
}
else
{
nMax = 7;
}
if (nValue > 0 && nValue <= nMax)
{
pSkillsTxtRecord = DATATBLS_GetSkillsTxtRecord(nSkillId);
if (pSkillsTxtRecord && DATATBLS_GetSkillDescTxtRecord(pSkillsTxtRecord->wSkillDesc))
{
STATLIST_SetStat(pStatList, STAT_ITEM_SINGLESKILL, nValue, nSkillId);
}
}
}
break;
}
case STAT_ITEM_SKILLONATTACK:
case STAT_ITEM_SKILLONKILL:
case STAT_ITEM_SKILLONDEATH:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10845(BITMANIP_Read(pBuffer, 21), &v241, &v240, &v242);
STATLIST_SetStat(pStatList, STAT_ITEM_SKILLONATTACK, v242, ((uint16_t)v241 << 6) + (v240 & 0x3F));
}
break;
}
case STAT_ITEM_SKILLONHIT:
case STAT_ITEM_SKILLONLEVELUP:
case STAT_UNUSED200:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10845(BITMANIP_Read(pBuffer, 21), &v244, &v243, &v245);
STATLIST_SetStat(pStatList, STAT_ITEM_SKILLONHIT, v245, ((uint16_t)v244 << 6) + (v243 & 0x3F));
}
break;
}
case STAT_ITEM_SKILLONGETHIT:
case STAT_UNUSED202:
case STAT_UNUSED203:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
D2Common_10845(BITMANIP_Read(pBuffer, 21), &v247, &v246, &v248);
STATLIST_SetStat(pStatList, STAT_ITEM_SKILLONGETHIT, v248, ((uint16_t)v247 << 6) + (v246 & 0x3F));
}
break;
}
case STAT_ITEM_CHARGED_SKILL:
case STAT_UNUSED204:
case STAT_UNUSED205:
case STAT_UNUSED206:
case STAT_UNUSED207:
case STAT_UNUSED208:
case STAT_UNUSED209:
case STAT_UNUSED210:
case STAT_UNUSED211:
case STAT_UNUSED212:
{
if (dwVersion > 92)
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
}
else
{
if (dwVersion > 73)
{
nBits = 30;
}
else
{
nBits = 29;
}
D2Common_10846(BITMANIP_Read(pBuffer, nBits), &v249, &v250, &v251, &v252);
STATLIST_SetStat(pStatList, STAT_ITEM_CHARGED_SKILL, (v252 << 8) + (uint8_t)v251, (v250 & LOWORD(sgptDataTables->nShiftedStuff)) + ((uint16_t)v249 << sgptDataTables->nStuff));
}
break;
}
default:
{
ITEMS_ReadStatFromItemBitstream(pBuffer, pStatList, pItemStatCostTxtRecord, nStatId, dwVersion, b109);
break;
}
}
}
if (dwVersion <= 92)
{
nValue = STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 0);
if (nValue > 0)
{
if (nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 1) && nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 2)
&& nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 3) && nValue == STATLIST_GetStatValue(pStatList, STAT_ITEM_ADDCLASSSKILLS, 4))
{
for (int i = 0; i < 7; ++i)
{
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_ADDCLASSSKILLS, 0, i);
}
STATLIST_SetStatIfListIsValid(pStatList, STAT_ITEM_ALLSKILLS, nValue, 0);
}
}
}
}
return 2 * (bError == FALSE) - 1;
}
//D2Common.0x6FDA2690
void __fastcall ITEMS_SetDefenseOrDamage(D2UnitStrc* pItem, int nStat)
{
int nMaxAc = 0;
int nItemId = 0;
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
const D2ItemsTxt* pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
pItemsTxtRecord = DATATBLS_GetItemRecordFromItemCode(pItemsTxtRecord->dwCode, &nItemId);
if (pItemsTxtRecord)
{
switch (nStat)
{
case STAT_ITEM_ARMOR_PERCENT:
case STAT_ARMORCLASS:
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR) && pItemsTxtRecord->dwMaxAc)
{
nMaxAc = STATLIST_GetUnitBaseStat(pItem, STAT_ARMORCLASS, 0) + 1;
if (nMaxAc <= pItemsTxtRecord->dwMaxAc)
{
nMaxAc = pItemsTxtRecord->dwMaxAc + 1;
}
STATLIST_SetUnitStat(pItem, STAT_ARMORCLASS, nMaxAc, 0);
}
break;
case STAT_ITEM_MAXDAMAGE_PERCENT:
case STAT_MAXDAMAGE:
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
if (pItemsTxtRecord->nMaxDam && STATLIST_GetUnitBaseStat(pItem, STAT_MAXDAMAGE, 0) < pItemsTxtRecord->nMaxDam)
{
STATLIST_SetUnitStat(pItem, STAT_MAXDAMAGE, pItemsTxtRecord->nMaxDam, 0);
}
if (pItemsTxtRecord->n2HandMaxDam && STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MAXDAMAGE, 0) < pItemsTxtRecord->n2HandMaxDam)
{
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MAXDAMAGE, pItemsTxtRecord->n2HandMaxDam, 0);
}
if (ITEMS_CheckIfThrowable(pItem) && pItemsTxtRecord->nMaxMisDam && STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, 0) < pItemsTxtRecord->nMaxMisDam)
{
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MAXDAMAGE, pItemsTxtRecord->nMaxMisDam, 0);
}
}
break;
case STAT_ITEM_MINDAMAGE_PERCENT:
case STAT_MINDAMAGE:
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
if (pItemsTxtRecord->nMinDam && STATLIST_GetUnitBaseStat(pItem, STAT_MINDAMAGE, 0) < pItemsTxtRecord->nMinDam)
{
STATLIST_SetUnitStat(pItem, STAT_MINDAMAGE, pItemsTxtRecord->nMinDam, 0);
}
if (pItemsTxtRecord->n2HandMinDam && STATLIST_GetUnitBaseStat(pItem, STAT_SECONDARY_MINDAMAGE, 0) < pItemsTxtRecord->n2HandMinDam)
{
STATLIST_SetUnitStat(pItem, STAT_SECONDARY_MINDAMAGE, pItemsTxtRecord->n2HandMinDam, 0);
}
if (ITEMS_CheckIfThrowable(pItem) && pItemsTxtRecord->nMinMisDam && STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_THROW_MINDAMAGE, 0) < pItemsTxtRecord->nMinMisDam)
{
STATLIST_SetUnitStat(pItem, STAT_ITEM_THROW_MINDAMAGE, pItemsTxtRecord->nMinMisDam, 0);
}
}
break;
default:
return;
}
}
}
//D2Common.0x6FDA29D0
void __fastcall ITEMS_ReadStatFromItemBitstream(D2BitBufferStrc* pBuffer, D2StatListStrc* pStatList, D2ItemStatCostTxt* pItemStatCostTxtRecord, int nStatId, uint32_t dwVersion, int n109)
{
int nSaveAdd = n109 ? pItemStatCostTxtRecord->dw09SaveAdd : pItemStatCostTxtRecord->dwSaveAdd;
int nParamBits = n109 ? pItemStatCostTxtRecord->dw09SaveParamBits : pItemStatCostTxtRecord->dwSaveParamBits;
int nSaveBits = n109 ? pItemStatCostTxtRecord->n09SaveBits : pItemStatCostTxtRecord->nSaveBits;
int nParam = 0;
int nValue = 0;
switch (nStatId)
{
case STAT_SECONDARY_MINDAMAGE:
if (dwVersion <= 89)
{
nSaveBits = 5;
}
break;
case STAT_SECONDARY_MAXDAMAGE:
if (dwVersion <= 89)
{
nSaveBits = 6;
}
break;
case STAT_HPREGEN:
if (dwVersion <= 89)
{
nSaveBits = 5;
nSaveAdd = 10;
}
break;
case STAT_ITEM_GOLDBONUS:
if (dwVersion <= 89)
{
nSaveBits = 8;
nSaveAdd = 20;
}
break;
case STAT_ITEM_MAGICBONUS:
if (dwVersion <= 0x59)
{
nSaveBits = 7;
nSaveAdd = 20;
}
break;
case STAT_ITEM_FASTERATTACKRATE:
case STAT_ITEM_FASTERMOVEVELOCITY:
case STAT_ITEM_FASTERGETHITRATE:
case STAT_ITEM_FASTERBLOCKRATE:
case STAT_ITEM_FASTERCASTRATE:
if (dwVersion <= 87)
{
nSaveBits = 6;
}
break;
case STAT_ITEM_LEVELREQ:
case STAT_ITEM_LEVELREQPCT:
if (dwVersion < 93)
{
nStatId = 93;
}
break;
case STAT_LASTBLOCKFRAME:
case STAT_ITEM_NONCLASSSKILL:
if (dwVersion < 93)
{
nStatId = 96;
}
break;
case STAT_STATE:
case STAT_MONSTER_PLAYERCOUNT:
if (dwVersion < 93)
{
nStatId = 99;
}
break;
case STAT_SKILL_POISON_OVERRIDE_LENGTH:
case STAT_SKILL_BYPASS_UNDEAD:
if (dwVersion < 93)
{
nStatId = 102;
}
break;
case STAT_SKILL_BYPASS_DEMONS:
case STAT_SKILL_BYPASS_BEASTS:
if (dwVersion < 93)
{
nStatId = 105;
}
break;
default:
break;
}
if (nParamBits > 0)
{
nParam = BITMANIP_Read(pBuffer, nParamBits);
}
nValue = BITMANIP_Read(pBuffer, nSaveBits);
if (pStatList)
{
STATLIST_SetStat(pStatList, nStatId, (nValue - nSaveAdd) << pItemStatCostTxtRecord->nValShift, nParam);
}
}
//D2Common.0x6FDA2BA0 (#10881)
size_t __stdcall ITEMS_SerializeItemToBitstream(D2UnitStrc* pItem, uint8_t* pBitstream, size_t nSize, BOOL bServer, BOOL bSaveItemInv, BOOL bGamble)
{
D2BitBufferStrc pBuffer = {};
BITMANIP_Initialize(&pBuffer, pBitstream, nSize);
ITEMS_SerializeItem(pItem, &pBuffer, bServer, bSaveItemInv, bGamble);
if (pBuffer.bFull)
{
return 0;
}
else
{
return BITMANIP_GetSize(&pBuffer);
}
}
//Inlined in D2Common.0x6FDA2C00
void __fastcall ITEMS_SerializeItemCompact(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, D2ItemsTxt* pItemsTxtRecord, BOOL bServer)
{
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
char* szName = NULL;
int nItemFormat = 0;
int nValue = 0;
int nGold = 0;
int nX = 0;
int nY = 0;
uint8_t nBodyLoc = 0;
int v39; // [sp+24h] [bp-8h]@63
int v40; // [sp+28h] [bp-4h]@63
nItemFormat = ITEMS_GetItemFormat(pItem);
if (nItemFormat > 0)
{
if (nItemFormat >= 1023)
{
nItemFormat = 1023;
}
}
else
{
nItemFormat = 0;
}
BITMANIP_Write(pBuffer, nItemFormat, 10);
ITEMS_WriteBitsToBitstream(pBuffer, pItem->dwAnimMode, 3);
if (pItem->dwAnimMode == IMODE_ONGROUND || pItem->dwAnimMode == IMODE_DROPPING)
{
ITEMS_WriteBitsToBitstream(pBuffer, UNITS_GetXPosition(pItem), 16);
ITEMS_WriteBitsToBitstream(pBuffer, UNITS_GetYPosition(pItem), 16);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetBodyLocation(pItem), 4);
nX = UNITS_GetXPosition(pItem);
if (nX > 0)
{
if (nX >= 15)
{
nX = 15;
}
}
else
{
nX = 0;
}
ITEMS_WriteBitsToBitstream(pBuffer, nX, 4);
nY = UNITS_GetYPosition(pItem);
if (nY > 0)
{
if (nY >= 15)
{
nY = 15;
}
}
else
{
nY = 0;
}
ITEMS_WriteBitsToBitstream(pBuffer, nY, 4);
ITEMS_WriteBitsToBitstream(pBuffer, (ITEMS_GetInvPage(pItem) + 1), 3);
}
if (ITEMS_GetItemFlags(pItem) & IFLAG_ISEAR)
{
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetFileIndex(pItem), 3);
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetEarLevel(pItem), 7);
szName = ITEMS_GetEarName(pItem);
do
{
ITEMS_WriteBitsToBitstream(pBuffer, *szName, 7);
}
while (*szName++);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, ITEMS_GetBaseCode(pItem), 32);
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
nGold = STATLIST_GetUnitStatUnsigned(pItem, STAT_GOLD, 0);
ITEMS_WriteBitsToBitstream(pBuffer, (nGold >= 4096), 1);
ITEMS_WriteBitsToBitstream(pBuffer, nGold, (((nGold < 4096) - 1) & 20) + 12);
}
}
if (pItemsTxtRecord->nQuest && pItemsTxtRecord->nQuestDiffCheck)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_QUESTITEMDIFFICULTY);
D2_ASSERT(pItemStatCostTxtRecord);
nValue = STATLIST_GetUnitStatUnsigned(pItem, STAT_QUESTITEMDIFFICULTY, 0);
ITEMS_WriteBitsToBitstream(pBuffer, pItemStatCostTxtRecord->dwSaveAdd + (nValue >> pItemStatCostTxtRecord->nValShift), pItemStatCostTxtRecord->nSaveBits);
}
if (bServer)
{
v40 = 0;
v39 = 0;
ITEMS_GetRealmData(pItem, &v40, &v39);
if (v39)
{
ITEMS_WriteBitsToBitstream(pBuffer, 1, 1);
ITEMS_WriteBitsToBitstream(pBuffer, v40, 32);
ITEMS_WriteBitsToBitstream(pBuffer, v39, 32);
ITEMS_WriteBitsToBitstream(pBuffer, 0, 32);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, 0, 1);
}
}
}
//D2Common.0x6FDA2C00
size_t __fastcall ITEMS_SerializeItem(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bServer, BOOL bSaveItemInv, BOOL bGamble)
{
D2ItemsTxt* pItemsTxtRecord = NULL;
D2ItemDataStrc* pItemData = NULL;
uint32_t nItemFlags = 0;
if (!pItem || pItem->dwUnitType != UNIT_ITEM)
{
return 0;
}
pItemData = pItem->pItemData;
if (pItemData)
{
nItemFlags = pItemData->dwItemFlags;
}
else
{
nItemFlags = 0;
}
nItemFlags = nItemFlags & ~IFLAG_INIT | IFLAG_JUSTSAVED;
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
if (!pItemsTxtRecord)
{
return 0;
}
if (pItemsTxtRecord->nCompactSave)
{
nItemFlags |= IFLAG_COMPACTSAVE;
}
if (bGamble)
{
nItemFlags = nItemFlags & ~IFLAG_ETHEREAL | IFLAG_LOWQUALITY;
}
if (bServer)
{
BITMANIP_Write(pBuffer, 'MJ', 16);
}
else
{
if (!(nItemFlags & IFLAG_IDENTIFIED))
{
nItemFlags &= ~IFLAG_SOCKETED;
}
}
BITMANIP_Write(pBuffer, nItemFlags, 32);
if (nItemFlags & IFLAG_COMPACTSAVE)
{
ITEMS_SerializeItemCompact(pItem, pBuffer, pItemsTxtRecord, bServer);
}
else
{
ITEMS_SerializeItemComplete(pItem, pBuffer, bServer, bGamble);
}
if (!bGamble && bSaveItemInv && pItem->pInventory)
{
for (D2UnitStrc* i = INVENTORY_GetFirstItem(pItem->pInventory); i; i = INVENTORY_GetNextItem(i))
{
BITMANIP_GoToNextByte(pBuffer);
ITEMS_SerializeItem(INVENTORY_UnitIsItem(i), pBuffer, bServer, bSaveItemInv, 0);
}
}
return BITMANIP_GetSize(pBuffer);
}
//D2Common.0x6FDA2FD0
void __fastcall ITEMS_WriteBitsToBitstream(D2BitBufferStrc* pBuffer, int nData, int nBits)
{
if (nBits != 32)
{
nData &= (nData <= 0) - 1;
if (nData >= (1 << nBits) - 1)
{
nData = (1 << nBits) - 1;
}
}
return BITMANIP_Write(pBuffer, nData, nBits);
}
//D2Common.0x6FDA3010
void __fastcall ITEMS_SerializeItemComplete(D2UnitStrc* pItem, D2BitBufferStrc* pBuffer, BOOL bServer, BOOL bGamble)
{
static const int gnItemSetStates_6FDD15A8[] =
{
STATE_ITEMSET1, STATE_ITEMSET2, STATE_ITEMSET3, STATE_ITEMSET4, STATE_ITEMSET5
};
D2ItemStatCostTxt* pItemStatCostTxtRecord = NULL;
D2ItemStatCostTxt* pLocalRecord = NULL;
D2MagicAffixDataTbl* pMagicAffixInfo = NULL;
D2ItemTypesTxt* pItemTypesTxtRecord = NULL;
D2ItemsTxt* pItemsTxtRecord = NULL;
D2StatListStrc* pStatListEx = NULL;
D2UnitStrc* pInventoryItem = NULL;
D2ItemDataStrc* pItemData = NULL;
char* szPlayerName = NULL;
int nMagicPrefixOffset = 0;
int nAutoMagicOffset = 0;
int nCurrentCharacter = 0;
int nStatListCounter = 0;
int nSocketedItems = 0;
int nMaxDurability = 0;
int nItemFormat = 0;
int nItemLevel = 0;
int nItemType = 0;
int nQuality = 0;
int nInvGfx = 0;
int nVarInvGfx = 0;
int nAnimMode = 0;
int nBodyLoc = 0;
int nStatCounter = 0;
int nSetItemMask = 0;
int nMagicPrefix = 0;
int nMagicSuffix = 0;
int nRarePrefix = 0;
int nRareSuffix = 0;
int nRunewordId = 0;
int nScrollType = 0;
int nAutoAffix = 0;
int nStatLists = 0;
int nFileIndex = 0;
int nEarLevel = 0;
int nCounter = 0;
int nStatId = 0;
int nStats = 0;
int nValue = 0;
int nGold = 0;
uint8_t nStorePage = 0;
BOOL bIsRuneword = FALSE;
BOOL bContinue = FALSE;
BOOL bInvalid = FALSE;
D2CoordStrc pCoords = {};
int nStatValues[511] = {};
D2StatStrc pStat[511] = {};
D2_ASSERT(pItem);
D2_ASSERT(pItem->dwUnitType == UNIT_ITEM);
pItemData = pItem->pItemData;
D2_ASSERT(pItemData);
nItemFormat = pItemData->wItemFormat;
if (nItemFormat > 0)
{
if (nItemFormat >= 1023)
{
nItemFormat = 1023;
}
}
else
{
nItemFormat = 0;
}
BITMANIP_Write(pBuffer, nItemFormat, 10);
nAnimMode = pItem->dwAnimMode;
if (nAnimMode > 0)
{
if (nAnimMode >= 7)
{
nAnimMode = 7;
}
}
else
{
nAnimMode = 0;
}
BITMANIP_Write(pBuffer, nAnimMode, 3);
if (nAnimMode == IMODE_ONGROUND || nAnimMode == IMODE_DROPPING)
{
UNITS_GetCoords(pItem, &pCoords);
if (pCoords.nX > 0)
{
if (pCoords.nX >= 65535)
{
pCoords.nX = 65535;
}
}
else
{
pCoords.nX = 0;
}
BITMANIP_Write(pBuffer, pCoords.nX, 16);
if (pCoords.nY > 0)
{
if (pCoords.nY >= 65535)
{
pCoords.nY = 65535;
}
}
else
{
pCoords.nY = 0;
}
BITMANIP_Write(pBuffer, pCoords.nY, 16);
}
else
{
nBodyLoc = pItemData->nBodyLoc;
if (nBodyLoc > 0)
{
if (nBodyLoc >= 15)
{
nBodyLoc = 15;
}
}
else
{
nBodyLoc = 0;
}
BITMANIP_Write(pBuffer, nBodyLoc, 4);
UNITS_GetCoords(pItem, &pCoords);
if (pCoords.nX > 0)
{
if (pCoords.nX >= 15)
{
pCoords.nX = 15;
}
}
else
{
pCoords.nX = 0;
}
BITMANIP_Write(pBuffer, pCoords.nX, 4);
if (pCoords.nY > 0)
{
if (pCoords.nY >= 15)
{
pCoords.nY = 15;
}
}
else
{
pCoords.nY = 0;
}
BITMANIP_Write(pBuffer, pCoords.nY, 4);
nStorePage = pItemData->nInvPage + 1;
if (nStorePage > 0)
{
if (nStorePage >= 7)
{
nStorePage = 7;
}
}
else
{
nStorePage = 0;
}
BITMANIP_Write(pBuffer, nStorePage, 3);
}
pItemsTxtRecord = DATATBLS_GetItemsTxtRecord(pItem->dwClassId);
D2_ASSERT(pItemsTxtRecord);
if (bGamble)
{
if (pItemsTxtRecord->dwNormCode)
{
BITMANIP_Write(pBuffer, pItemsTxtRecord->dwNormCode, 32);
}
else
{
BITMANIP_Write(pBuffer, pItemsTxtRecord->dwCode, 32);
}
return;
}
BITMANIP_Write(pBuffer, pItemsTxtRecord->dwCode, 32);
nSocketedItems = 0;
if (ITEMS_CheckIfSocketable(pItem) && pItem->pInventory)
{
pInventoryItem = INVENTORY_GetFirstItem(pItem->pInventory);
if (pInventoryItem)
{
do
{
++nSocketedItems;
pInventoryItem = INVENTORY_GetNextItem(pInventoryItem);
}
while (pInventoryItem);
if (nSocketedItems > 0)
{
if (nSocketedItems >= 7)
{
nSocketedItems = 7;
}
}
else
{
nSocketedItems = 0;
}
}
}
BITMANIP_Write(pBuffer, nSocketedItems, 3);
if (bServer)
{
BITMANIP_Write(pBuffer, pItem->dwInitSeed, 32);
}
if ((int)pItemData->dwItemLevel < 1)
{
pItemData->dwItemLevel = 1;
}
nItemLevel = pItemData->dwItemLevel;
if (nItemLevel > 0)
{
if (nItemLevel >= 127)
{
nItemLevel = 127;
}
}
else
{
nItemLevel = 0;
}
BITMANIP_Write(pBuffer, nItemLevel, 7);
nQuality = pItemData->dwQualityNo;
if (nQuality > 0)
{
if (nQuality >= 15)
{
nQuality = 15;
}
}
else
{
nQuality = 0;
}
BITMANIP_Write(pBuffer, nQuality, 4);
nItemType = ITEMS_GetItemType(pItem);
pItemTypesTxtRecord = DATATBLS_GetItemTypesTxtRecord(nItemType);
if (pItemTypesTxtRecord)
{
nVarInvGfx = pItemTypesTxtRecord->nVarInvGfx;
}
else
{
nVarInvGfx = 0;
}
BITMANIP_Write(pBuffer, nVarInvGfx ? 1 : 0, 1);
if (pItemTypesTxtRecord && pItemTypesTxtRecord->nVarInvGfx)
{
nInvGfx = pItemData->nInvGfxIdx;
if (nInvGfx > 0)
{
if (nInvGfx >= 7)
{
nInvGfx = 7;
}
}
else
{
nInvGfx = 0;
}
BITMANIP_Write(pBuffer, nInvGfx, 3);
}
pMagicAffixInfo = DATATBLS_GetMagicAffixDataTables();
nMagicPrefixOffset = ((int)pMagicAffixInfo->pMagicPrefix - (int)pMagicAffixInfo->pMagicAffixTxt) / sizeof(D2MagicAffixTxt);
nAutoMagicOffset = ((int)pMagicAffixInfo->pAutoMagic - (int)pMagicAffixInfo->pMagicAffixTxt) / sizeof(D2MagicAffixTxt);
nAutoAffix = pItemData->wAutoAffix;
if (nAutoAffix > nAutoMagicOffset)
{
nAutoAffix -= nAutoMagicOffset;
}
BITMANIP_Write(pBuffer, nAutoAffix ? 1 : 0, 1);
if (nAutoAffix)
{
if (nAutoAffix > 0)
{
if (nAutoAffix >= 2047)
{
nAutoAffix = 2047;
}
}
else
{
nAutoAffix = 0;
}
BITMANIP_Write(pBuffer, nAutoAffix, 11);
}
switch (pItemData->dwQualityNo)
{
case ITEMQUAL_INFERIOR:
case ITEMQUAL_SUPERIOR:
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex > 0)
{
if (nFileIndex >= 7)
{
nFileIndex = 7;
}
}
else
{
nFileIndex = 0;
}
BITMANIP_Write(pBuffer, nFileIndex, 3);
break;
}
case ITEMQUAL_RARE:
case ITEMQUAL_CRAFT:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nRarePrefix = pItemData->wRarePrefix;
if (nRarePrefix > 0)
{
if (nRarePrefix >= 255)
{
nRarePrefix = 255;
}
}
else
{
nRarePrefix = 0;
}
BITMANIP_Write(pBuffer, nRarePrefix, 8);
nRareSuffix = pItemData->wRareSuffix;
if (nRareSuffix > 0)
{
if (nRareSuffix >= 255)
{
nRareSuffix = 255;
}
}
else
{
nRareSuffix = 0;
}
BITMANIP_Write(pBuffer, nRareSuffix, 8);
}
nCounter = 0;
do
{
nMagicPrefix = pItemData->wMagicPrefix[nCounter];
if (nMagicPrefix > nMagicPrefixOffset)
{
nMagicPrefix -= nMagicPrefixOffset;
}
if (nMagicPrefix)
{
BITMANIP_Write(pBuffer, 1, 1);
if (nMagicPrefix > 0)
{
if (nMagicPrefix >= 2047)
{
nMagicPrefix = 2047;
}
}
else
{
nMagicPrefix = 0;
}
BITMANIP_Write(pBuffer, nMagicPrefix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 1);
}
if (pItemData->wMagicSuffix[nCounter] != 0)
{
BITMANIP_Write(pBuffer, 1, 1);
nMagicSuffix = pItemData->wMagicSuffix[nCounter];
if (nMagicSuffix > 0)
{
if (nMagicSuffix >= 2047)
{
nMagicSuffix = 2047;
}
}
else
{
nMagicSuffix = 0;
}
BITMANIP_Write(pBuffer, nMagicSuffix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 1);
}
++nCounter;
}
while (nCounter < 3);
break;
}
case ITEMQUAL_TEMPERED:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nRarePrefix = pItemData->wRarePrefix;
if (nRarePrefix > 0)
{
if (nRarePrefix >= 255)
{
nRarePrefix = 255;
}
}
else
{
nRarePrefix = 0;
}
BITMANIP_Write(pBuffer, nRarePrefix, 8);
nRareSuffix = pItemData->wRareSuffix;
if (nRareSuffix > 0)
{
if (nRareSuffix >= 255)
{
nRareSuffix = 255;
}
}
else
{
nRareSuffix = 0;
}
BITMANIP_Write(pBuffer, nRareSuffix, 8);
}
break;
}
case ITEMQUAL_MAGIC:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nMagicPrefix = pItemData->wMagicPrefix[0];
if (nMagicPrefix > nMagicPrefixOffset)
{
nMagicPrefix -= nMagicPrefixOffset;
}
if (nMagicPrefix > 0)
{
if (nMagicPrefix >= 2047)
{
nMagicPrefix = 2047;
}
}
else
{
nMagicPrefix = 0;
}
BITMANIP_Write(pBuffer, nMagicPrefix, 11);
nMagicSuffix = pItemData->wMagicSuffix[0];
if (nMagicSuffix > 0)
{
if (nMagicSuffix >= 2047)
{
nMagicSuffix = 2047;
}
}
else
{
nMagicSuffix = 0;
}
BITMANIP_Write(pBuffer, nMagicSuffix, 11);
}
break;
}
case ITEMQUAL_SET:
case ITEMQUAL_UNIQUE:
{
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex < 0)
{
nFileIndex = 4095;
}
if (nFileIndex >= 4095)
{
nFileIndex = 4095;
}
BITMANIP_Write(pBuffer, nFileIndex, 12);
}
break;
}
default:
{
if (pItemData->dwQualityNo != ITEMQUAL_NORMAL)
{
pItemData->dwQualityNo = ITEMQUAL_NORMAL;
bInvalid = TRUE;
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_CHARM) && (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED))
{
nMagicPrefix = pItemData->wMagicPrefix[0];
if (nMagicPrefix > nMagicPrefixOffset)
{
nMagicPrefix -= nMagicPrefixOffset;
}
BITMANIP_Write(pBuffer, nMagicPrefix ? 1 : 0, 1);
if (nMagicPrefix)
{
if (nMagicPrefix > 0)
{
if (nMagicPrefix >= 2047)
{
nMagicPrefix = 2047;
}
BITMANIP_Write(pBuffer, nMagicPrefix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 11);
}
}
else
{
nMagicSuffix = pItemData->wMagicSuffix[0];
if (nMagicSuffix > 0)
{
if (nMagicSuffix >= 2047)
{
nMagicSuffix = 2047;
}
BITMANIP_Write(pBuffer, nMagicSuffix, 11);
}
else
{
BITMANIP_Write(pBuffer, 0, 11);
}
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BODY_PART) && !ITEMS_CheckItemTypeId(pItem, ITEMTYPE_PLAYER_BODY_PART))
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex > 0)
{
if (nFileIndex >= 1023)
{
nFileIndex = 1023;
}
}
else
{
nFileIndex = 0;
}
BITMANIP_Write(pBuffer, nFileIndex, 10);
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_SCROLL) || ITEMS_CheckItemTypeId(pItem, ITEMTYPE_BOOK))
{
nScrollType = pItemData->wMagicSuffix[0];
if (nScrollType > 0)
{
if (nScrollType >= 31)
{
nScrollType = 31;
}
}
else
{
nScrollType = 0;
}
BITMANIP_Write(pBuffer, nScrollType, 5);
}
break;
}
}
if (pItemData->dwItemFlags & IFLAG_RUNEWORD)
{
if (const D2RunesTxt* pRunesTxtRecord = ITEMS_GetRunesTxtRecordFromItem(pItem))
{
nRunewordId = pRunesTxtRecord->wStringId;
}
else
{
nRunewordId = -1;
}
if (nRunewordId > 0)
{
if (nRunewordId >= 65535)
{
nRunewordId = 65535;
}
}
else
{
nRunewordId = 0;
}
BITMANIP_Write(pBuffer, nRunewordId, 16);
}
if (pItemData->dwItemFlags & IFLAG_ISEAR)
{
nFileIndex = pItemData->dwFileIndex;
if (nFileIndex > 0)
{
if (nFileIndex >= 7)
{
nFileIndex = 7;
}
}
else
{
nFileIndex = 0;
}
BITMANIP_Write(pBuffer, nFileIndex, 3);
nEarLevel = pItemData->nEarLvl;
if (nEarLevel > 0)
{
if (nEarLevel >= 127)
{
nEarLevel = 127;
}
}
else
{
nEarLevel = 0;
}
BITMANIP_Write(pBuffer, nEarLevel, 7);
szPlayerName = pItemData->szPlayerName;
do
{
nCurrentCharacter = *szPlayerName;
if (nCurrentCharacter > 0)
{
if (nCurrentCharacter >= 127)
{
nCurrentCharacter = 127;
}
}
else
{
nCurrentCharacter = 0;
}
BITMANIP_Write(pBuffer, nCurrentCharacter, 7);
bContinue = *szPlayerName++;
}
while (bContinue);
}
else if (pItemData->dwItemFlags & IFLAG_PERSONALIZED)
{
szPlayerName = pItemData->szPlayerName;
do
{
nCurrentCharacter = *szPlayerName;
if (nCurrentCharacter > 0)
{
if (nCurrentCharacter >= 127)
{
nCurrentCharacter = 127;
}
}
else
{
nCurrentCharacter = 0;
}
BITMANIP_Write(pBuffer, nCurrentCharacter, 7);
bContinue = *szPlayerName++;
}
while (bContinue);
}
if (bServer)
{
if (pItemData->dwRealmData[1])
{
BITMANIP_Write(pBuffer, 1, 1);
BITMANIP_Write(pBuffer, pItemData->dwRealmData[0], 32);
ITEMS_WriteBitsToBitstream(pBuffer, pItemData->dwRealmData[1], 32);
ITEMS_WriteBitsToBitstream(pBuffer, 0, 32);
}
else
{
ITEMS_WriteBitsToBitstream(pBuffer, 0, 1);
}
}
if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_ANY_ARMOR))
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ARMORCLASS);
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitBaseStat(pItem, STAT_ARMORCLASS, 0) + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nMaxDurability = STATLIST_GetUnitBaseStat(pItem, STAT_MAXDURABILITY, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nMaxDurability + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
if (nMaxDurability)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_WEAPON))
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAXDURABILITY);
nMaxDurability = STATLIST_GetUnitBaseStat(pItem, STAT_MAXDURABILITY, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nMaxDurability + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
if (nMaxDurability)
{
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(STAT_DURABILITY);
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitStatUnsigned(pItem, STAT_DURABILITY, 0) + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
else if (ITEMS_CheckItemTypeId(pItem, ITEMTYPE_GOLD))
{
nGold = STATLIST_GetUnitStatUnsigned(pItem, STAT_GOLD, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nGold >= 4096, 1);
ITEMS_WriteBitsToBitstream(pBuffer, nGold, nGold >= 4096 ? 32 : 12);
}
if (ITEMS_CheckIfStackable(pItem))
{
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitStatUnsigned(pItem, STAT_QUANTITY, 0), 9);
}
if (pItemData->dwItemFlags & IFLAG_SOCKETED)
{
ITEMS_WriteBitsToBitstream(pBuffer, STATLIST_GetUnitBaseStat(pItem, STAT_ITEM_NUMSOCKETS, 0), ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_NUMSOCKETS)->nSaveBits);
}
if (bServer || pItemData->dwItemFlags & IFLAG_IDENTIFIED)
{
nStatLists = 0;
if (ITEMS_GetItemQuality(pItem) == ITEMQUAL_SET)
{
nSetItemMask = 0;
nCounter = 0;
do
{
if (STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nCounter], 0x2040) || STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nCounter], 0x40))
{
nStatLists = nCounter + 1;
nSetItemMask += 1 << nCounter;
}
++nCounter;
}
while (nCounter < 5);
ITEMS_WriteBitsToBitstream(pBuffer, nSetItemMask, 5);
}
bIsRuneword = 0;
if (ITEMS_CheckItemFlag(pItem, IFLAG_RUNEWORD, __LINE__, __FILE__))
{
++nStatLists;
bIsRuneword = TRUE;
}
nStatListCounter = -1;
pStatListEx = STATLIST_GetStatListFromUnitStateAndFlag(pItem, 0, 0x40);
while (1)
{
if (pStatListEx && !bInvalid)
{
memset(nStatValues, 0, sizeof(nStatValues));
nStats = STATLIST_GetBaseStatsData((D2StatListExStrc*)pStatListEx, pStat, ARRAY_SIZE(pStat));
nStatCounter = 0;
while (nStatCounter < nStats)
{
nStatId = pStat[nStatCounter].nStat;
pItemStatCostTxtRecord = ITEMS_GetItemStatCostTxtRecord(nStatId);
nValue = pStat[nStatCounter].nValue >> pItemStatCostTxtRecord->nValShift;
if (pItemStatCostTxtRecord->nSaveBits && nValue && nValue != nStatValues[nStatId])
{
ITEMS_WriteBitsToBitstream(pBuffer, nStatId, 9);
if (nStatId <= STAT_MAGICMINDAM)
{
if (nStatId == STAT_MAGICMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_MAGICMAXDAM);
nStatValues[STAT_MAGICMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_MAGICMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_MAGICMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_ITEM_MAXDAMAGE_PERCENT)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_ITEM_MINDAMAGE_PERCENT);
nStatValues[STAT_ITEM_MINDAMAGE_PERCENT] = STATLIST_GetStatValue(pStatListEx, STAT_ITEM_MINDAMAGE_PERCENT, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_ITEM_MINDAMAGE_PERCENT] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_FIREMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_FIREMAXDAM);
nStatValues[STAT_FIREMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_FIREMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_FIREMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_LIGHTMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_LIGHTMAXDAM);
nStatValues[STAT_LIGHTMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_LIGHTMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_LIGHTMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else
{
if ((int)pItemStatCostTxtRecord->dwSaveParamBits > 0)
{
ITEMS_WriteBitsToBitstream(pBuffer, pStat[nStatCounter].nLayer, pItemStatCostTxtRecord->dwSaveParamBits);
}
if (pItemStatCostTxtRecord->nSaveBits)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
}
else if (nStatId == STAT_COLDMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDMAXDAM);
nStatValues[STAT_COLDMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_COLDMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_COLDMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_COLDLENGTH);
nStatValues[STAT_COLDLENGTH] = STATLIST_GetStatValue(pStatListEx, STAT_COLDLENGTH, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_COLDLENGTH] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId == STAT_POISONMINDAM)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONMAXDAM);
nStatValues[STAT_POISONMAXDAM] = STATLIST_GetStatValue(pStatListEx, STAT_POISONMAXDAM, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_POISONMAXDAM] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
pLocalRecord = ITEMS_GetItemStatCostTxtRecord(STAT_POISONLENGTH);
nStatValues[STAT_POISONLENGTH] = STATLIST_GetStatValue(pStatListEx, STAT_POISONLENGTH, 0);
ITEMS_WriteBitsToBitstream(pBuffer, nStatValues[STAT_POISONLENGTH] + pLocalRecord->dwSaveAdd, pLocalRecord->nSaveBits);
}
else if (nStatId != STAT_POISON_COUNT)
{
if ((int)pItemStatCostTxtRecord->dwSaveParamBits > 0)
{
ITEMS_WriteBitsToBitstream(pBuffer, pStat[nStatCounter].nLayer, pItemStatCostTxtRecord->dwSaveParamBits);
}
if (pItemStatCostTxtRecord->nSaveBits)
{
ITEMS_WriteBitsToBitstream(pBuffer, nValue + pItemStatCostTxtRecord->dwSaveAdd, pItemStatCostTxtRecord->nSaveBits);
}
}
}
++nStatCounter;
}
}
if (nStatListCounter < 0 || pStatListEx || bIsRuneword)
{
ITEMS_WriteBitsToBitstream(pBuffer, 511, 9);
}
++nStatListCounter;
if (nStatListCounter >= nStatLists)
{
return;
}
if (bIsRuneword && nStatListCounter == nStatLists - 1)
{
pStatListEx = STATLIST_GetStatListFromUnitStateOrFlag(pItem, STATE_RUNEWORD, 0x40);
}
else
{
pStatListEx = STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nStatListCounter], 0x2040);
if (!pStatListEx)
{
pStatListEx = STATLIST_GetStatListFromUnitStateAndFlag(pItem, gnItemSetStates_6FDD15A8[nStatListCounter], 0x40);
}
}
}
}
}
//D2Common.0x6FDA42B0
D2ItemStatCostTxt* __fastcall ITEMS_GetItemStatCostTxtRecord(int nStatId)
{
if (nStatId >= 0 && nStatId < sgptDataTables->nItemStatCostTxtRecordCount)
{
return &sgptDataTables->pItemStatCostTxt[nStatId];
}
return NULL;
}
//D2Common.0x6FDA42E0 (#10837)
int __stdcall ITEMS_GetNoOfSetItemsFromItem(D2UnitStrc* pItem)
{
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
if (pItem && pItem->dwUnitType == UNIT_ITEM && pItem->pItemData && pItem->pItemData->dwQualityNo == ITEMQUAL_SET)
{
if (pItem->pItemData->dwFileIndex >= 0 && pItem->pItemData->dwFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[pItem->pItemData->dwFileIndex];
if (pSetItemsTxtRecord)
{
return pSetItemsTxtRecord->nSetItems;
}
}
}
return -1;
}
//D2Common.0x6FDD15C8
int gnItemSetStates[] =
{
STATE_ITEMSET1, STATE_ITEMSET2, STATE_ITEMSET3, STATE_ITEMSET4, STATE_ITEMSET5, STATE_ITEMSET6
};
//D2Common.0x6FDD15E0
int gnSetMaskToBonusMappingTable[] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6
};
//D2Common.0x6FDA4380
//TODO: Find a name
BOOL __fastcall sub_6FDA4380(D2UnitStrc* pItem, unsigned int nSetItemMask)
{
D2SetItemsTxt* pSetItemsTxt = NULL;
int nSetItems = 0;
int nBonuses = 0;
int nIndex = 0;
BOOL bSet = FALSE;
if (!pItem || pItem->dwUnitType != UNIT_ITEM || ITEMS_GetItemQuality(pItem) != ITEMQUAL_SET)
{
return FALSE;
}
pSetItemsTxt = ITEMS_GetSetItemsTxtRecordFromItem(pItem);
if (!pSetItemsTxt || !pSetItemsTxt->nAddFunc)
{
return FALSE;
}
if (pSetItemsTxt->nAddFunc == 1)
{
nSetItems = ITEMS_GetNoOfSetItemsFromItem(pItem);
for (int i = 0; i < 6; ++i)
{
nIndex = i;
if (i != nSetItems)
{
if (i > nSetItems)
{
--nIndex;
}
if ((1 << i) & nSetItemMask)
{
bSet = FALSE;
}
else
{
bSet = TRUE;
}
D2Common_10574(pItem, gnItemSetStates[nIndex], bSet);
}
}
}
else if (pSetItemsTxt->nAddFunc == 2)
{
nBonuses = nSetItemMask < ARRAY_SIZE(gnSetMaskToBonusMappingTable) ? gnSetMaskToBonusMappingTable[nSetItemMask] : 0;
for (int i = 0; i < nBonuses - 1; ++i)
{
D2Common_10574(pItem, gnItemSetStates[i], FALSE);
}
if (nBonuses - 1 >= 5)
{
return TRUE;
}
for(int i = nBonuses - 1; i < 6; ++i)
{
D2Common_10574(pItem, gnItemSetStates[i], TRUE);
}
}
return TRUE;
}
//D2Common.0x6FDA4490
//TODO: Find a name
BOOL __fastcall sub_6FDA4490(D2UnitStrc* pUnit, D2UnitStrc* pItem, int a3)
{
D2SetItemsTxt* pSetItemsTxtRecord = NULL;
D2StatListStrc* pStatList = NULL;
int nFileIndex = 0;
int nIndex = 0;
int nValue = 0;
if (a3 <= 1 && pUnit && pItem && pItem->dwUnitType == UNIT_ITEM && ITEMS_GetItemQuality(pItem) == ITEMQUAL_SET && (pUnit->dwUnitType != UNIT_ITEM || !ITEMS_IsMagSetRarUniCrfOrTmp(pUnit)))
{
nFileIndex = ITEMS_GetFileIndex(pItem);
if (nFileIndex >= 0 && nFileIndex < sgptDataTables->nSetItemsTxtRecordCount)
{
pSetItemsTxtRecord = &sgptDataTables->pSetItemsTxt[nFileIndex];
if (pSetItemsTxtRecord && pSetItemsTxtRecord->nSetId >= 0 && pSetItemsTxtRecord->nSetId < sgptDataTables->nSetsTxtRecordCount)
{
nValue = pSetItemsTxtRecord->nSetId;
nIndex = -1;
for (int i = 0; i < 6; ++i)
{
pStatList = STATLIST_GetStatListFromUnitAndState(pUnit, gnItemSetStates[i]);
if (pStatList)
{
if (nValue == STATLIST_GetStatValue(pStatList, STAT_VALUE, 0))
{
if (a3 == 0)
{
STATLIST_RemoveAllStats(pStatList);
STATLIST_AddStat(pStatList, STAT_VALUE, nValue, 0);
ITEMMODS_UpdateFullSetBoni(pUnit, pItem, gnItemSetStates[i]);
}
else if (a3 == 1)
{
D2Common_10474(pUnit, pStatList);
STATLIST_FreeStatList(pStatList);
}
return TRUE;
}
}
else if (nIndex < 0)
{
nIndex = i;
}
}
if (a3 == 1 || nIndex < 0)
{
return FALSE;
}
pStatList = STATLIST_AllocStatList(pUnit->pMemoryPool, 0, 0, pItem->dwUnitType, pItem->dwUnitId);
D2COMMON_10475_PostStatToStatList(pUnit, pStatList, 1);
STATLIST_SetState(pStatList, gnItemSetStates[nIndex]);
if (a3 == 0)
{
STATLIST_AddStat(pStatList, STAT_VALUE, nValue, 0);
ITEMMODS_UpdateFullSetBoni(pUnit, pItem, gnItemSetStates[nIndex]);
}
//else if (a3 == 1)
//{
// D2Common_10474(pUnit, pStatList);
// STATLIST_FreeStatList(pStatList);
//}
return TRUE;
}
}
}
return FALSE;
}
//D2Common.0x6FDA4640 (#10866)
BOOL __stdcall ITEMS_UpdateSets(D2UnitStrc* pUnit, D2UnitStrc* pItem, int a3, int a4)
{
unsigned int nSetItemMask = 0;
if (pUnit && pItem && pItem->dwUnitType == UNIT_ITEM && pUnit->pInventory)
{
if (INVENTORY_IsItemInInventory(pUnit->pInventory, pItem) && INVENTORY_GetItemNodePage(pItem) == 3)
{
nSetItemMask = ITEMS_GetSetItemsMask(pUnit, pItem, TRUE);
}
if (a4 || !a3)
{
sub_6FDA4380(pItem, nSetItemMask);
}
sub_6FDA4490(pUnit, pItem, a3);
return TRUE;
}
return FALSE;
}
| 25.696934 | 232 | 0.702981 | raumuongluoc |
6335d7f36b845fd556117015a46314f05aeccb04 | 440 | cc | C++ | lib/lf/base/lf_assert.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | lib/lf/base/lf_assert.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | lib/lf/base/lf_assert.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | /** @file lf_assert.cc */
#include "lf_assert.h"
#include <iostream>
namespace lf::base {
// Output for assertions
void AssertionFailed(const std::string& expr, const std::string& file, int line,
const std::string& msg) {
std::cerr << "***** Internal Program Error - assertion (" << expr
<< ") failed:\n"
<< file << '(' << line << "): " << msg << std::endl;
}
} // end namespace lf::base
| 25.882353 | 80 | 0.552273 | Pascal-So |
63365c091173ab941fac5cf8a42e8a1fb9a587e9 | 11,052 | hxx | C++ | tests/testing_factor_node_unsym.hxx | tasseff/SyLVER | 35cb652ece05447ddf12e530e97428078446eaf4 | [
"BSD-3-Clause"
] | 9 | 2019-07-02T12:46:22.000Z | 2021-07-08T11:54:46.000Z | tests/testing_factor_node_unsym.hxx | tasseff/SyLVER | 35cb652ece05447ddf12e530e97428078446eaf4 | [
"BSD-3-Clause"
] | 2 | 2020-03-23T22:55:52.000Z | 2020-03-24T11:15:16.000Z | tests/testing_factor_node_unsym.hxx | tasseff/SyLVER | 35cb652ece05447ddf12e530e97428078446eaf4 | [
"BSD-3-Clause"
] | 5 | 2019-06-10T11:11:14.000Z | 2020-03-22T02:38:12.000Z | #pragma once
// SpLDLT
#include "SymbolicFront.hxx"
#include "NumericFront.hxx"
#include "factor_unsym.hxx"
#include "kernels/lu_nopiv.hxx"
#include "sylver_ciface.hxx"
// SSIDS
#include "ssids/cpu/cpu_iface.hxx"
namespace sylver {
namespace splu {
namespace tests {
/// @param T working precision
/// @param FactorAllocator memory allocator for factors
/// @param m number of rows/columns in the front
/// @param k number of columns to eliminate
template<typename T, typename FactorAllocator>
int factor_node_unsym_test(
struct spral::ssids::cpu::cpu_factor_options& options, int m, int k,
int ncpu, int ngpu, bool diagdom, bool check) {
bool failed = false;
int blksz = options.cpu_block_size;
printf("[factor_node_unsym_test] m = %d\n", m);
printf("[factor_node_unsym_test] k = %d\n", k);
printf("[factor_node_unsym_test] blksz = %d\n", blksz);
printf("[factor_node_unsym_test] u = %e\n", options.u);
// We don't allow these cases
ASSERT_TRUE(k > 0);
ASSERT_TRUE(m > 0);
ASSERT_TRUE(ncpu > 0);
ASSERT_TRUE(ngpu >= 0);
ASSERT_TRUE(m >= k);
////////////////////////////////////////
// Init test problem
// Generate test matrix
int lda = spral::ssids::cpu::align_lda<T>(m);
printf("[factor_node_unsym_test] lda = %d\n", lda);
T* a = nullptr;
T* b = nullptr;
////////////////////////////////////////
// Setup front
// Setup pool allocator
typedef spldlt::BuddyAllocator<T,std::allocator<T>> PoolAllocator;
// typedef spral::ssids::cpu::BuddyAllocator<T, std::allocator<T>> PoolAllocator;
PoolAllocator pool_alloc(m*m);
// Setup symbolic front
spldlt::SymbolicFront sfront;
sfront.nrow = m;
sfront.ncol = k;
spldlt::NumericFront<T, PoolAllocator> front(sfront, pool_alloc, blksz);
front.ndelay_in = 0; // No incoming delayed columns
front.ndelay_out = 0;
// Allocate factors
FactorAllocator factor_alloc;
size_t lenL = lda*k; // Size of L
// Allocate L factor (size m x k). Contains U factors in the upper triangular part
front.lcol = factor_alloc.allocate(lenL);
// Allocate U factor (size k x (m-k))
int ldu = spral::ssids::cpu::align_lda<T>(k);
size_t lenU = ldu*(m-k); // Size of U
front.ucol = factor_alloc.allocate(lenU);
// Generate factors
if (check) {
a = new T[lda*m];
// if (diagdom) gen_unsym_diagdom(m, a, lda);
if (diagdom) gen_unsym_diagdomblock(m, a, lda, blksz);
else gen_mat(m, m, a, lda);
print_mat_unsym(" %6.2f", m, a, lda);
b = new T[m];
gen_unsym_rhs(m, a, lda, b);
// Copy A in L
memcpy(front.lcol, a, lda*k*sizeof(T));
// Copy A in U
if (m > k) {
for (int j = 0; j < m-k; ++j)
memcpy(&front.ucol[j*ldu], &a[j*lda], k*sizeof(T));
}
}
else {
ASSERT_TRUE(m == k); // FIXME: does not work for non square fronts
if (diagdom) gen_unsym_diagdom(m, front.lcol, lda);
else gen_mat(m, m, front.lcol, lda);
}
// Alloc blocks in the factors
front.alloc_blocks_unsym();
// Allocate contribution blocks
front.alloc_contrib_blocks_unsym();
if (options.pivot_method == spral::ssids::cpu::PivotMethod::app_block) {
// Allocate backups of blocks
front.alloc_backup_blocks_unsym();
// Setup colulm data
front.alloc_cdata(); // TODO only if piv strategy is APTP
}
// Setup permutation vector
// Row permutation
front.perm = new int[m];
for(int i=0; i<m; i++) front.perm[i] = i;
// Column permutation
front.cperm = new int[m];
for(int i=0; i<m; i++) front.cperm[i] = i;
////////////////////////////////////////
// Launch runtime system
#if defined(SPLDLT_USE_STARPU)
struct starpu_conf conf;
starpu_conf_init(&conf);
conf.ncpus = ncpu;
conf.sched_policy_name = "lws";
int ret;
ret = starpu_init(&conf);
STARPU_CHECK_RETURN_VALUE(ret, "starpu_init");
#endif
////////////////////////////////////////
// Create workspaces
int nworkers = 1;
#if defined(SPLDLT_USE_STARPU)
nworkers = starpu_worker_get_count();
// #else
// nworkers = omp_get_num_threads();
#endif
std::vector<spral::ssids::cpu::ThreadStats> worker_stats(nworkers);
std::vector<spral::ssids::cpu::Workspace> workspaces;
const int PAGE_SIZE = 8*1024*1024; // 8 MB
workspaces.reserve(nworkers);
for(int i = 0; i < nworkers; ++i)
workspaces.emplace_back(PAGE_SIZE);
printf("[factor_node_indef_test] nworkers = %d\n", nworkers);
////////////////////////////////////////
// Register data in runtime system
#if defined(SPLDLT_USE_STARPU)
// TODO
#endif
////////////////////////////////////////
// Perform factorization
printf("[factor_node_unsym_test] Factor..\n");
auto start = std::chrono::high_resolution_clock::now();
switch (options.pivot_method) {
case spral::ssids::cpu::PivotMethod::app_aggressive:
// Front factorization using restricted pivoting
factor_front_unsym_rp(front, workspaces);
break;
case spral::ssids::cpu::PivotMethod::app_block:
// Front factorization using restricted pivoting
factor_front_unsym_app(options, front, workspaces);
// Print permutation matrix
printf("cperm = \n");
for (int i=0; i<m; ++i)
printf(" %d ", front.cperm[i]);
printf("\n");
print_mat_unsym(" %6.2f", k, front.lcol, lda, front.perm);
printf("[factor_node_unsym_test] Eliminated pivots = %d\n", front.nelim);
printf("[factor_node_unsym_test] Permute failed\n");
permute_failed_unsym(front);
// Print permutation matrix
printf("cperm = \n");
for (int i=0; i<m; ++i)
printf(" %d ", front.cperm[i]);
printf("\n");
print_mat_unsym(" %6.2f", k, front.lcol, lda, front.perm);
break;
default:
printf("[factor_node_unsym_test] Pivot method not implemented\n");
}
// Wait for completion
#if defined(SPLDLT_USE_STARPU)
starpu_task_wait_for_all();
#endif
auto end = std::chrono::high_resolution_clock::now();
long ttotal =
std::chrono::duration_cast<std::chrono::nanoseconds>
(end-start).count();
////////////////////////////////////////
// Shutdown runtime system
#if defined(SPLDLT_USE_STARPU)
starpu_shutdown();
#endif
////////////////////////////////////////
// Check solution results
if (check) {
int nelim = front.nelim;
int *rperm = front.perm;
int *cperm = front.cperm;
// // Print permutation matrix
// printf("rperm = \n");
// for (int i=0; i<m; ++i)
// printf(" %d ", rperm[i]);
// printf("\n");
// // Print permutation matrix
// printf("cperm = \n");
// for (int i=0; i<m; ++i)
// printf(" %d ", cperm[i]);
// printf("\n");
// Alloc lu array for storing factors
T *lu = factor_alloc.allocate(lda*m);
// Initialize array with zeros
for (int j=0; j<m; ++j)
for (int i=0; i<m; ++i)
lu[i+j*lda] = 0.0;
// Copy factors from lcol into lu array
// Copy only factors (colmuns 1 to k)
memcpy(lu, front.lcol, lda*k*sizeof(T)); // Copy lcol to lu
// print_mat_unsym(" %6.2f", k, lu, lda, rperm);
if (m > k) {
// TODO Copy part from ucol into lu
// TODO Copy cb into lu
}
if (nelim < m) {
printf("[factor_node_unsym_test] Finish off\n");
// Finish off uneliminated entries
lu_pp_factor(
m-nelim, m-nelim, &rperm[nelim], &lu[nelim+nelim*lda], lda,
nelim, &lu[nelim], lda);
print_mat_unsym(" %6.2f", m, lu, lda, rperm);
}
int nrhs = 1;
int ldsoln = m;
T *soln = new T[nrhs*ldsoln];
// Setup permuted rhs
T *pb = new T[m];
for (int i=0; i<m; ++i)
for (int r=0; r<nrhs; ++r)
pb[r*ldsoln+i] = b[r*ldsoln+rperm[i]];
// Copy rhs into solution vector
for(int r=0; r<nrhs; ++r)
memcpy(&soln[r*ldsoln], pb, m*sizeof(T));
// Perform solve
// Fwd substitutuion
lu_nopiv_fwd(m, k, lu, lda, nrhs, soln, ldsoln);
// Bwd substitutuion
lu_nopiv_bwd(m, k, lu, lda, nrhs, soln, ldsoln);
// Permute x
T *psoln = new T[m];
for (int i=0; i<m; ++i)
for (int r=0; r<nrhs; ++r)
psoln[r*ldsoln+i] = soln[r*ldsoln+cperm[i]];
// Calculate bwd error
double bwderr = unsym_backward_error(
m, k, a, lda, b, nrhs, psoln, ldsoln);
printf("bwderr = %le\n", bwderr);
}
////////////////////////////////////////
// Print results
printf("factor time (s) = %e\n", 1e-9*ttotal);
////////////////////////////////////////
// Cleanup memory
if (options.pivot_method == spral::ssids::cpu::PivotMethod::app_block) {
// Allocate backups of blocks
front.release_backup_blocks_unsym();
// Free column data
front.free_cdata();
}
// Cleanup data structures
front.free_contrib_blocks_unsym();
front.free_blocks_unsym();
// Cleanup factors
factor_alloc.deallocate(front.lcol, lenL);
factor_alloc.deallocate(front.ucol, lenU);
if (check) {
delete[] a;
delete[] b;
}
return failed ? -1 : 0;
}
}}} // End of namespace spylver::splu::tests
| 32.795252 | 92 | 0.491857 | tasseff |
6336af14cb080015d674299c2b778c6597206349 | 692 | cpp | C++ | Arrays & Strings/BreakWords.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | null | null | null | Arrays & Strings/BreakWords.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | null | null | null | Arrays & Strings/BreakWords.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | 3 | 2020-10-06T02:57:41.000Z | 2020-10-20T06:54:04.000Z | #include<iostream>
#include<string.h>
using namespace std;
void breakWords(char* S)
{
int j = 0;
int count = 0;
int i = 0;
int n = strlen(S);
while(i<=n){
n = strlen(S);
j = i;
while(S[i] != ' ' || S[i] != '\0'){
i++;
}
count = i-j;
if(count%2 == 0){
int space = j + (count)/2;
for(int z = n; z>=space; z--){
S[z+1] = S[z];
}
S[space] = ' ';
i++;
}
i++;
}
}
int main()
{
char str[100000];
cin.getline(str,100000);
breakWords(str);
cout<<str;
}
| 16.878049 | 44 | 0.348266 | tanmayagarwal06 |
6336bff2c15bf517640b3ca2e8bf426c31964250 | 425 | cpp | C++ | 0001.TwoSum/main.cpp | SumanSudhir/LeetCode | cab5205747b8c1a9d5c27f0e821cf6e6d9ac10d6 | [
"MIT"
] | 1 | 2020-01-13T11:10:35.000Z | 2020-01-13T11:10:35.000Z | 0001.TwoSum/main.cpp | SumanSudhir/LeetCode | cab5205747b8c1a9d5c27f0e821cf6e6d9ac10d6 | [
"MIT"
] | 4 | 2020-01-01T09:47:39.000Z | 2020-04-08T08:34:29.000Z | 0001.TwoSum/main.cpp | SumanSudhir/LeetCode | cab5205747b8c1a9d5c27f0e821cf6e6d9ac10d6 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> out;
for(int i=0;i<nums.size()-1;i++){
for(int j = i+1;j<nums.size();j++){
if((nums[i] + nums[j]) == target){
out.push_back(i);
out.push_back(j);
break;
}
}
}
return out;
}
};
| 20.238095 | 55 | 0.385882 | SumanSudhir |
633812fca97251f92e2181fe6fb38e5394c4015c | 453 | cpp | C++ | android/EuhatExpert/app/src/main/cpp/macHdd.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | android/EuhatExpert/app/src/main/cpp/macHdd.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | android/EuhatExpert/app/src/main/cpp/macHdd.cpp | euhat/EuhatExpert | 3932238a0bd72a8f12b4ae6ced1ade6482228fe0 | [
"BSD-2-Clause"
] | null | null | null | #include "macHdd.h"
#include <common/OpCommon.h>
#include <common/WhCommon.h>
#define INI_SECTION_LOCAL "local"
int isMacHddChanged(DbOpIni &ini, const char *mac)
{
string macsOld = ini.readStr(INI_SECTION_LOCAL, "mac");
if (macsOld.empty())
{
ini.write(INI_SECTION_LOCAL, "mac", mac);
return 0;
}
if (macsOld != mac)
{
ini.write(INI_SECTION_LOCAL, "mac", mac);
return 1;
}
return 0;
} | 19.695652 | 59 | 0.613687 | euhat |
6338c7e8c42fc5400a25449a33d690cf9f59cc55 | 8,304 | cpp | C++ | src/retroplug/luawrapper/Common.cpp | fossabot/RetroPlug | 5a39379bd10d2e2c0b13a0850380db4d5a58cdd3 | [
"MIT"
] | 186 | 2019-05-14T15:15:33.000Z | 2022-03-21T22:27:10.000Z | src/retroplug/luawrapper/Common.cpp | fossabot/RetroPlug | 5a39379bd10d2e2c0b13a0850380db4d5a58cdd3 | [
"MIT"
] | 24 | 2019-05-14T14:27:24.000Z | 2022-02-17T19:23:19.000Z | src/retroplug/luawrapper/Common.cpp | fossabot/RetroPlug | 5a39379bd10d2e2c0b13a0850380db4d5a58cdd3 | [
"MIT"
] | 9 | 2019-05-17T08:24:42.000Z | 2021-11-14T12:00:11.000Z | #include "Wrappers.h"
#include <sol/sol.hpp>
#include <iPlug2/IPlug/IPlugConstants.h>
#include "platform/Logger.h"
#include "model/Project.h"
#include "config.h"
#include "platform/Menu.h"
#include "model/ButtonStream.h"
#include "platform/FileDialog.h"
#include "platform/Os.h"
bool isNullPtr(const sol::object o) {
switch (o.get_type()) {
case sol::type::lua_nil: return true;
case sol::type::lightuserdata:
case sol::type::userdata: {
void* p = o.as<void*>();
return p == nullptr;
}
}
return false;
}
void luawrappers::registerCommon(sol::state& s) {
s["isNullPtr"].set_function(isNullPtr);
s["_RETROPLUG_VERSION"].set(PLUG_VERSION_STR);
s["_PROJECT_VERSION"].set(PROJECT_VERSION);
s["_consolePrint"].set_function(consoleLog);
s.new_enum("OperatingSystemType",
"Unknown", os::OperatingSystemType::Unknown,
"Windows", os::OperatingSystemType::Windows,
"MacOs", os::OperatingSystemType::MacOs,
"Linux", os::OperatingSystemType::Linux,
"Web", os::OperatingSystemType::Web
);
s["_OPERATING_SYSTEM"].set(os::CURRENT);
s.new_enum("MenuItemType",
"None", MenuItemType::None,
"SubMenu", MenuItemType::SubMenu,
"Select", MenuItemType::Select,
"MultiSelect", MenuItemType::MultiSelect,
"Separator", MenuItemType::Separator,
"Action", MenuItemType::Action,
"Title", MenuItemType::Title
);
s.new_enum("SystemState",
"Uninitialized", SystemState::Uninitialized,
"Initialized", SystemState::Initialized,
"RomMissing", SystemState::RomMissing,
"Running", SystemState::Running
);
s.new_enum("SystemType",
"Unknown", SystemType::Unknown,
"Placeholder", SystemType::Placeholder,
"SameBoy", SystemType::SameBoy
);
s.new_enum("AudioChannelRouting",
"StereoMixDown", AudioChannelRouting::StereoMixDown,
"TwoChannelsPerChannel", AudioChannelRouting::TwoChannelsPerChannel,
"TwoChannelsPerInstance", AudioChannelRouting::TwoChannelsPerInstance
);
s.new_enum("MidiChannelRouting",
"FourChannelsPerInstance", MidiChannelRouting::FourChannelsPerInstance,
"OneChannelPerInstance", MidiChannelRouting::OneChannelPerInstance,
"SendToAll", MidiChannelRouting::SendToAll
);
s.new_enum("SystemLayout",
"Auto", SystemLayout::Auto,
"Column", SystemLayout::Column,
"Grid", SystemLayout::Grid,
"Row", SystemLayout::Row
);
s.new_enum("SaveStateType",
"Sram", SaveStateType::Sram,
"State", SaveStateType::State
);
s.new_enum("GameboyModel",
"Auto", GameboyModel::Auto,
"Agb", GameboyModel::Agb,
"CgbC", GameboyModel::CgbC,
"CgbE", GameboyModel::CgbE,
"DmgB", GameboyModel::DmgB
);
s.new_enum("DialogType",
"Load", DialogType::Load,
"Save", DialogType::Save,
"Directory", DialogType::Directory
);
s.new_enum("HostType",
"Reaper", iplug::kHostReaper,
"ProTools", iplug::kHostProTools,
"Cubase", iplug::kHostCubase,
"Nuendo", iplug::kHostNuendo,
"Sonar", iplug::kHostSonar,
"Vegas", iplug::kHostVegas,
"FL", iplug::kHostFL,
"Samplitude", iplug::kHostSamplitude,
"AbletonLive", iplug::kHostAbletonLive,
"Tracktion", iplug::kHostTracktion,
"NTracks", iplug::kHostNTracks,
"MelodyneStudio", iplug::kHostMelodyneStudio,
"VSTScanner", iplug::kHostVSTScanner,
"AULab", iplug::kHostAULab,
"Forte", iplug::kHostForte,
"Chainer", iplug::kHostChainer,
"Audition", iplug::kHostAudition,
"Orion", iplug::kHostOrion,
"Bias", iplug::kHostBias,
"SAWStudio", iplug::kHostSAWStudio,
"Logic", iplug::kHostLogic,
"GarageBand", iplug::kHostGarageBand,
"DigitalPerformer", iplug::kHostDigitalPerformer,
"AudioMulch", iplug::kHostAudioMulch,
"StudioOne", iplug::kHostStudioOne,
"VST3TestHost", iplug::kHostVST3TestHost,
"Ardour", iplug::kHostArdour,
"Renoise", iplug::kHostRenoise,
"OpenMPT", iplug::kHostOpenMPT,
"WaveLabElements", iplug::kHostWaveLabElements,
"WaveLab", iplug::kHostWaveLab,
"TwistedWave", iplug::kHostTwistedWave,
"Bitwig", iplug::kHostBitwig,
"Reason", iplug::kHostReason,
"GoldWave5x", iplug::kHostGoldWave5x,
"Waveform", iplug::kHostWaveform,
"Audacity", iplug::kHostAudacity,
"Acoustica", iplug::kHostAcoustica,
"PluginDoctor", iplug::kHostPluginDoctor,
"iZotopeRX", iplug::kHostiZotopeRX,
"SAVIHost", iplug::kHostSAVIHost,
"BlueCat", iplug::kHostBlueCat,
"Standalone", iplug::kHostStandalone,
"WWW", iplug::kHostWWW,
"Unknown", iplug::kHostUnknown
);
s.new_usertype<SameBoySettings>("SameBoySettings",
"model", &SameBoySettings::model,
"gameLink", &SameBoySettings::gameLink,
"skipBootRom", &SameBoySettings::skipBootRom
);
s.new_usertype<Project>("NativeProject",
"path", &Project::path,
"systems", &Project::systems,
"settings", &Project::settings,
"selectedSystem", &Project::selectedSystem
);
s.new_usertype<Project::Settings>("ProjectSettings",
"audioRouting", &Project::Settings::audioRouting,
"midiRouting", &Project::Settings::midiRouting,
"layout", &Project::Settings::layout,
"zoom", &Project::Settings::zoom,
"saveType", &Project::Settings::saveType,
"includeRom", &Project::Settings::includeRom
);
s.new_usertype<GameboyButtonStream>("GameboyButtonStream",
"hold", &GameboyButtonStream::hold,
"release", &GameboyButtonStream::release,
"releaseAll", &GameboyButtonStream::releaseAll,
"delay", &GameboyButtonStream::delay,
"press", &GameboyButtonStream::press,
"holdDuration", &GameboyButtonStream::holdDuration,
"releaseDuration", &GameboyButtonStream::releaseDuration,
"releaseAllDuration", &GameboyButtonStream::releaseAllDuration
);
s.new_usertype<Select>("Select", sol::base_classes, sol::bases<MenuItemBase>());
s.new_usertype<Action>("Action", sol::base_classes, sol::bases<MenuItemBase>());
s.new_usertype<MultiSelect>("MultiSelect", sol::base_classes, sol::bases<MenuItemBase>());
s.new_usertype<Title>("Title", sol::base_classes, sol::bases<MenuItemBase>());
s.new_usertype<Separator>("Separator", sol::base_classes, sol::bases<MenuItemBase>());
s.new_usertype<Menu>("Menu", "addItem", &Menu::addItem, sol::base_classes, sol::bases<MenuItemBase>());
// TODO: The following should be allocated from a pool/factory
s.create_named_table("MenuAlloc",
"root", []() { return new Menu(); },
"menu", [](const std::string& name, bool active, Menu* parent) { return new Menu(name, active, parent); },
"title", [](const std::string& name) { return new Title(name); },
"select", [](const std::string& name, bool checked, bool active, int id) { return new Select(name, checked, nullptr, active, id); },
"action", [](const std::string& name, bool active, int id) { return new Action(name, nullptr, active, id); },
"multiSelect", [](const sol::as_table_t<std::vector<std::string>>& items, int value, bool active, int id) { return new MultiSelect(items.value(), value, nullptr, active, id); },
"separator", []() { return new Separator(); }
);
s.new_usertype<DataBuffer<char>>("DataBuffer",
"new", sol::factories(
[]() { return std::make_shared<DataBuffer<char>>(); },
[](size_t size) { return std::make_shared<DataBuffer<char>>(size); }
),
"get", &DataBuffer<char>::get,
"set", &DataBuffer<char>::set,
"slice", [](DataBuffer<char>& buffer, size_t pos, size_t size) {
return std::make_shared<DataBuffer<char>>(buffer.slice(pos, size));
},
"toString", &DataBuffer<char>::toString,
"hash", &DataBuffer<char>::hash,
"size", &DataBuffer<char>::size,
"clear", &DataBuffer<char>::clear,
"resize", &DataBuffer<char>::resize,
"reserve", &DataBuffer<char>::reserve,
"copyTo", &DataBuffer<char>::copyTo,
"copyFrom", &DataBuffer<char>::copyFrom,
"clone", [](const DataBuffer<char>& buffer) {
return std::make_shared<DataBuffer<char>>(std::move(buffer.clone()));
},
"readUint32", &DataBuffer<char>::readUint32,
"readInt32", &DataBuffer<char>::readInt32
);
s.new_usertype<FileDialogFilters>("FileDialogFilters",
"name", &FileDialogFilters::name,
"extensions", &FileDialogFilters::extensions
);
s.new_usertype<DialogRequest>("DialogRequest",
"new", sol::factories([]() { return std::make_shared<DialogRequest>(); }),
"type", &DialogRequest::type,
"filters", &DialogRequest::filters,
"multiSelect", &DialogRequest::multiSelect,
"fileName", &DialogRequest::fileName
);
s.new_usertype<MouseMod>("MouseMod",
"left", &MouseMod::left,
"right", &MouseMod::right
);
}
| 33.349398 | 179 | 0.710983 | fossabot |
633b0d506075e1dfce4c71be4bf01f93c08ec35f | 7,411 | cpp | C++ | src/BldRecons/SPB2BP/ConvertGrid.cpp | liuxinren/UrbanReconstruction | 079d9b0c9089aa9cdb15d31d76155e50a5e72f00 | [
"MIT"
] | 94 | 2017-07-20T05:32:07.000Z | 2022-03-02T03:38:54.000Z | src/BldRecons/SPB2BP/ConvertGrid.cpp | GucciPrada/UrbanReconstruction | 8b058349fd860ea9029623a92d705dd93a4e4878 | [
"MIT"
] | 3 | 2017-09-12T00:07:05.000Z | 2020-03-08T21:12:36.000Z | src/BldRecons/SPB2BP/ConvertGrid.cpp | GucciPrada/UrbanReconstruction | 8b058349fd860ea9029623a92d705dd93a4e4878 | [
"MIT"
] | 38 | 2017-07-25T06:00:52.000Z | 2022-03-19T10:01:06.000Z | #include "StdAfx.h"
#include "ConvertGrid.h"
#include "ParamManager.h"
#include "Miscs\TimeMeter.h"
CConvertGrid::CConvertGrid(void)
{
}
CConvertGrid::~CConvertGrid(void)
{
}
void CConvertGrid::Convert()
{
CParamManager * manager = CParamManager::GetParamManager();
CTimeMeter timer;
timer.Start();
fprintf_s( stderr, "==================== Pass 1, count last cell ====================\n" );
InitCount();
fprintf_s( stderr, "Processing progress ... " );
InitPrintProgress();
int index;
while ( ( index = ReadNextChunk() ) != -1 ) {
PrintProgress( );
CConvertChunk * chunk = m_vecPointer[ index ];
CountChunk( chunk );
delete m_vecPointer[ index ];
m_vecPointer[ index ] = NULL;
}
fprintf_s( stderr, " ... done!\n" );
FinCount();
fprintf_s( stderr, "Total processing time is " );
timer.End();
timer.Print();
fprintf_s( stderr, ".\n\n" );
timer.Start();
fprintf_s( stderr, "==================== Pass 2, output ====================\n" );
InitWrite();
fprintf_s( stderr, "Processing progress ... " );
InitPrintProgress();
while ( ( index = ReadNextChunk() ) != -1 ) {
PrintProgress( );
CConvertChunk * chunk = m_vecPointer[ index ];
WriteChunk( chunk );
delete m_vecPointer[ index ];
m_vecPointer[ index ] = NULL;
}
fprintf_s( stderr, " ... done!\n" );
FinWrite();
fprintf_s( stderr, "Total processing time is " );
timer.End();
timer.Print();
fprintf_s( stderr, ".\n" );
}
int CConvertGrid::ReadNextChunk()
{
// return the index of the finalized chunk
// return -1 indicating a EOF has been read
bool bNoneChunkEnd = true;
int index;
while ( bNoneChunkEnd ) {
if ( m_cReader.ReadNextElement() ) { // read chunk information
SPBCell * cell = m_cReader.GetCell();
switch ( cell->type ) {
case 0: // begin chunk
m_vecPointer[ cell->chunk_index ] = new CConvertChunk( cell->chunk_index, cell->point_number, this );
break;
case 1: // end chunk
bNoneChunkEnd = false;
index = cell->chunk_index;
break;
case -1: // EOF
bNoneChunkEnd = false;
index = -1;
break;
}
} else {
SPBPoint * point = m_cReader.GetPoint();
CVector3D v( point->pos[0], point->pos[1], point->pos[2] );
CConvertChunk * chunk = m_vecPointer[ Index( v ) ];
chunk->PushPoint( point );
IncReadNumber();
}
}
return index;
}
//////////////////////////////////////////////////////////////////////////
// main functions
//////////////////////////////////////////////////////////////////////////
void CConvertGrid::InitCount()
{
CParamManager * manager = CParamManager::GetParamManager();
m_cReader.OpenFile( manager->m_pInputFile );
m_cReader.RegisterGrid( this );
m_cReader.ReadHeader();
m_vecPointer.clear();
m_vecPointer.resize( m_nSideNumber * m_nSideNumber, NULL );
m_hashWriterInfo.clear();
m_hashFinalizedPatch.clear();
}
void CConvertGrid::CountChunk( CConvertChunk * chunk )
{
CParamManager * manager = CParamManager::GetParamManager();
double min_z = MinGroundZ( chunk );
for ( int i = 0; i < ( int )( chunk->m_vecPatchPointData.size() ); i++ ) {
PatchPointData & point = chunk->m_vecPatchPointData[ i ];
if ( CheckPoint( point ) ) {
stdext::hash_map< PatchIndex, PatchWriterInfo >::iterator it = m_hashWriterInfo.find( point.patch.base );
if ( it == m_hashWriterInfo.end() ) {
PatchWriterInfo info;
info.begin_cell = chunk->m_iIndex;
info.final_cell = chunk->m_iIndex;
info.ground_z = min_z;
info.number = 1;
m_hashWriterInfo.insert( std::pair< PatchIndex, PatchWriterInfo >( point.patch.base, info ) );
} else {
it->second.final_cell = chunk->m_iIndex;
if ( it->second.ground_z > min_z )
it->second.ground_z = min_z;
it->second.number++;
}
}
}
}
void CConvertGrid::FinCount()
{
m_cReader.CloseFile();
for ( stdext::hash_map< PatchIndex, PatchWriterInfo >::iterator it = m_hashWriterInfo.begin(); it != m_hashWriterInfo.end(); it++ ) {
stdext::hash_map< int, std::vector< PatchIndex > >::iterator itt = m_hashFinalizedPatch.find( it->second.final_cell );
if ( itt == m_hashFinalizedPatch.end() ) {
std::vector< PatchIndex > temp;
temp.push_back( it->first );
m_hashFinalizedPatch.insert( std::pair< int, std::vector< PatchIndex > >( it->second.final_cell, temp ) );
} else {
itt->second.push_back( it->first );
}
}
fprintf_s( stderr, "Total %d roof patch are going to be written.\n", ( int )m_hashWriterInfo.size() );
}
void CConvertGrid::InitWrite()
{
CParamManager * manager = CParamManager::GetParamManager();
m_cReader.OpenFile( manager->m_pInputFile );
m_cReader.RegisterGrid( this );
m_cReader.ReadHeader();
m_vecPointer.clear();
m_vecPointer.resize( m_nSideNumber * m_nSideNumber, NULL );
m_hashWriter.clear();
}
void CConvertGrid::WriteChunk( CConvertChunk * chunk )
{
CParamManager * manager = CParamManager::GetParamManager();
for ( int i = 0; i < ( int )( chunk->m_vecPatchPointData.size() ); i++ ) {
PatchPointData & point = chunk->m_vecPatchPointData[ i ];
if ( CheckPoint( point ) ) {
stdext::hash_map< PatchIndex, CBPWriter >::iterator it = m_hashWriter.find( point.patch.base );
if ( it == m_hashWriter.end() ) {
stdext::hash_map< PatchIndex, PatchWriterInfo >::iterator itinfo = m_hashWriterInfo.find( point.patch.base );
if ( itinfo->second.ground_z == 1e300 ) {
itinfo->second.ground_z = m_cBoundingBox.m_vMin[ 2 ];
}
char filename[ 1024 ];
sprintf_s( filename, 1024, "%sPatch_%016I64x.bp", manager->m_pOutputDir, point.patch.base );
CBPWriter writer;
writer.OpenFile( filename );
writer.WriteHeader( point.patch.base, itinfo->second.number, itinfo->second.ground_z, m_dbGridLength );
writer.WritePoint( point.v.pVec, point.n.pVec, point.flatness, -1 );
m_hashWriter.insert( std::pair< PatchIndex, CBPWriter >( point.patch.base, writer ) );
} else {
it->second.WritePoint( point.v.pVec, point.n.pVec, point.flatness, -1 );
}
}
}
stdext::hash_map< int, std::vector< PatchIndex > >::iterator itt = m_hashFinalizedPatch.find( chunk->m_iIndex );
if ( itt != m_hashFinalizedPatch.end() ) {
std::vector< PatchIndex > & temp = itt->second;
for ( int k = 0; k < ( int )temp.size(); k++ ) {
stdext::hash_map< PatchIndex, CBPWriter >::iterator it = m_hashWriter.find( temp[ k ] );
it->second.CloseFile();
}
}
}
void CConvertGrid::FinWrite()
{
m_cReader.CloseFile();
}
//////////////////////////////////////////////////////////////////////////
// auxiliary functions
//////////////////////////////////////////////////////////////////////////
bool CConvertGrid::CheckPoint( PatchPointData & point )
{
CParamManager * manager = CParamManager::GetParamManager();
if ( manager->m_bClip == false ||
( ( point.v[0] >= manager->m_dbClip[0][0] )
&& ( point.v[0] <= manager->m_dbClip[0][1] )
&& ( point.v[1] >= manager->m_dbClip[1][0] )
&& ( point.v[1] <= manager->m_dbClip[1][1] ) ) )
{
if ( point.type == PT_Building ) {
return true;
}
}
return false;
}
double CConvertGrid::MinGroundZ( CConvertChunk * chunk )
{
double min_z = 1e300;
for ( int i = 0; i < ( int )( chunk->m_vecPatchPointData.size() ); i++ ) {
PatchPointData & point = chunk->m_vecPatchPointData[ i ];
if ( point.type == PT_Ground && point.v[ 2 ] < min_z ) {
min_z = point.v[ 2 ];
}
}
return min_z;
}
| 23.378549 | 134 | 0.622048 | liuxinren |
633bf75ea0674cf4e9ceab5fd13be62ffbc0d4fa | 433 | hpp | C++ | include/particle-system/core/emptyattractor.hpp | semitro/Particle-system | f29e4f6d45132f98b3089f39e0d6c76a1bd63e86 | [
"MIT"
] | null | null | null | include/particle-system/core/emptyattractor.hpp | semitro/Particle-system | f29e4f6d45132f98b3089f39e0d6c76a1bd63e86 | [
"MIT"
] | null | null | null | include/particle-system/core/emptyattractor.hpp | semitro/Particle-system | f29e4f6d45132f98b3089f39e0d6c76a1bd63e86 | [
"MIT"
] | null | null | null | #ifndef EMTPY_ATTRACTOR_HPP
#define EMPTY_ATTRACTOR_HPP
#include "particle-system/core/particle.hpp"
#include "particle-system/core/attractor.hpp"
#include <vector>
#include <cstdlib>
using std::vector;
class EmptyAttractor : public Attractor
{
public:
EmptyAttractor():Attractor(0, 0){}
virtual ~EmptyAttractor(){}
virtual void attract(vector<Particle> &particles,
float deltaTime){}
};
#endif // EMRPTY_ATTRACTOR_HPP
| 20.619048 | 50 | 0.762125 | semitro |
6342a63a5a2c6a869687ad8acb3085a1f4174e46 | 9,579 | cpp | C++ | tests/unittest/test_hetercallbacklist_basic.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 685 | 2018-05-13T03:59:19.000Z | 2022-03-31T22:43:43.000Z | tests/unittest/test_hetercallbacklist_basic.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 32 | 2018-06-01T03:15:13.000Z | 2022-01-18T09:23:06.000Z | tests/unittest/test_hetercallbacklist_basic.cpp | digital-stage/eventpp | a0978f91f9d74a5943ed668b3fe15d64b0675b5c | [
"Apache-2.0"
] | 128 | 2018-05-13T06:41:58.000Z | 2022-03-30T16:58:10.000Z | // eventpp library
// Copyright (C) 2018 Wang Qi (wqking)
// Github: https://github.com/wqking/eventpp
// 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 "test.h"
#include "eventpp/hetercallbacklist.h"
#include <vector>
TEST_CASE("HeterCallbackList, empty")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
SECTION("empty") {
CL callbackList;
REQUIRE(callbackList.empty());
}
SECTION("append") {
CL callbackList;
callbackList.append([](){});
REQUIRE(! callbackList.empty());
}
SECTION("prepend") {
CL callbackList;
callbackList.prepend([](int){});
REQUIRE(! callbackList.empty());
}
SECTION("remove") {
CL callbackList;
auto handle = callbackList.append([](){});
REQUIRE(! callbackList.empty());
callbackList.remove(handle);
REQUIRE(callbackList.empty());
}
}
TEST_CASE("HeterCallbackList, append")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> orderList(5);
int order;
callbackList.append([&orderList, &order]() {
orderList[order++] = 1;
});
callbackList.append([&orderList, &order]() {
orderList[order++] = 2;
});
callbackList.append([&orderList, &order](int) {
orderList[order++] = 3;
});
callbackList.append([&orderList, &order](int) {
orderList[order++] = 4;
});
callbackList.append([&orderList, &order](int) {
orderList[order++] = 5;
});
REQUIRE(orderList == std::vector<int>{ 0, 0, 0, 0, 0 });
order = 0;
callbackList(3);
REQUIRE(orderList == std::vector<int>{ 3, 4, 5, 0, 0 });
callbackList();
REQUIRE(orderList == std::vector<int>{ 3, 4, 5, 1, 2 });
}
TEST_CASE("HeterCallbackList, prepend")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> orderList(5);
int order;
callbackList.prepend([&orderList, &order]() {
orderList[order++] = 1;
});
callbackList.prepend([&orderList, &order]() {
orderList[order++] = 2;
});
callbackList.prepend([&orderList, &order](int) {
orderList[order++] = 3;
});
callbackList.prepend([&orderList, &order](int) {
orderList[order++] = 4;
});
callbackList.prepend([&orderList, &order](int) {
orderList[order++] = 5;
});
REQUIRE(orderList == std::vector<int>{ 0, 0, 0, 0, 0 });
order = 0;
callbackList(3);
REQUIRE(orderList == std::vector<int>{ 5, 4, 3, 0, 0 });
callbackList();
REQUIRE(orderList == std::vector<int>{ 5, 4, 3, 2, 1 });
}
TEST_CASE("HeterCallbackList, insert")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> orderList(5);
int order;
auto h1 = callbackList.append([&orderList, &order]() {
orderList[order++] = 1;
});
callbackList.insert([&orderList, &order]() {
orderList[order++] = 2;
}, h1);
auto h2 = callbackList.append([&orderList, &order](int) {
orderList[order++] = 3;
});
callbackList.insert([&orderList, &order](int) {
orderList[order++] = 4;
}, h2);
// Increase h2.index to trigger the check `if(before.index != PrototypeInfo::index)` in HeterCallbackList::insert
// This works as if the callback is appended rather than inserted.
++h2.index;
callbackList.insert([&orderList, &order](int) {
orderList[order++] = 5;
}, h2);
REQUIRE(orderList == std::vector<int>{ 0, 0, 0, 0, 0 });
order = 0;
callbackList(3);
REQUIRE(orderList == std::vector<int>{ 4, 3, 5, 0, 0 });
callbackList();
REQUIRE(orderList == std::vector<int>{ 4, 3, 5, 2, 1 });
}
TEST_CASE("HeterCallbackList, remove")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void (int)> >;
CL callbackList;
std::vector<int> dataList(5);
auto h1 = callbackList.append([&dataList]() {
++dataList[0];
});
auto h2 = callbackList.append([&dataList]() {
++dataList[1];
});
auto h3 = callbackList.append([&dataList](int) {
++dataList[2];
});
auto h4 = callbackList.append([&dataList](int) {
++dataList[3];
});
auto h5 = callbackList.append([&dataList](int) {
++dataList[4];
});
REQUIRE(dataList == std::vector<int>{ 0, 0, 0, 0, 0 });
// Remove non-exist handle
REQUIRE(! callbackList.remove(decltype(h1)()));
callbackList(3);
REQUIRE(dataList == std::vector<int>{ 0, 0, 1, 1, 1 });
callbackList();
REQUIRE(dataList == std::vector<int>{ 1, 1, 1, 1, 1 });
REQUIRE(callbackList.remove(h2));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 2, 1, 2, 2, 2 });
// double remove, no effect
REQUIRE(! callbackList.remove(h2));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 3, 1, 3, 3, 3 });
REQUIRE(callbackList.remove(h3));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 4, 1, 3, 4, 4 });
REQUIRE(callbackList.remove(h5));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 5, 1, 3, 5, 4 });
REQUIRE(callbackList.remove(h1));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 5, 1, 3, 6, 4 });
REQUIRE(callbackList.remove(h4));
callbackList(3);
callbackList();
REQUIRE(dataList == std::vector<int>{ 5, 1, 3, 6, 4 });
}
TEST_CASE("HeterCallbackList, forEach")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<int (), int(int)> >;
CL callbackList;
callbackList.append([]() { return 1; });
callbackList.append([]() { return 2; });
callbackList.append([]() { return 3; });
callbackList.append([](int n) { return n + 5 + 0; });
callbackList.append([](int n) { return n + 5 + 1; });
callbackList.append([](int n) { return n + 5 + 2; });
int i = 1;
callbackList.forEach<int ()>([&i](auto callback) {
REQUIRE(callback() == i);
++i;
});
i = 0;
callbackList.forEach<int (int)>([&i](const std::function<int (int)> & callback) {
REQUIRE(callback(3) == 8 + i);
++i;
});
}
TEST_CASE("HeterCallbackList, forEachIf")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void(int)> >;
CL callbackList;
std::vector<int> dataListNoArg(3);
std::vector<int> dataListWithArg(3);
callbackList.append([&dataListNoArg]() {
dataListNoArg[0] += 1;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[1] += 2;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[2] += 3;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[0] += n;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[1] += n * 2;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[2] += n * 3;
});
REQUIRE(dataListNoArg == std::vector<int>{ 0, 0, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
int i = 0;
bool result = callbackList.forEachIf<void ()>([&i](const std::function<void ()> & callback) -> bool {
callback();
++i;
return i != 2;
});
REQUIRE(! result);
REQUIRE(dataListNoArg == std::vector<int>{ 1, 2, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
i = 0;
result = callbackList.forEachIf<void (int)>([&i](const std::function<void (int)> & callback) -> bool {
callback(3);
++i;
return i != 1;
});
REQUIRE(! result);
REQUIRE(dataListNoArg == std::vector<int>{ 1, 2, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 3, 0, 0 });
}
TEST_CASE("HeterCallbackList, invoke")
{
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (), void(int)> >;
CL callbackList;
std::vector<int> dataListNoArg(3);
std::vector<int> dataListWithArg(3);
callbackList.append([&dataListNoArg]() {
dataListNoArg[0] += 1;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[1] += 2;
});
callbackList.append([&dataListNoArg]() {
dataListNoArg[2] += 3;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[0] += n;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[1] += n * 2;
});
callbackList.append([&dataListWithArg](int n) {
dataListWithArg[2] += n * 3;
});
REQUIRE(dataListNoArg == std::vector<int>{ 0, 0, 0 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
callbackList();
REQUIRE(dataListNoArg == std::vector<int>{ 1, 2, 3 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
callbackList();
REQUIRE(dataListNoArg == std::vector<int>{ 2, 4, 6 });
REQUIRE(dataListWithArg == std::vector<int>{ 0, 0, 0 });
callbackList(1);
REQUIRE(dataListNoArg == std::vector<int>{ 2, 4, 6 });
REQUIRE(dataListWithArg == std::vector<int>{ 1, 2, 3 });
callbackList(2);
REQUIRE(dataListNoArg == std::vector<int>{ 2, 4, 6 });
REQUIRE(dataListWithArg == std::vector<int>{ 3, 6, 9 });
}
TEST_CASE("HeterCallbackList, prototype convert")
{
struct MyClass
{
MyClass(int) {}
};
using CL = eventpp::HeterCallbackList<eventpp::HeterTuple<void (int)> >;
CL callbackList;
std::vector<int> dataList(2);
callbackList.append([&dataList](int) {
++dataList[0];
});
callbackList.append([&dataList](const MyClass &) {
++dataList[1];
});
REQUIRE(dataList == std::vector<int>{ 0, 0 });
callbackList((int)5);
REQUIRE(dataList == std::vector<int>{ 1, 1 });
callbackList((char)5);
REQUIRE(dataList == std::vector<int>{ 2, 2 });
}
| 25.408488 | 114 | 0.649024 | digital-stage |
6345730d11666a9992159533a2677a96ed7e8752 | 347 | cpp | C++ | TrainingWithBook/JumpingBinarySearch.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/JumpingBinarySearch.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | TrainingWithBook/JumpingBinarySearch.cpp | andzh1/Competitive-programming | babb9494e03fe0feb2130e50887996d0ffc92c4e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define loop(a,b) for(int i = a; i < b; i++)
int main(){
int n = 5, wanted = 5;
int array[] = {1,2,3,4,5};
int k = 0;
for(int b = n/2; b >= 1; b /= 2){
while(k + b < n && array[k+b] <= wanted) k += b;
}
if(array[k] == wanted){
//we got wanted value
}
}
| 20.411765 | 56 | 0.458213 | andzh1 |
63489ad56bf0b0d5a22c5bbb6c18274404087dd7 | 2,306 | cpp | C++ | STM32F1/libraries/MakeArduino_Examples/examples/MakeArduino_F103Rx_UsbCardReader/app_usb_mass.cpp | iamdev/MakeArduino_STM32 | 3dba2f132082d63cdbb318ba0fcc1df6d382227a | [
"Unlicense"
] | null | null | null | STM32F1/libraries/MakeArduino_Examples/examples/MakeArduino_F103Rx_UsbCardReader/app_usb_mass.cpp | iamdev/MakeArduino_STM32 | 3dba2f132082d63cdbb318ba0fcc1df6d382227a | [
"Unlicense"
] | null | null | null | STM32F1/libraries/MakeArduino_Examples/examples/MakeArduino_F103Rx_UsbCardReader/app_usb_mass.cpp | iamdev/MakeArduino_STM32 | 3dba2f132082d63cdbb318ba0fcc1df6d382227a | [
"Unlicense"
] | null | null | null | #include "app_usb_mass.h"
#include "app_sdfat.h"
#define DEBUG_READ_WRITE 0
bool sd_write_buffer(uint32_t memoryOffset, const uint8_t *writebuff, uint16_t transferLength)
{
digitalWrite(LED_BUILTIN,LOW);
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
Serial.print("Write [0x");
Serial.print(memoryOffset,HEX);
Serial.print(":");
Serial.print(transferLength,DEC);
Serial.print("]...");
#endif
bool ret = sd.card()->writeBlocks(memoryOffset/512, writebuff, transferLength/512);
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
if(ret)
Serial.println("Pass");
else
Serial.println("Fail");
#endif
digitalWrite(LED_BUILTIN,HIGH);
return ret;
}
bool sd_read_buffer(uint32_t memoryOffset, uint8_t *readbuff, uint16_t transferLength) {
digitalWrite(LED_BUILTIN,LOW);
int c = 0;
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
Serial.print("Read [0x");
Serial.print(memoryOffset,HEX);
Serial.print(":");
Serial.print(transferLength,DEC);
Serial.print("]...");
#endif
bool ret= sd.card()->readBlocks(memoryOffset/512, readbuff, transferLength/512);
#if SERIAL_DEBUG >0 && DEBUG_SD_INFO > 0 && DEBUG_READ_WRITE > 0
if(ret)
Serial.println("Pass");
else
Serial.println("Fail");
c = 0;
CompositeSerial.print("Read [0x");
CompositeSerial.print(memoryOffset,HEX);
CompositeSerial.print(":");
CompositeSerial.print(transferLength,DEC);
CompositeSerial.println("]");
while(c<transferLength){
for(int i=0;i<32;i++){
uint8_t v = readbuff[c++];
if(v<0x10)CompositeSerial.print("0");
CompositeSerial.print(v,HEX);
CompositeSerial.print(" ");
}
CompositeSerial.println();
}
#endif
digitalWrite(LED_BUILTIN,HIGH);
return ret;
}
void init_reader() {
Serial.println(F("Initialize USB Mass Storage"));
cardSize = sd.card()->cardSize();
USBComposite.setProductId(PRODUCT_ID);
MassStorage.setDrive(0, cardSize*512, sd_read_buffer, sd_write_buffer);
MassStorage.registerComponent();
CompositeSerial.registerComponent();
USBComposite.begin();
digitalWrite(USB_DESC_PIN,HIGH);
usb_mass_enabled=true;
}
void usb_mass_loop(){
if (!usb_mass_enabled) {
init_reader();
}
else {
MassStorage.loop();
}
}
| 26.813953 | 95 | 0.691674 | iamdev |
634c5a28e779a93d5770eaecfa8fbc46d2f4cad5 | 3,852 | cpp | C++ | src/skylines_engine/queries/algorithms/single_thread_sorting.cpp | gggprojects/skylines | 1b0d204f1fbb8e24af026723ba9887988798c974 | [
"MIT"
] | null | null | null | src/skylines_engine/queries/algorithms/single_thread_sorting.cpp | gggprojects/skylines | 1b0d204f1fbb8e24af026723ba9887988798c974 | [
"MIT"
] | null | null | null | src/skylines_engine/queries/algorithms/single_thread_sorting.cpp | gggprojects/skylines | 1b0d204f1fbb8e24af026723ba9887988798c974 | [
"MIT"
] | 1 | 2018-08-31T15:53:36.000Z | 2018-08-31T15:53:36.000Z | #include <iostream>
#include "queries/algorithms/single_thread_sorting.hpp"
#include "common/time.hpp"
namespace sl { namespace queries { namespace algorithms {
data::Statistics SingleThreadSorting::Run(NonConstData<data::WeightedPoint> *output, DistanceType distance_type) {
if (!Init(output)) return data::Statistics();
return Compute(output, distance_type);
}
template<class Comparator, class Sorter>
data::Statistics SingleThreadSorting::ComputeSkylines(
Comparator comparator_function,
Sorter sorter_function,
std::vector<data::WeightedPoint> *skylines) {
data::Statistics stats_results;
const sl::queries::data::Point *input_q = input_q_.GetPoints().data();
const int q_size = static_cast<int>(input_q_.GetPoints().size());
NonConstData<data::WeightedPoint> sorted_input;
//copy P
sorted_input = input_p_;
//sorting depending on function
std::sort(sorted_input.Points().begin(), sorted_input.Points().end(), sorter_function);
//the first element is skyline
skylines->emplace_back(sorted_input.GetPoints()[0]);
std::vector<data::WeightedPoint>::const_iterator first_element = sorted_input.GetPoints().cbegin();
std::vector<data::WeightedPoint>::const_iterator last_element = sorted_input.GetPoints().cend();
std::vector<data::WeightedPoint>::const_iterator skyline_candidate;
for (skyline_candidate = first_element + 1;
skyline_candidate != last_element;
++skyline_candidate) {
std::vector<data::WeightedPoint>::const_iterator skyline_element = skylines->cbegin();
bool is_skyline = true;
while (is_skyline && skyline_element != skylines->cend()) {
if (IsDominated(*skyline_candidate, *skyline_element, input_q, q_size, &stats_results.num_comparisions_, comparator_function)) {
is_skyline = false;
}
skyline_element++;
}
if (is_skyline) {
skylines->emplace_back(*skyline_candidate);
}
}
return stats_results;
}
template<class Comparator, class Sorter>
data::Statistics SingleThreadSorting::_Compute(Comparator comparator_function, Sorter sorter_function, NonConstData<data::WeightedPoint> *output) {
std::vector<data::WeightedPoint> skylines;
data::Statistics stats_results = ComputeSkylines(comparator_function, sorter_function, &skylines);
ComputeTopK(skylines, output);
stats_results.output_size_ = output->GetPoints().size();
return stats_results;
}
data::Statistics SingleThreadSorting::Compute(NonConstData<data::WeightedPoint> *output, DistanceType distance_type) {
//std::cout << "Computing STS\n";
const data::Point &first_q = input_q_.GetPoints()[0];
switch (distance_type) {
case sl::queries::algorithms::DistanceType::Nearest:
return _Compute(
[](const float a, const float b) -> bool { return a <= b; },
[&first_q](const data::WeightedPoint &a, const data::WeightedPoint &b) -> bool { return a.SquaredDistance(first_q) < b.SquaredDistance(first_q); },
output);
break;
case sl::queries::algorithms::DistanceType::Furthest:
return _Compute(
[](const float a, const float b) -> bool { return a >= b; },
[&first_q](const data::WeightedPoint &a, const data::WeightedPoint &b) -> bool { return a.SquaredDistance(first_q) > b.SquaredDistance(first_q); },
output);
break;
default:
break;
}
return data::Statistics();
}
}}}
| 43.280899 | 167 | 0.631101 | gggprojects |
634d33823e408bf68ace8adaac3ef32e177f3b99 | 3,059 | cpp | C++ | fboss/agent/hw/bcm/tests/BcmVlanTests.cpp | dendisuhubdy/fboss | 89deb9468f647f2a56da55c7ed8f36e7e1151b4e | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/bcm/tests/BcmVlanTests.cpp | dendisuhubdy/fboss | 89deb9468f647f2a56da55c7ed8f36e7e1151b4e | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/bcm/tests/BcmVlanTests.cpp | dendisuhubdy/fboss | 89deb9468f647f2a56da55c7ed8f36e7e1151b4e | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/bcm/tests/BcmTest.h"
#include "fboss/agent/ApplyThriftConfig.h"
#include "fboss/agent/FbossError.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/hw/bcm/tests/platforms/BcmTestPlatform.h"
#include "fboss/agent/state/SwitchState.h"
#include "fboss/agent/state/StateDelta.h"
#include "fboss/agent/state/Vlan.h"
#include "fboss/agent/state/VlanMap.h"
#include "fboss/agent/gen-cpp2/switch_config_types.h"
#include "fboss/agent/hw/bcm/tests/BcmPortUtils.h"
#include "fboss/agent/hw/test/ConfigFactory.h"
#include <string>
extern "C" {
#include <opennsl/port.h>
}
using std::make_shared;
using std::shared_ptr;
using std::string;
namespace {
using namespace facebook::fboss;
typedef std::vector<opennsl_vlan_data_t> VlanVector;
VlanVector listVlans(int unit) {
opennsl_vlan_data_t* vlanList = nullptr;
int vlanCount = 0;
auto rv = opennsl_vlan_list(unit, &vlanList, &vlanCount);
facebook::fboss::bcmCheckError(rv, "failed to list all VLANs");
return VlanVector(vlanList, vlanList + vlanCount);
}
} // unnamed namespace
namespace facebook {
namespace fboss {
class BcmVlanTest : public BcmTest {
protected:
cfg::SwitchConfig initialConfig() const override {
return utility::twoL3IntfConfig(getHwSwitch(),
masterLogicalPortIds()[0], masterLogicalPortIds()[1]);
}
};
TEST_F(BcmVlanTest, VlanInit) {
auto setup = [=]() { return getProgrammedState(); };
auto verify = [=]() {
// Make sure there are still no VLANs except the default VLAN
ASSERT_EQ(1, listVlans(getUnit()).size());
};
verifyAcrossWarmBoots(setup, verify);
}
TEST_F(BcmVlanTest, VlanApplyConfig) {
auto setup = [=]() {
return applyNewConfig(initialConfig());
};
auto verify = [=]() {
// There should be 2 VLANs
auto vlan_data_list = listVlans(getUnit());
ASSERT_EQ(3, vlan_data_list.size());
// There should be 2 ports
auto ports = {masterLogicalPortIds()[0], masterLogicalPortIds()[1]};
for (auto port : ports) {
ASSERT_TRUE(utility::portEnabled(getUnit(), port));
}
// kBaseVlanId should be associate with 2 ports
std::map<int, int> vlan2PortCount = {
{utility::kBaseVlanId, 2},
{utility::kBaseVlanId + 1, 0},
};
for (auto& vlanData : vlan_data_list) {
if (vlanData.vlan_tag == utility::kDefaultVlanId) {
continue;
}
auto vlanItr = vlan2PortCount.find(vlanData.vlan_tag);
ASSERT_TRUE(vlanItr != vlan2PortCount.end());
int port_count;
OPENNSL_PBMP_COUNT(vlanData.port_bitmap, port_count);
EXPECT_EQ(vlanItr->second, port_count);
}
};
verifyAcrossWarmBoots(setup, verify);
}
} // namespace fboss
} // namespace
| 28.06422 | 79 | 0.700556 | dendisuhubdy |
634dcd61e03217413826471232eb547feeee1daa | 1,145 | cpp | C++ | vegastrike/src/cmd/script/pythonmission.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/src/cmd/script/pythonmission.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | vegastrike/src/cmd/script/pythonmission.cpp | Ezeer/VegaStrike_win32FR | 75891b9ccbdb95e48e15d3b4a9cd977955b97d1f | [
"MIT"
] | null | null | null | #include <Python.h>
#include <math.h>
#include "pythonmission.h"
#include "python/python_compile.h"
#include <string>
#include "pythonmission.h"
#include "python/init.h"
#include <boost/version.hpp>
#if BOOST_VERSION == 102800
#include <boost/python/reference.hpp>
#include <boost/python/callback.hpp>
#endif
#include "vsfilesystem.h"
#include "cmd/container.h"
PythonMissionBaseClass::PythonMissionBaseClass() {}
void PythonMissionBaseClass::Destructor()
{
delete this;
}
PythonMissionBaseClass::~PythonMissionBaseClass()
{
for (unsigned int i = 0; i < relevant_units.size(); ++i) {
relevant_units[i]->SetUnit( NULL );
delete relevant_units[i];
}
relevant_units.clear();
VSFileSystem::vs_fprintf( stderr, "BASE Destruct called. If called from C++ this is death %ld (0x%x)",
(unsigned long) (size_t) this, (unsigned int) (size_t) this );
}
void PythonMissionBaseClass::Execute() {}
void PythonMissionBaseClass::callFunction( std::string ) {}
std::string PythonMissionBaseClass::Pickle()
{
return std::string();
}
void PythonMissionBaseClass::UnPickle( std::string s ) {}
| 27.926829 | 106 | 0.702183 | Ezeer |
634ff123129d4b1a5fc42ca350d23c31bf9127b1 | 7,922 | cpp | C++ | cocos2d-x-2.2/extensions/CocoStudio/ActionTimeline/CCActionTimeline.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 58 | 2015-01-05T04:40:48.000Z | 2021-12-17T06:01:28.000Z | cocos2d-x-2.2/extensions/CocoStudio/ActionTimeline/CCActionTimeline.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 4 | 2021-04-29T06:20:51.000Z | 2021-04-29T15:20:13.000Z | cocos2d-x-2.2/extensions/CocoStudio/ActionTimeline/CCActionTimeline.cpp | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 46 | 2015-01-03T06:20:54.000Z | 2020-04-18T13:32:52.000Z | /****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCActionTimeline.h"
#include "CCNodeReader.h"
using namespace cocos2d;
NS_TIMELINE_BEGIN
ActionTimeline* ActionTimeline::create()
{
ActionTimeline* object = new ActionTimeline();
if (object && object->init())
{
object->autorelease();
return object;
}
CC_SAFE_DELETE(object);
return NULL;
}
ActionTimeline::ActionTimeline()
: _timelineList(NULL)
, _duration(0)
, _time(0)
, _timeSpeed(1)
, _frameInternal(1/60.0f)
, _playing(false)
, _currentFrame(0)
, _startFrame(0)
, _endFrame(0)
, _frameEventCallFunc(NULL)
, _frameEventTarget(NULL)
, _scriptObjectDict(NULL)
{
}
ActionTimeline::~ActionTimeline()
{
std::map<int, cocos2d::CCArray*>::const_iterator i = _timelineMap.begin();
for (; i != _timelineMap.end(); i++)
{
CCArray* timelines = i->second;
CC_SAFE_DELETE(timelines);
}
CC_SAFE_DELETE(_timelineList);
CC_SAFE_RELEASE_NULL(_scriptObjectDict);
}
bool ActionTimeline::init()
{
_timelineList = new cocos2d::CCArray();
_timelineList->init();
return true;
}
void ActionTimeline::gotoFrameAndPlay(int startIndex)
{
gotoFrameAndPlay(startIndex, true);
}
void ActionTimeline::gotoFrameAndPlay(int startIndex, bool loop)
{
gotoFrameAndPlay(startIndex, _duration, loop);
}
void ActionTimeline::gotoFrameAndPlay(int startIndex, int endIndex, bool loop)
{
gotoFrameAndPlay(startIndex, endIndex, startIndex, loop);
}
void ActionTimeline::gotoFrameAndPlay(int startIndex, int endIndex, int currentFrameIndex, bool loop)
{
_startFrame = startIndex;
_endFrame = endIndex;
_currentFrame = currentFrameIndex;
_loop = loop;
_time = _currentFrame*_frameInternal;
resume();
gotoFrame(_currentFrame);
}
void ActionTimeline::gotoFrameAndPause(int startIndex)
{
_startFrame = _currentFrame = startIndex;
_time = _currentFrame * _frameInternal;
pause();
gotoFrame(_currentFrame);
}
void ActionTimeline::pause()
{
_playing = false;
}
void ActionTimeline::resume()
{
_playing = true;
}
bool ActionTimeline::isPlaying() const
{
return _playing;
}
void ActionTimeline::setCurrentFrame(int frameIndex)
{
if (frameIndex >= _startFrame && frameIndex >= _endFrame)
{
_currentFrame = frameIndex;
_time = _currentFrame*_frameInternal;
}
else
{
CCLOG("frame index is not between start frame and end frame");
}
}
ActionTimeline* ActionTimeline::clone() const
{
ActionTimeline* newAction = ActionTimeline::create();
newAction->setDuration(_duration);
newAction->setTimeSpeed(_timeSpeed);
std::map<int, cocos2d::CCArray*>::const_iterator i = _timelineMap.begin();
for (; i != _timelineMap.end(); i++)
{
CCObject* object = NULL;
CCARRAY_FOREACH(i->second, object)
{
Timeline* timeline = static_cast<Timeline*>(object);
Timeline* newTimeline = timeline->clone();
newAction->addTimeline(newTimeline);
}
}
return newAction;
}
void ActionTimeline::step(float delta)
{
if (!_playing || _timelineMap.size() == 0 || _duration == 0)
{
return;
}
_time += delta * _timeSpeed;
_currentFrame = (int)(_time / _frameInternal);
stepToFrame(_currentFrame);
if(_time > _endFrame * _frameInternal)
{
_playing = _loop;
if(!_playing)
_time = _endFrame * _frameInternal;
else
_time = _startFrame * _frameInternal;
}
}
void ActionTimeline::foreachNodeDescendant(CCNode* parent)
{
TimelineActionData* data = dynamic_cast<TimelineActionData*>(parent->getUserObject());
CCObject* object = NULL;
if(data)
{
int actionTag = data->getActionTag();
if(_timelineMap.find(actionTag) != _timelineMap.end())
{
CCArray* timelines = this->_timelineMap[actionTag];
CCARRAY_FOREACH (timelines, object)
{
Timeline* timeline = static_cast<Timeline*>(object);
timeline->setNode(parent);
}
}
}
CCArray* children = parent->getChildren();
CCARRAY_FOREACH (children, object)
{
CCNode* child = static_cast<CCNode*>(object);
foreachNodeDescendant(child);
}
}
void ActionTimeline::startWithTarget(CCNode *target)
{
CCAction::startWithTarget(target);
foreachNodeDescendant(target);
}
void ActionTimeline::addTimeline(Timeline* timeline)
{
int tag = timeline->getActionTag();
if (_timelineMap.find(tag) == _timelineMap.end())
{
CCArray* timelines = new CCArray();
timelines->init();
_timelineMap[tag] = timelines;
}
if (!_timelineMap[tag]->containsObject(timeline))
{
_timelineList->addObject(timeline);
_timelineMap[tag]->addObject(timeline);
timeline->setActionTimeline(this);
}
}
void ActionTimeline::removeTimeline(Timeline* timeline)
{
int tag = timeline->getActionTag();
if (_timelineMap.find(tag) != _timelineMap.end())
{
if(_timelineMap[tag]->containsObject(timeline))
{
_timelineMap[tag]->removeObject(timeline);
_timelineList->removeObject(timeline);
timeline->setActionTimeline(NULL);
}
}
}
void ActionTimeline::setFrameEventCallFunc (CCObject *target, SEL_TimelineFrameEventCallFunc callFunc)
{
_frameEventTarget = target;
_frameEventCallFunc = callFunc;
}
void ActionTimeline::clearFrameEventCallFunc()
{
_frameEventTarget = NULL;
_frameEventCallFunc = NULL;
}
void ActionTimeline::emitFrameEvent(Frame* frame)
{
if (_frameEventTarget != NULL && _frameEventCallFunc != NULL)
{
(_frameEventTarget->*_frameEventCallFunc)(frame);
}
}
void ActionTimeline::gotoFrame(int frameIndex)
{
int size = _timelineList->count();
Timeline** timelines = (Timeline**)_timelineList->data->arr;
for(int i = 0; i<size; i++)
{
timelines[i]->gotoFrame(frameIndex);
}
}
void ActionTimeline::stepToFrame(int frameIndex)
{
int size = _timelineList->count();
Timeline** timelines = (Timeline**)_timelineList->data->arr;
for(int i = 0; i<size; i++)
{
timelines[i]->stepToFrame(frameIndex);
}
}
void ActionTimeline::setScriptObjectDict(cocos2d::CCDictionary *scriptObjectDict)
{
CC_SAFE_RETAIN(scriptObjectDict);
CC_SAFE_RELEASE(_scriptObjectDict);
_scriptObjectDict = scriptObjectDict;
}
cocos2d::CCDictionary* ActionTimeline::getScriptObjectDict() const
{
return _scriptObjectDict;
}
NS_TIMELINE_END
| 25.554839 | 103 | 0.662964 | centrallydecentralized |
635a2d20960c28bd98e165dbecc1334fa1439da0 | 3,102 | cpp | C++ | server/src/server.cpp | fruityloops1/smo-duktape | b840048b9f682eb5d46c3d48c3fa870a7509e55c | [
"MIT"
] | 2 | 2021-12-03T17:41:19.000Z | 2022-02-26T05:57:11.000Z | server/src/server.cpp | fruityloops1/smo-duktape | b840048b9f682eb5d46c3d48c3fa870a7509e55c | [
"MIT"
] | null | null | null | server/src/server.cpp | fruityloops1/smo-duktape | b840048b9f682eb5d46c3d48c3fa870a7509e55c | [
"MIT"
] | null | null | null | #include <ratio>
#include <server.h>
#include <packet.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <thread>
#include <iostream>
#include <fstream>
#define MAX_PACKET_SIZE 0x400
#define IN_PACKET(TYPE) case smo::InPacketType::TYPE: {\
InPacket##TYPE p;\
p.parse(data + 1, length - 1);\
p.on(*this, *parent);\
break;}
namespace smo
{
void smo::Client::connect()
{
struct in_addr ip;
ip.s_addr = uid;
std::cout << "Client connected from " << inet_ntoa(ip) << std::endl;
}
void smo::Client::handlePacket(Server* parent, u8* data, s32 length)
{
if (length < 1) return;
switch ((InPacketType) data[0])
{
case smo::InPacketType::DummyInit:
{
break;
}
case smo::InPacketType::Init:
{
connect();
break;
}
IN_PACKET(Log)
default: break;
}
}
void smo::Client::sendPacket(Server* parent, smo::OutPacket& packet, smo::OutPacketType type)
{
u32 len = packet.calcLen();
u8* packetData = new u8[len + 1];
packet.construct(packetData + 1);
packetData[0] = (u8) type;
sendto(parent->getSocket(), packetData, len + 1, 0, (struct sockaddr*) &client, sizeof(client));
delete[] packetData;
}
bool smo::Server::disconnect(u64 uid)
{
if (clients.find(uid) != clients.end())
{
clients.erase(uid);
return true;
} else return false;
}
u8 smo::Server::start(u16 port)
{
struct sockaddr_in addr, cli;
socketfd = socket(AF_INET, SOCK_DGRAM, 0);
if (socketfd == -1) return 1;
setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, nullptr, sizeof(int));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
int rval = bind(socketfd, (struct sockaddr*) &addr, sizeof(addr));
if (rval != 0) return 2;
listen(socketfd, 2);
u8 buf[12288];
s32 size = 0;
std::thread loop(&smo::Server::loopThread, this);
loop.detach();
while (true)
{
s32 length = sizeof(cli);
struct sockaddr_in client;
socklen_t addrSize;
if ((size = recvfrom(socketfd, buf, sizeof(buf), 0, (struct sockaddr *) &client, &addrSize)) < 0) continue;
u64 uid = client.sin_addr.s_addr + client.sin_port;
Client& c = clients[uid];
c.uid = uid;
c.addr = client.sin_addr.s_addr;
c.client = client;
c.handlePacket(this, buf, size);
}
return 0;
}
void smo::Server::loopThread()
{
using namespace std::chrono_literals;
while (true)
{
std::this_thread::sleep_for(10000ms);
}
}
s32 smo::Server::getSocket() {return socketfd;}
} | 25.016129 | 119 | 0.527724 | fruityloops1 |
635aa647c9ec6bc5da9f8b2bbf52d806786aa6b9 | 4,235 | cpp | C++ | examples/HelloWorld.cpp | pchabermann/EosSdk | c7f96a18bb06d0bbdb0b15a9de501f2518102651 | [
"BSD-3-Clause"
] | 132 | 2015-02-04T20:25:20.000Z | 2022-03-10T03:50:32.000Z | examples/HelloWorld.cpp | pchabermann/EosSdk | c7f96a18bb06d0bbdb0b15a9de501f2518102651 | [
"BSD-3-Clause"
] | 57 | 2015-05-20T22:34:28.000Z | 2022-03-16T21:52:28.000Z | examples/HelloWorld.cpp | pchabermann/EosSdk | c7f96a18bb06d0bbdb0b15a9de501f2518102651 | [
"BSD-3-Clause"
] | 39 | 2015-02-17T21:04:47.000Z | 2021-06-18T00:38:46.000Z | // Copyright (c) 2014 Arista Networks, Inc. All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.
#include <eos/agent.h>
#include <eos/sdk.h>
#include <eos/tracing.h>
// This simple agent says "hi" to a user when the user configures his
// or her name, and demonstrates how to use the various components of
// the SDK. To run this agent, first build this agent and copy the
// resulting binary to switch. Then, from the CLI, run:
// switch# configure
// switch(conf)# daemon HelloAgent
// switch(conf-daemon-HelloAgent)# exec /path/to/HelloWorldBinary
// switch(conf-daemon-HelloAgent)# no shutdown
// At this point, you can run 'show daemon HelloAgent' and observe the
// agent's operational status (which will transition from
// 'initializing' to 'running'), along with the custom status message
// it sets: 'greeting: Welcome, what is your name?'
// You can now tell the agent your name:
// switch(conf-daemon-HelloAgent)# option name value Bruce Wayne
// After setting the name option, running the 'show daemon' command
// again will display the updated status:
// 'greeting - Hello Bruce Wayne!'
// Although a trivial example, this agent helps demonstrate some of
// the key properties of writing EOS SDK agents. First, all activities
// are asynchronous and triggered from the event loop. At no point
// does this agent poll or block on an activity - instead we implement
// the callbacks provided by agent_handler to be notified when we are
// initialized and when options are updated.
// Secondly, this agent illustrates the uses of a mgr
// class. <module>_mgr's are used to get and set state from
// Sysdb. Here we read state from Sysdb in order to get the current
// option, and change state in Sysdb so we can update our status. This
// change is propagated to other Agents that have requested our status
// as an input, which, in this case, are only the CLI and eAPI agents.
// Finally, this example illustrates an agent's lifecycle. Upon running
// the "no shutdown" from the CLI, this program's main function is
// executed. When the program calls sdk.main_loop, the agent begins
// its initialization, at which point it will synchronize with Sysdb
// and can handle any initial state. The agent then runs
// continuously: mostly idling in the underlying event loop, but
// occasionally reacting to system events (i.e. a user entering their
// name). When you run "shutdown" from the CLI, the agent can perform
// any necessary cleanup before being disabled.
// A python version of this program can be found at HelloWorld.py
class hello_world_agent : public eos::agent_handler {
public:
eos::tracer t;
explicit hello_world_agent(eos::sdk & sdk)
: eos::agent_handler(sdk.get_agent_mgr()),
t("HelloWorldCppAgent") {
t.trace0("Agent constructed");
}
void on_initialized() {
t.trace0("Initialized");
std::string name = get_agent_mgr()->agent_option("name");
if(name.empty()) {
// No name initially set.
get_agent_mgr()->status_set("greeting", "Welcome! What is your name?");
} else {
// Handle initial state.
on_agent_option("name", name);
}
}
void on_agent_option(std::string const & option_name,
std::string const & value) {
if(option_name == "name") {
if(value.empty()) {
// User deleted the 'name' option
t.trace3("Name deleted");
get_agent_mgr()->status_set("greeting", "Goodbye!");
} else {
// Now *this* is what social networking is all
// about. Somebody set, or changed, the name option. Let's
// do some salutations!
t.trace3("Saying hi to %s", value.c_str());
get_agent_mgr()->status_set("greeting", "Hello " + value + "!");
}
}
}
void on_agent_enabled(bool enabled) {
if (!enabled) {
t.trace0("Shutting down");
get_agent_mgr()->status_set("greeting", "Adios!");
get_agent_mgr()->agent_shutdown_complete_is(true);
}
}
};
int main(int argc, char ** argv) {
eos::sdk sdk;
hello_world_agent agent(sdk);
sdk.main_loop(argc, argv);
}
| 38.5 | 80 | 0.675797 | pchabermann |
635f1c293fa074f158292cee2f3ec52e8ba7c145 | 1,707 | cpp | C++ | src/Compiler/Parser/ParseHelper.cpp | feral-lang/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"MIT"
] | 131 | 2020-03-19T15:22:37.000Z | 2021-12-19T02:37:01.000Z | src/Compiler/Parser/ParseHelper.cpp | Electrux/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"BSD-3-Clause"
] | 14 | 2020-04-06T05:50:15.000Z | 2021-06-26T06:19:04.000Z | src/Compiler/Parser/ParseHelper.cpp | Electrux/feral | 1ce8eb72eec7c8a5ac19d3767e907b86387e29e0 | [
"BSD-3-Clause"
] | 20 | 2020-04-06T07:28:30.000Z | 2021-09-05T14:46:25.000Z | /*
MIT License
Copyright (c) 2020 Feral Language repositories
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.
*/
#include "Compiler/Parser/ParseHelper.hpp"
#include <cstdarg>
phelper_t::phelper_t(lex::toks_t &toks, const size_t begin)
: m_toks(toks), m_invalid(0, TOK_INVALID, ""),
m_eof(toks.size() > 0 ? toks.back().pos : 0, TOK_EOF, ""), m_idx(begin)
{}
const lex::tok_t *phelper_t::peak(const int offset) const
{
if(offset < 0 && m_idx < (-offset)) return &m_eof;
if(m_idx + offset >= m_toks.size()) return &m_eof;
return &m_toks[m_idx + offset];
}
TokType phelper_t::peakt(const int offset) const
{
if(offset < 0 && m_idx < (-offset)) return m_eof.type;
if(m_idx + offset >= m_toks.size()) return m_eof.type;
return m_toks[m_idx + offset].type;
}
const lex::tok_t *phelper_t::next()
{
++m_idx;
if(m_idx >= m_toks.size()) return &m_eof;
return &m_toks[m_idx];
}
TokType phelper_t::nextt()
{
++m_idx;
if(m_idx >= m_toks.size()) return m_eof.type;
return m_toks[m_idx].type;
}
const lex::tok_t *phelper_t::prev()
{
if(m_idx == 0) return &m_invalid;
--m_idx;
return &m_toks[m_idx];
}
TokType phelper_t::prevt()
{
if(m_idx == 0) return m_invalid.type;
--m_idx;
return m_toks[m_idx].type;
}
const lex::tok_t *phelper_t::at(const size_t &idx) const
{
if(idx >= m_toks.size()) return &m_invalid;
return &m_toks[idx];
} | 24.73913 | 78 | 0.70123 | feral-lang |
6360c83106eccf789b6fa68dbb1a18def5e4ced4 | 6,030 | hpp | C++ | Spark/Buffer.hpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | 1 | 2022-02-15T19:50:01.000Z | 2022-02-15T19:50:01.000Z | Spark/Buffer.hpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | null | null | null | Spark/Buffer.hpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <optional>
#include <set>
#include <vector>
#include <glad/glad.h>
template<GLenum BUFFER_TYPE>
class Buffer
{
public:
GLuint ID{0};
GLint binding{-1};
GLsizei size{0};
Buffer(std::size_t sizeInBytes = 0, GLenum usage = GL_DYNAMIC_DRAW);
Buffer(const Buffer& buffer) = delete;
Buffer(Buffer&& buffer) = delete;
Buffer& operator=(const Buffer& buffer) = delete;
Buffer& operator=(Buffer&& buffer) = delete;
~Buffer();
void bind() const;
static void unbind();
template<typename T>
void updateData(const std::vector<T>& buffer);
template<typename T>
void updateSubData(size_t offsetFromBeginning, const std::vector<T>& buffer);
template<typename T, size_t Size>
void updateData(const std::array<T, Size>& buffer);
template<typename T, size_t Size>
void updateSubData(size_t offsetFromBeginning, const std::array<T, Size>& buffer);
void resizeBuffer(size_t sizeInBytes);
// this method sets value 0 for all bytes in the buffer
void clearData();
private:
void genBuffer(size_t sizeInBytes = 0);
void cleanup();
void getBinding();
void freeBinding();
static inline std::set<uint32_t> bindings{};
const GLenum bufferUsage;
};
template<GLenum BUFFER_TYPE>
Buffer<BUFFER_TYPE>::Buffer(std::size_t sizeInBytes, GLenum usage) : bufferUsage(usage)
{
genBuffer(sizeInBytes);
}
template<GLenum BUFFER_TYPE>
Buffer<BUFFER_TYPE>::~Buffer()
{
if(ID != 0)
{
cleanup();
}
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::bind() const
{
glBindBuffer(BUFFER_TYPE, ID);
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::unbind()
{
glBindBuffer(BUFFER_TYPE, 0);
}
template<GLenum BUFFER_TYPE>
template<typename T>
void Buffer<BUFFER_TYPE>::updateData(const std::vector<T>& buffer)
{
const size_t vectorSize = buffer.size() * sizeof(T);
if(vectorSize < size || vectorSize > size)
{
// SPARK_WARN("Trying to update SSBO with a vector with too large size! SSBO size: {}, vector size: {}. Buffer will be resized and update
// will be processed!", size, vectorSize);
size = static_cast<GLsizei>(vectorSize);
glNamedBufferData(ID, vectorSize, buffer.data(), bufferUsage);
}
else
{
glNamedBufferSubData(ID, 0, vectorSize, buffer.data());
}
}
template<GLenum BUFFER_TYPE>
template<typename T>
void Buffer<BUFFER_TYPE>::updateSubData(size_t offsetFromBeginning, const std::vector<T>& buffer)
{
const size_t vectorSize = buffer.size() * sizeof(T);
const GLintptr offset = static_cast<GLintptr>(offsetFromBeginning);
if(offset > size)
{
return;
}
if(offset + vectorSize > size)
{
return;
}
glNamedBufferSubData(ID, offset, vectorSize, buffer.data());
}
template<GLenum BUFFER_TYPE>
template<typename T, size_t Size>
void Buffer<BUFFER_TYPE>::updateData(const std::array<T, Size>& buffer)
{
const size_t vectorSize = Size * sizeof(T);
if(vectorSize < size || vectorSize > size)
{
// SPARK_WARN("Trying to update SSBO with a vector with too large size! SSBO size: {}, vector size: {}. Buffer will be resized and update
// will be processed!", size, vectorSize);
size = static_cast<GLsizei>(vectorSize);
glNamedBufferData(ID, vectorSize, buffer.data(), bufferUsage);
}
else
{
glNamedBufferSubData(ID, 0, vectorSize, buffer.data());
}
}
template<GLenum BUFFER_TYPE>
template<typename T, size_t Size>
void Buffer<BUFFER_TYPE>::updateSubData(size_t offsetFromBeginning, const std::array<T, Size>& buffer)
{
const size_t vectorSize = Size * sizeof(T);
const GLintptr offset = static_cast<GLintptr>(offsetFromBeginning);
if(offset > size)
{
return;
}
if(offset + vectorSize > size)
{
return;
}
glNamedBufferSubData(ID, offset, vectorSize, buffer.data());
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::resizeBuffer(size_t sizeInBytes)
{
glNamedBufferData(ID, sizeInBytes, nullptr, bufferUsage);
size = static_cast<GLsizei>(sizeInBytes);
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::clearData()
{
glClearNamedBufferData(ID, GL_R32F, GL_RED, GL_FLOAT, nullptr);
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::genBuffer(size_t sizeInBytes)
{
if(ID != 0)
{
cleanup();
}
size = static_cast<GLsizei>(sizeInBytes);
glGenBuffers(1, &ID);
glBindBuffer(BUFFER_TYPE, ID);
glBufferData(BUFFER_TYPE, size, nullptr, bufferUsage);
glBindBuffer(BUFFER_TYPE, 0);
getBinding();
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::cleanup()
{
glDeleteBuffers(1, &ID);
ID = 0;
freeBinding();
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::getBinding()
{
constexpr auto findFreeBindingBetweenAdjacentBindings = [](const uint32_t& binding1, const uint32_t& binding2) {
constexpr auto allowedDistanceBetweenBindings = 1;
return (binding2 - binding1) > allowedDistanceBetweenBindings;
};
const auto it = std::adjacent_find(bindings.begin(), bindings.end(), findFreeBindingBetweenAdjacentBindings);
if(it != bindings.end())
{
binding = *it + 1;
bindings.insert(binding);
}
else
{
if(bindings.empty())
{
binding = 0;
bindings.insert(binding);
}
else
{
binding = *std::prev(bindings.end()) + 1;
bindings.insert(binding);
}
}
}
template<GLenum BUFFER_TYPE>
void Buffer<BUFFER_TYPE>::freeBinding()
{
const auto it = bindings.find(binding);
if(it != bindings.end())
{
bindings.erase(it);
binding = -1;
}
}
using SSBO = Buffer<GL_SHADER_STORAGE_BUFFER>;
using UniformBuffer = Buffer<GL_UNIFORM_BUFFER>;
using ElementArrayBuffer = Buffer<GL_ELEMENT_ARRAY_BUFFER>;
using VertexBuffer = Buffer<GL_ARRAY_BUFFER>; | 25.550847 | 145 | 0.670813 | MickAlmighty |
6361822b2c2cfbd7b223eea9ef426877359fa128 | 29,603 | cpp | C++ | LeeMain.cpp | fanhubgt/Leemapper | 4182ca298824279eb74a2951e8f3bb5f892ffe2c | [
"CC0-1.0"
] | null | null | null | LeeMain.cpp | fanhubgt/Leemapper | 4182ca298824279eb74a2951e8f3bb5f892ffe2c | [
"CC0-1.0"
] | null | null | null | LeeMain.cpp | fanhubgt/Leemapper | 4182ca298824279eb74a2951e8f3bb5f892ffe2c | [
"CC0-1.0"
] | null | null | null | //
// File: LeeMain.cc
// Author: appiah
//
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <map>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <vector>
#include <ctime>
#include <set>
#include <cmath>
#include <stdio.h>
#include <iomanip>
#include <iterator>
#include <sys/unistd.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sched.h>
#include <pthread.h>
#include <fstream>
#include <unistd.h>
#include "LEEType.h"
#include "IsImplies.h"
using namespace std;
namespace{
//typed variables that you can change values
action a="buy", a1="sell", a2="sold", a3="trade";
interest ia="sell_pc", ia1="buy_pc";
rank r="rank_9";
location loc="tottenham", loc1="London";
temporal temp="Sat 12/09/2019 12:00pm";
// end of possible changes
std::string go;
IsImplies is;
std::string enterStarts(){
std::string start;
std::cout<< std::endl<< "Enter[ok] to start>>"<< std::endl;
getline(std::cin, start);
return start;
}
std::string enterContinues(){
std::string con="go";
std::cout<< std::endl<< "Enter number[go(1)/no(2)] to continue>>"<< std::endl;
getline(std::cin, con);
go=strtol(con.c_str(), 0, 10);
std::cout << "Go Value:=#" << go << std::endl;
return con;
}
inline std::ostream& italic(std::ostream& stream){
stream << "\033[3m";
return stream;
}
inline std::ostream& reset(std::ostream& stream){
stream << "\033[00m";
return stream;
}
inline std::ostream& bold(std::ostream& stream){
stream << "\033[1m";
return stream;
}
inline std::ostream& underline(std::ostream& stream){
stream << "\033[4m";
return stream;
}
inline std::ostream& blink(std::ostream& stream){
stream << "\033[5m";
return stream;
}
inline std::ostream& dark(std::ostream& stream){
stream << "\033[2m";
return stream;
}
template <int code> inline
std::ostream& color(std::ostream& stream){
char command[12];
snprintf(command, sizeof(command), "\033[38;5;%dm", code);
stream<< command;
return stream;
}
template <int r, int g, int b> inline
std::ostream& color(std::ostream& stream){
char command[20];
snprintf(command, sizeof(command), "\033[38;2;%d;%d;%dm", r, g, b);
stream<< command;
return stream;
}
void setLEEValues(){
Enactage en1;
en1.setAction(a);
en1.setLocation(loc);
en1.setTemporal(temp);
Enact en2;
en2.setInterests(ia, ia1);
en2.setRank(r);
is.setEnact1(en1, en2);
enactEL EL(en1, en2);
is.setEnact(EL);
Enactage EA(a, loc, temp);
is.setInterestAct1(EA, a);
is.setEnact1(EA, en2);
locationact LA(en1);
is.setLocationAct1(loc, a);
temporalrank TR(en2, EA);
is.setTemporalRank1(temp, r);
}
void setContextLanguage(){
cout<<endl<<"Structural Language Context(SLC)"<<reset<<endl;
cout<<color<33, 33, 33><<"(1) Enact_E ---> Enact_L ::="<<reset;
interest* iss=is.getEnact().getEnactmentL().getInterests();
cout<<color<34, 34, 34><<"Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<" ---> "<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
//enterContinues();
sleep(1);
cout<<color<33, 33, 33><<"(2) a_i ---> a_j ::= ";
cout<<color<34, 34, 34><<is.getEnact().getEnactage().getAction();
cout<<"--->"<<iss[0]<<reset<<endl;
// enterContinues();
sleep(1);
cout<<endl<<color<33, 33, 33><<"(3) a_j ---> l ::= "<<reset;
cout<<color<34, 34, 34><<iss[0];
cout<<" --->"<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
//enterContinues();
sleep(1);
cout<<endl<<color<33, 33, 33><<"(4) rank_i ---> t ::= "<<reset;
cout<<color<34, 34, 34><<is.getEnact().getEnactmentL().getRank();
cout<<" --->"<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
sleep(1);
cout<<color<33, 21, 43><<bold<<"Contextual Language for LEE"<<reset<<endl;
cout<<color<45, 34, 30><<"(i)The enact of business implies the enact of machinery, partonomy, interest, attention and more logic."<<endl;
cout<<"(ii)The enact of business interest implies the enact of business action or event.";
cout<<endl<<"(iii)The enact of business interest implies the enact of interest in a location.";
cout<<endl<<"(iv)The enact rank of business interest implies the enact of the linear/temporal ordering of interest.";
cout<<reset<<endl;
}
void setIsLanguage(){
sleep(1);
cout<<color<33, 33, 33><<"LEE is_Language"<<reset;
sleep(1);
cout<<color<33, 21, 43><<bold<<"Contextual Language for LEE_is"<<reset<<endl;
cout<<color<45, 34, 30><<"(i) The enact of business is the enact of logic."<<endl;
cout<<"(ii) The enact of business interest is the implication of business action. ";
cout<<endl<<"(iii) The enact of business interest is in a location.";
cout<<endl<<"(iv) The enact of business rank is based on temporal dimensions.";
cout<<reset<<endl;
}
void setLEEImplies(){
cout<<endl<<color<45, 46, 33><<"LEE Implies(LEE->)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"(1) Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" implies "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(2)"<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" implies "<<reset<<iss[0]<<reset<<endl;
// enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(3)"<<iss[0];
cout<<color<32><<" implies "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(4)"<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" implies "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
sleep(1);
cout<<color<33, 21, 43><<bold<<"Contextual Language for LEE Implications"<<reset<<endl;
cout<<color<45, 34, 30><<"(i)The enact of business is the enact of logic."<<endl;
cout<<"(ii)The enact of business interest is the implication of business action.";
cout<<endl<<"(iii)The enact of business interest is in a location.";
cout<<endl<<"(iv)The enact of business rank is based on temporal dimensions.";
cout<<reset<<endl;
}
void setLEEImpliesLang(){
cout<<endl<<color<45, 46, 33><<"LEE Implies Language(LEE->)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"(1) Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" implies "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
//enterContinues();
cout<<color<34, 34, 34><<"(2) Interest "<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" implies Action "<<reset<<iss[0]<<reset<<endl;
// enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(3) Interest "<<iss[0];
cout<<color<32><<" implies Action in Location "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(4) Rank interest "<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" implies Ordering in temporal dimension "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
sleep(1);
cout<<color<33, 21, 43><<bold<<"Contextual Language for LEE Implications"<<reset<<endl;
cout<<color<45, 34, 30><<"(i)The enact of business is the enact of logic."<<endl;
cout<<"(ii)The enact of business interest is the implication of business action.";
cout<<endl<<"(iii)The enact of business interest is in a location.";
cout<<endl<<"(iv)The enact of business rank is based on temporal dimensions.";
cout<<reset<<endl;
}
void setLEEDoubleArrow(){
cout<<endl<<color<45, 46, 33><<"LEE Double Arrow(LEE<==>)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"(1) Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" <==> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(2)"<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" <==> "<<reset<<iss[0]<<reset<<endl;
// enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(3)"<<iss[0];
cout<<color<32><<" <==> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(4)"<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" <==> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
}
void setLEEStructLang(){
cout<<endl<<color<45, 46, 33><<"LEE Structural Language(LEEStruct Language)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"(1) Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" --> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
sleep(1);
cout<<color<45, 31, 36><<"Reading\n::A run(r) of an agent in an engaged environment is thus a sequence of inter-logic environment of states and actions."<<reset<<endl;
enterContinues();
cout<<color<34, 34, 34><<"(2)"<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" --> "<<reset<<iss[0]<<reset<<endl;
cout<<color<45, 31, 36><<"Reading\n::A run of an agent by a sequence of inter-logic environment of states and actions in an engaged environment."<<reset<<endl;
enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(3)"<<iss[0];
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
sleep(1);
cout<<color<45, 31, 36><<"Reading\n::A run of an agent by sequence of inter-logic states and actions is localized in an engaged environment."<<reset<<endl;
enterContinues();
cout<<color<34, 34, 34><<"(4)"<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
cout<<color<45, 31, 36><<"Reading\n::A state is initially ranked in an engaged environment before choosing an action to execute (run in a specific time)."<<reset<<endl;
}
void setLEEAbbLanguage(){
cout<<endl<<color<45, 46, 33><<"LEE Abbreviation Language(LEEAbb Language)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"(1) Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" <==> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
sleep(1);
cout<<color<45, 31, 36><<"Reading\n::An Enact_E will exist to be true implies Enact_L is true and Enact_L existence is true implies Enact_E is true."<<reset<<endl;
enterContinues();
cout<<color<34, 34, 34><<"(2)"<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" <==> "<<reset<<iss[0]<<reset<<endl;
cout<<color<45, 31, 36><<"Reading\n::An interest a_i will exist to be true implies a_i is true and a hold to be true in existence implies a_i is existentially true."<<reset<<endl;
enterContinues();
cout<<color<34, 34, 34><<"(3)"<<iss[0];
cout<<color<32><<" <==> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
sleep(1);
cout<<color<45, 31, 36><<"Reading\n::An interest enaction, a_j is existentially true implies location exist to be true and location,l is very true in existence implies interest holding is truly in existence."<<reset<<endl;
enterContinues();
cout<<color<34, 34, 34><<"(4)"<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" <==> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
cout<<color<45, 31, 36><<"Reading\n::A rank for interest will exist true implies a chosen priority in time holds to be true."<<reset<<endl;
}
void setLEEDoubleArrowStruct(){
cout<<endl<<color<45, 46, 33><<"LEE Double Arrow Structures(LEE<-->)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"(1) (Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" --> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<"))"<<reset;
sleep(1);
cout<<color<32><<" and "<<reset<<" (Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset;
cout<<color<32><<" --> "<<reset<<color<34, 34, 34><<" Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<"))"<<endl;
sleep(1);
//enterContinues();
cout<<color<34, 34, 34><<"(2) ("<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" --> "<<reset<<iss[0]<<reset;
cout<<color<35, 35, 35><<") and ("<<iss[0];
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getAction()<<")"<<reset<<endl;
sleep(1);
// enterContinues();
cout<<color<34, 34, 34><<"(3) ("<<iss[0];
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset;
cout<<color<35, 35, 35><<") and ("<<is.getEnact().getEnactage().getLocation();
cout<<color<32><<" --> "<<reset<<iss[0]<<")"<<reset<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(4) ("<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" ---> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset;
cout<<color<35, 35, 35><<") and ("<<is.getEnact().getEnactage().getTemporal();
cout<<color<32><<" ---> "<<reset<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl;
sleep(1);
enterContinues();
}
void setLEEAbb(){
cout<<endl<<color<45, 46, 33><<"LEE Abbreviation(LEEAbb)::{";
cout<<"LEE Implies are now abbreviated below:}"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34><<"(1) not "<<reset<<color<31, 31, 31><<"Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")"<<reset<<endl;
cout<<color<32><<" or "<<reset<<color<36, 36, 36><<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
//enterContinues();
sleep(1);
cout<<color<34><<"(2) not "<<reset<<color<31, 31, 31><<is.getEnact().getEnactage().getAction()<<reset;
cout<<color<32><<" or "<<reset<<color<36, 36, 36><<iss[0]<<reset<<endl;
// enterContinues();
sleep(1);
cout<<color<34><<"(3) not "<<reset<<color<31, 31, 31><<iss[0]<<reset;
cout<<color<32><<" or "<<reset<<color<36, 36, 36><<is.getEnact().getEnactage().getLocation()<<reset<<endl;
//enterContinues();
sleep(1);
cout<<color<34><<"(4) not "<<reset<<color<31, 31, 31><<is.getEnact().getEnactmentL().getRank()<<reset;
cout<<color<32><<" or "<<reset<<color<36, 36, 36><<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
// cout<<reset<<endl;
}
void setLEELinearOrd(){
cout<<endl<<color<45, 46, 33><<"LEE Mapping Structure(LEE-Linear Ordering)"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" --> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")";
cout<<color<32><<" --> "<<reset;
//enterContinues();
cout<<color<34, 34, 34><<is.getEnact().getEnactage().getAction()<<reset;
cout<<color<32><<" --> "<<reset<<iss[0]<<reset;
// enterContinues();
sleep(1);
cout<<color<32><<" --> "<<reset;
cout<<color<34, 34, 34><<iss[0]<<reset;
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset;
//enterContinues();
sleep(1);
cout<<color<32><<" --> "<<reset;
cout<<color<34, 34, 34><<is.getEnact().getEnactmentL().getRank()<<reset;
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
cout<<reset<<endl;
}
void setLEEConsequentRun(){
cout<<endl<<color<45, 46, 33><<"LEE Consequent Runs(LEE-runs)\n"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
cout<<color<34, 60, 43><<"D::Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" --> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")";
cout<<color<33><<" --> "<<reset;
cout<<is.getEnact().getEnactage().getAction()<<endl;
cout<<reset;
sleep(1);
cout<<color<32, 44, 55><<"Di::Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")";
cout<<color<32><<" --> "<<reset;
cout<<is.getEnact().getEnactage().getAction();
cout<<color<43><<" --> "<<reset<<iss[0]<<endl;
cout<<reset;
sleep(1);
cout<<color<36, 41, 45><<"Dii::"<<iss[0];
cout<<color<32><<" --> "<<reset;
cout<<iss[1];
cout<<color<33><<" --> "<<reset<<is.getEnact().getEnactage().getAction()<<endl;
cout<<reset;
sleep(1);
cout<<color<44, 55, 12><<"Diii::"<<iss[0];
cout<<color<32><<" --> "<<reset;
cout<<iss[1]<<reset;
cout<<color<35><<" --> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
sleep(1);
cout<<color<30, 38, 47><<"Div::"<<iss[1];
cout<<color<36><<" --> "<<reset;
cout<<is.getEnact().getEnactage().getLocation()<<reset;
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactmentL().getRank()<<reset<<endl;
sleep(1);
cout<<color<42, 67, 34><<"Dv::"<<is.getEnact().getEnactage().getLocation()<<reset;
cout<<color<34><<" --> "<<reset;
cout<<is.getEnact().getEnactmentL().getRank()<<reset;
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
}
void setLEEComposite(){
cout<<endl<<color<45, 46, 33><<"LEE Propose Enactment (Enactment Formulas)\n"<<reset<<endl;
cout<<color<33><<"Propositional Constants::"<<reset<<color<32><<"\nT and F\n"<<reset;
cout<<endl<<color<45, 46, 33><<"Propositional Variables::"<<reset<<endl;
interest* iss=is.getEnact().getEnactmentL().getInterests();
sleep(1);
cout<<color<34, 34, 34><<"Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" , "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")";
cout<<color<32><<" , "<<reset;
//enterContinues();
cout<<color<34, 34, 34><<is.getEnact().getEnactage().getAction()<<reset;
cout<<color<32><<" , "<<reset<<iss[0]<<reset;
// enterContinues();
sleep(1);
cout<<color<32><<" , "<<reset;
cout<<color<34, 34, 34><<iss[0]<<reset;
cout<<color<32><<" , "<<reset<<is.getEnact().getEnactage().getLocation()<<reset;
//enterContinues();
sleep(1);
cout<<color<32><<" , "<<reset;
cout<<color<34, 34, 34><<is.getEnact().getEnactmentL().getRank()<<reset;
cout<<color<32><<" , "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
cout<<endl<<color<45, 46, 33><<"Propositional Composites::"<<reset<<endl;
cout<<endl<<color<45, 46, 32><<"or-Composites"<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(i) not Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" or "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(ii) not "<<is.getEnact().getEnactage().getAction()<<reset;
cout<<color<32><<" or "<<reset<<iss[0]<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(iii) not "<<iss[0]<<reset;
cout<<color<32><<" or "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(iv) not "<<is.getEnact().getEnactmentL().getRank()<<reset;
cout<<color<32><<" or "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
cout<<endl<<color<45, 46, 32><<"not-Composites"<<reset<<endl;
sleep(1);
sleep(1);
cout<<color<34, 34, 34><<"(i) not "<<reset<<"Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")"<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(ii) not "<<reset<<is.getEnact().getEnactage().getAction()<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(iii) not "<<reset<<iss[0]<<reset<<endl;
cout<<color<34, 34, 34><<"(iv) not "<<reset<<is.getEnact().getEnactmentL().getRank()<<reset<<endl;
cout<<endl<<color<45, 46, 32><<"and-Composites"<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(i) (Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" --> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<"))";
cout<<color<32><<" and "<<reset<<"(Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")";
cout<<color<32><<" --> "<<reset<<color<34, 34, 34><<"Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<"))"<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(ii) ("<<is.getEnact().getEnactage().getAction()<<reset;
cout<<color<32><<" --> "<<reset<<iss[0]<<reset;
cout<<color<32><<") and ("<<reset<<iss[0]<<reset;
cout<<color<32><<" --> "<<reset;
cout<<color<34, 34, 34><<" "<<is.getEnact().getEnactage().getAction()<<")"<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(iii) ("<<iss[0]<<reset;
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset;
cout<<color<32><<" ) and ( "<<reset<<is.getEnact().getEnactage().getLocation()<<reset;
cout<<color<34, 34, 34><<" --> "<<reset<<iss[0]<<")"<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(iv) ("<<is.getEnact().getEnactmentL().getRank()<<reset;
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset;
cout<<color<32><<") and ( "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset;
cout<<color<34, 34, 34><<" --> "<<reset<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl;
cout<<endl<<color<45, 46, 32><<"implies-Composites"<<reset<<endl;
sleep(1);
cout<<color<34, 34, 34><<"(1) Enact_E("<<is.getEnact().getEnactage().getAction();
cout<<","<<is.getEnact().getEnactage().getLocation();
cout<<","<<is.getEnact().getEnactage().getTemporal()<<")";
cout<<color<32><<" --> "<<reset<<"Enact_L("<<iss[0]<<","<<iss[1]<<","<<is.getEnact().getEnactmentL().getRank()<<")"<<reset<<endl<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(2)"<<is.getEnact().getEnactage().getAction();
cout<<color<32><<" --> "<<reset<<iss[0]<<reset<<endl;
// enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(3)"<<iss[0];
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getLocation()<<reset<<endl;
//enterContinues();
sleep(1);
cout<<color<34, 34, 34><<"(4)"<<is.getEnact().getEnactmentL().getRank();
cout<<color<32><<" --> "<<reset<<is.getEnact().getEnactage().getTemporal()<<reset<<endl;
enterContinues();
sleep(1);
}
}
int main(int argc, char** argv) {
cout<<color<36><<"LEE Run- (L)ogical (E)ngage (E)nactment Program"<<endl;
cout<<reset<<endl;
enterStarts();
cout<<"LEE Language and Composites"<<endl;
cout<<"Enactment Formalizations"<<endl;
cout<<"Developed by: Frank Appiah"<<endl;
enterContinues();
cout<<"\n========================================\n Enactment Logic Solution Menu\n======================================="<<endl;
cout<<color<12, 45, 36><<"(1):: Context Language"<<endl;
sleep(1);
cout<<"(2):: LEE Implications"<<endl;
sleep(1);
cout<<"(3):: LEE Imply Language"<<endl;
sleep(1);
cout<<"(4):: LEE Linear Ordering"<<endl;
sleep(1);
cout<<"(5):: LEE Abbreviation(Abb)"<<endl;
sleep(1);
cout<<"(6):: LEE AbbStruct Language"<<endl;
sleep(1);
cout<<"(7):: LEE Abbreviation Language"<<endl;
cout<<"(8):: LEE Double Arrow(DA)"<<endl;
sleep(1);
cout<<"(9):: LEE DA Structures"<<endl;
cout<<"(10):: LEE is_Language"<<endl;
sleep(1);
cout<<"(11):: LEE Consequent Run"<<endl;
cout<<"(12):: Enactment Formalizations"<<endl;
cout<<reset<<endl;
cout<<color<41, 66, 30><<"Building the Enactment Engagement Language....."<<endl;
sleep(2);
setLEEValues();
enterContinues();
setContextLanguage();
enterContinues();
setLEEImplies();
enterContinues();
setLEEImpliesLang();
enterContinues();
setLEELinearOrd();
enterContinues();
setLEEAbb();
enterContinues();
setLEEStructLang();
enterContinues();
setLEEAbbLanguage();
enterContinues();
setLEEDoubleArrow();
enterContinues();
setLEEDoubleArrowStruct();
enterContinues();
setIsLanguage();
enterContinues();
setLEEConsequentRun();
enterContinues();
setLEEComposite();
enterContinues();
return (EXIT_SUCCESS);
}
| 45.403374 | 230 | 0.554268 | fanhubgt |
636631e3e1982ba0dd8e17db01f3bbd2da46b3f8 | 973 | cpp | C++ | docs/template_plugin/tests/functional/shared_tests_instances/behavior/ov_plugin/caching_tests.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2022-02-07T09:14:15.000Z | 2022-02-07T09:14:15.000Z | docs/template_plugin/tests/functional/shared_tests_instances/behavior/ov_plugin/caching_tests.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 2 | 2022-03-28T13:18:55.000Z | 2022-03-28T13:18:57.000Z | docs/template_plugin/tests/functional/shared_tests_instances/behavior/ov_plugin/caching_tests.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "behavior/ov_plugin/caching_tests.hpp"
using namespace ov::test::behavior;
namespace {
static const std::vector<ov::element::Type> precisionsTemplate = {
ov::element::f32,
};
static const std::vector<std::size_t> batchSizesTemplate = {
1, 2
};
INSTANTIATE_TEST_SUITE_P(smoke_Behavior_CachingSupportCase_Template, CompileModelCacheTestBase,
::testing::Combine(
::testing::ValuesIn(CompileModelCacheTestBase::getStandardFunctions()),
::testing::ValuesIn(precisionsTemplate),
::testing::ValuesIn(batchSizesTemplate),
::testing::Values(CommonTestUtils::DEVICE_TEMPLATE)),
CompileModelCacheTestBase::getTestCaseName);
} // namespace
| 37.423077 | 107 | 0.590956 | ryanloney |
63671d1240dc16daf9cf31de2d059475a5d5d032 | 16,303 | cxx | C++ | Examples/ANTSIntegrateVectorField.cxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | null | null | null | Examples/ANTSIntegrateVectorField.cxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | null | null | null | Examples/ANTSIntegrateVectorField.cxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | 1 | 2019-10-06T07:31:58.000Z | 2019-10-06T07:31:58.000Z |
#include "antsUtilities.h"
#include "antsAllocImage.h"
#include <algorithm>
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "vnl/algo/vnl_determinant.h"
#include "itkWarpImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "vnl/algo/vnl_determinant.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkVectorLinearInterpolateImageFunction.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkLaplacianRecursiveGaussianImageFilter.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "ReadWriteData.h"
namespace ants
{
template <typename TField, typename TImage>
typename TImage::Pointer
GetVectorComponent(typename TField::Pointer field, unsigned int index)
{
// Initialize the Moving to the displacement field
typedef TImage ImageType;
typename ImageType::Pointer sfield = AllocImage<ImageType>(field);
typedef itk::ImageRegionIteratorWithIndex<TField> Iterator;
Iterator vfIter( field, field->GetLargestPossibleRegion() );
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
typename TField::PixelType v1 = vfIter.Get();
sfield->SetPixel(vfIter.GetIndex(), v1[index]);
}
return sfield;
}
template <typename TImage>
typename TImage::Pointer
SmoothImage(typename TImage::Pointer image, float sig)
{
// find min value
typedef itk::ImageRegionIteratorWithIndex<TImage> Iterator;
Iterator vfIter(image, image->GetLargestPossibleRegion() );
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
typename TImage::PixelType v1 = vfIter.Get();
if( std::isnan(v1) )
{
vfIter.Set(0);
}
}
typedef itk::DiscreteGaussianImageFilter<TImage, TImage> dgf;
typename dgf::Pointer filter = dgf::New();
filter->SetVariance(sig);
filter->SetUseImageSpacingOn();
filter->SetMaximumError(.01f);
filter->SetInput(image);
filter->Update();
typename TImage::Pointer out = filter->GetOutput();
return out;
}
template <typename TImage>
void
SmoothDeformation(typename TImage::Pointer vectorimage, float sig)
{
typedef itk::Vector<float, 3> VectorType;
typedef itk::Image<float, 3> ImageType;
typename ImageType::Pointer subimgx = GetVectorComponent<TImage, ImageType>(vectorimage, 0);
subimgx = SmoothImage<ImageType>(subimgx, sig);
typename ImageType::Pointer subimgy = GetVectorComponent<TImage, ImageType>(vectorimage, 1);
subimgy = SmoothImage<ImageType>(subimgy, sig);
typename ImageType::Pointer subimgz = GetVectorComponent<TImage, ImageType>(vectorimage, 2);
subimgz = SmoothImage<ImageType>(subimgz, sig);
typedef itk::ImageRegionIteratorWithIndex<TImage> IteratorType;
IteratorType Iterator( vectorimage, vectorimage->GetLargestPossibleRegion().GetSize() );
Iterator.GoToBegin();
while( !Iterator.IsAtEnd() )
{
VectorType vec;
vec[0] = subimgx->GetPixel(Iterator.GetIndex() );
vec[1] = subimgy->GetPixel(Iterator.GetIndex() );
vec[2] = subimgz->GetPixel(Iterator.GetIndex() );
Iterator.Set(vec);
++Iterator;
}
return;
}
template <typename TImage, typename TField, typename TInterp, typename TInterp2>
float IntegrateLength( typename TImage::Pointer gmsurf, typename TImage::Pointer /* thickimage */,
typename TImage::IndexType velind, typename TField::Pointer lapgrad, float itime,
float starttime, const float deltaTime, typename TInterp::Pointer vinterp,
typename TImage::SpacingType spacing, float vecsign, float timesign, float gradsign )
{
typedef typename TField::PixelType VectorType;
typedef typename TField::PointType DPointType;
typedef itk::VectorLinearInterpolateImageFunction<TField, float> DefaultInterpolatorType;
VectorType zero;
zero.Fill(0);
VectorType disp;
disp.Fill(0);
unsigned int ct = 0;
DPointType pointIn1;
DPointType pointIn2;
typename DefaultInterpolatorType::ContinuousIndexType vcontind;
DPointType pointIn3;
enum { ImageDimension = TImage::ImageDimension };
typedef typename TImage::IndexType IndexType;
unsigned int m_NumberOfTimePoints = 2;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn1[jj] = velind[jj] * lapgrad->GetSpacing()[jj];
}
itime = starttime;
bool timedone = false;
float totalmag = 0;
while( !timedone )
{
float scale = 1; // *m_DT[timeind]/m_DS[timeind];
// std::cout << " scale " << scale << std::endl;
double itimetn1 = itime - timesign * deltaTime * scale;
double itimetn1h = itime - timesign * deltaTime * 0.5 * scale;
if( itimetn1h < 0 )
{
itimetn1h = 0;
}
if( itimetn1h > m_NumberOfTimePoints - 1 )
{
itimetn1h = m_NumberOfTimePoints - 1;
}
if( itimetn1 < 0 )
{
itimetn1 = 0;
}
if( itimetn1 > m_NumberOfTimePoints - 1 )
{
itimetn1 = m_NumberOfTimePoints - 1;
}
// first get current position of particle
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn1[jj] = velind[jj] * lapgrad->GetSpacing()[jj];
}
// std::cout << " ind " << index << std::endl;
// now index the time varying field at that position.
typename DefaultInterpolatorType::OutputType f1; f1.Fill(0);
typename DefaultInterpolatorType::OutputType f2; f2.Fill(0);
typename DefaultInterpolatorType::OutputType f3; f3.Fill(0);
typename DefaultInterpolatorType::OutputType f4; f4.Fill(0);
typename DefaultInterpolatorType::ContinuousIndexType Y1;
typename DefaultInterpolatorType::ContinuousIndexType Y2;
typename DefaultInterpolatorType::ContinuousIndexType Y3;
typename DefaultInterpolatorType::ContinuousIndexType Y4;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn2[jj] = disp[jj] + pointIn1[jj];
vcontind[jj] = pointIn2[jj] / lapgrad->GetSpacing()[jj];
Y1[jj] = vcontind[jj];
Y2[jj] = vcontind[jj];
Y3[jj] = vcontind[jj];
Y4[jj] = vcontind[jj];
}
// Y1[ImageDimension]=itimetn1;
// Y2[ImageDimension]=itimetn1h;
// Y3[ImageDimension]=itimetn1h;
// Y4[ImageDimension]=itime;
f1 = vinterp->EvaluateAtContinuousIndex( Y1 );
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
Y2[jj] += f1[jj] * deltaTime * 0.5;
}
bool isinside = true;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
if( Y2[jj] < 1 || Y2[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 )
{
isinside = false;
}
}
if( isinside )
{
f2 = vinterp->EvaluateAtContinuousIndex( Y2 );
}
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
Y3[jj] += f2[jj] * deltaTime * 0.5;
}
isinside = true;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
if( Y3[jj] < 1 || Y3[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 )
{
isinside = false;
}
}
if( isinside )
{
f3 = vinterp->EvaluateAtContinuousIndex( Y3 );
}
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
Y4[jj] += f3[jj] * deltaTime;
}
isinside = true;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
if( Y4[jj] < 1 || Y4[jj] > lapgrad->GetLargestPossibleRegion().GetSize()[jj] - 2 )
{
isinside = false;
}
}
if( isinside )
{
f4 = vinterp->EvaluateAtContinuousIndex( Y4 );
}
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
pointIn3[jj] = pointIn2[jj] + gradsign * vecsign * deltaTime / 6.0
* ( f1[jj] + 2.0 * f2[jj] + 2.0 * f3[jj] + f4[jj] );
}
VectorType out;
float mag = 0, dmag = 0, voxmag = 0;
for( unsigned int jj = 0; jj < ImageDimension; jj++ )
{
out[jj] = pointIn3[jj] - pointIn1[jj];
mag += (pointIn3[jj] - pointIn2[jj]) * (pointIn3[jj] - pointIn2[jj]);
voxmag += (pointIn3[jj] - pointIn2[jj]) / spacing[jj] * (pointIn3[jj] - pointIn2[jj]) / spacing[jj];
dmag += (pointIn3[jj] - pointIn1[jj]) * (pointIn3[jj] - pointIn1[jj]);
disp[jj] = out[jj];
}
voxmag = sqrt(voxmag);
dmag = sqrt(dmag);
totalmag += sqrt(mag);
ct++;
// if (!propagate) //thislength=dmag;//
// thislength += totalmag;
itime = itime + deltaTime * timesign;
IndexType myind;
for( unsigned int qq = 0; qq < ImageDimension; qq++ )
{
myind[qq] = (unsigned long)(pointIn3[qq] / spacing[qq] + 0.5);
}
if( gmsurf->GetPixel(myind) < 1 )
{
timedone = true;
}
if( ct > 1000 )
{
std::cout << " stopping b/c exceed 1000 points " << voxmag << std::endl; timedone = true;
}
if( voxmag < 0.1 )
{
timedone = true;
}
}
return totalmag;
}
template <unsigned int ImageDimension>
int IntegrateVectorField(int argc, char *argv[])
{
typedef float PixelType;
typedef itk::Vector<float, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef typename ImageType::SpacingType SpacingType;
constexpr float deltaTime = 0.001;
float gradstep = 1. / deltaTime; // atof(argv[3])*(-1.0);
std::string vectorfn = std::string(argv[1]);
std::string roifn = std::string(argv[2]);
int argct = 3;
argct++;
std::string lenoutname = std::string("");
if( argc > argct )
{
lenoutname = std::string(argv[argct]);
}
argct++;
if( argc > argct )
{
gradstep *= atof(argv[argct]);
}
argct++;
typename ImageType::Pointer ROIimage;
ReadImage<ImageType>(ROIimage, roifn.c_str() );
typename ImageType::Pointer thickimage;
ReadImage<ImageType>(thickimage, roifn.c_str() );
thickimage->FillBuffer(0);
typename DisplacementFieldType::Pointer VECimage;
ReadImage<DisplacementFieldType>(VECimage, vectorfn.c_str() );
SpacingType spacing = ROIimage->GetSpacing();
typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType;
IteratorType Iterator( ROIimage, ROIimage->GetLargestPossibleRegion().GetSize() );
double timezero = 0; // 1
double timeone = 1; // (s[ImageDimension]-1-timezero);
float starttime = timezero; // timezero;
float finishtime = timeone; // s[ImageDimension]-1;//timeone;
typename DisplacementFieldType::IndexType velind;
float timesign = 1.0;
if( starttime > finishtime )
{
timesign = -1.0;
}
typedef DisplacementFieldType TimeVaryingVelocityFieldType;
typedef typename DisplacementFieldType::PointType DPointType;
typedef itk::VectorLinearInterpolateImageFunction<TimeVaryingVelocityFieldType, float> DefaultInterpolatorType;
typename DefaultInterpolatorType::Pointer vinterp = DefaultInterpolatorType::New();
typedef itk::LinearInterpolateImageFunction<ImageType, float> ScalarInterpolatorType;
VectorType zero;
zero.Fill(0);
typedef itk::ImageRegionIteratorWithIndex<DisplacementFieldType> VIteratorType;
VIteratorType VIterator( VECimage, VECimage->GetLargestPossibleRegion().GetSize() );
VIterator.GoToBegin();
while( !VIterator.IsAtEnd() )
{
VectorType vec = VIterator.Get();
float mag = 0;
for( unsigned int qq = 0; qq < ImageDimension; qq++ )
{
mag += vec[qq] * vec[qq];
}
mag = sqrt(mag);
if( mag > 0 )
{
vec = vec / mag;
}
VIterator.Set(vec * gradstep);
++VIterator;
}
Iterator.GoToBegin();
while( !Iterator.IsAtEnd() )
{
velind = Iterator.GetIndex();
float itime = starttime;
VectorType disp;
disp.Fill(0.0);
if( ROIimage->GetPixel(velind) == 2 )
{
vinterp->SetInputImage(VECimage);
float gradsign = -1.0;
double vecsign = -1.0;
float len1 = IntegrateLength<ImageType, DisplacementFieldType, DefaultInterpolatorType, ScalarInterpolatorType>
(ROIimage, thickimage, velind, VECimage, itime, starttime, deltaTime, vinterp,
spacing, vecsign, gradsign,
timesign);
gradsign = 1.0; vecsign = 1;
const float len2 = IntegrateLength<ImageType, DisplacementFieldType, DefaultInterpolatorType, ScalarInterpolatorType>
(ROIimage, thickimage, velind, VECimage, itime, starttime, deltaTime, vinterp,
spacing, vecsign, gradsign,
timesign );
float totalength = len1 + len2;
thickimage->SetPixel(velind, totalength);
if( (totalength) > 0 )
{
std::cout << " len1 " << len1 << " len2 " << len2 << " ind " << velind << std::endl;
}
}
++Iterator;
}
WriteImage<ImageType>(thickimage, lenoutname.c_str() );
return EXIT_SUCCESS;
}
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int ANTSIntegrateVectorField( std::vector<std::string> args, std::ostream* /*out_stream = nullptr*/ )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "ANTSIntegrateVectorField" );
int argc = args.size();
char* * argv = new char *[args.size() + 1];
for( unsigned int i = 0; i < args.size(); ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = nullptr;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
// antscout->set_stream( out_stream );
if( argc < 4 )
{
std::cout << "Usage: " << argv[0]
<< " VecImageIN.nii.gz ROIMaskIN.nii.gz FibersOUT.vtk LengthImageOUT.nii.gz " << std::endl;
std::cout
<<
" The vector field should have vectors as voxels , the ROI is an integer image, fibers out will be vtk text files .... "
<< std::endl;
std::cout << " ROI-Mask controls where the integration is performed and the start point region ... " << std::endl;
std::cout << " e.g. the brain will have value 1 , the ROI has value 2 , then all starting seed points "
<< std::endl;
std::cout
<< " for the integration will start in the region labeled 2 and be constrained to the region labeled 1. "
<< std::endl;
if( argc >= 2 &&
( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
std::string ifn = std::string(argv[1]);
itk::ImageIOBase::Pointer imageIO =
itk::ImageIOFactory::CreateImageIO(ifn.c_str(), itk::ImageIOFactory::ReadMode);
imageIO->SetFileName(ifn.c_str() );
imageIO->ReadImageInformation();
unsigned int dim = imageIO->GetNumberOfDimensions();
switch( dim )
{
case 2:
{
IntegrateVectorField<2>(argc, argv);
}
break;
case 3:
{
IntegrateVectorField<3>(argc, argv);
}
break;
case 4:
{
IntegrateVectorField<4>(argc, argv);
}
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace ants
| 33.203666 | 126 | 0.635098 | KevinScholtes |
636af685bcd7ad025e660a410b114e639536321f | 5,672 | cpp | C++ | source/mclib/mlr/mlrinfinitelightwithfalloff.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 38 | 2015-04-10T13:31:03.000Z | 2021-09-03T22:34:05.000Z | source/mclib/mlr/mlrinfinitelightwithfalloff.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 1 | 2020-07-09T09:48:44.000Z | 2020-07-12T12:41:43.000Z | source/mclib/mlr/mlrinfinitelightwithfalloff.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 12 | 2015-06-29T08:06:57.000Z | 2021-10-13T13:11:41.000Z | //===========================================================================//
// Copyright (C) Microsoft Corporation. All rights reserved. //
//===========================================================================//
#include "stdinc.h"
#include "mlr/mlrinfinitelightwithfalloff.h"
namespace MidLevelRenderer {
//#############################################################################
//############### MLRInfiniteLightWithFalloff ###########################
//#############################################################################
MLRInfiniteLightWithFalloff::ClassData* MLRInfiniteLightWithFalloff::DefaultData = nullptr;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::InitializeClass()
{
_ASSERT(!DefaultData);
// _ASSERT(gos_GetCurrentHeap() == StaticHeap);
DefaultData = new ClassData(MLRInfiniteLightWithFalloffClassID,
"MidLevelRenderer::MLRInfiniteLightWithFalloff", MLRLight::DefaultData);
Register_Object(DefaultData);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::TerminateClass()
{
Unregister_Object(DefaultData);
delete DefaultData;
DefaultData = nullptr;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::MLRInfiniteLightWithFalloff(ClassData* class_data) :
MLRLight(class_data)
{
// _ASSERT(gos_GetCurrentHeap() == Heap);
lightMask = MLRState::FaceLightingMode | MLRState::VertexLightingMode;
innerRadius = 0.0f;
outerRadius = 0.0f;
oneOverDistance = 100.0f;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::MLRInfiniteLightWithFalloff(
ClassData* class_data, std::iostream stream, uint32_t version) :
MLRLight(class_data, stream, version)
{
Check_Object(stream);
// _ASSERT(gos_GetCurrentHeap() == Heap);
lightMask = MLRState::FaceLightingMode | MLRState::VertexLightingMode;
float inner, outer;
*stream >> inner >> outer;
SetFalloffDistance(inner, outer);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::MLRInfiniteLightWithFalloff(ClassData* class_data, Stuff::Page* page) :
MLRLight(class_data, page)
{
Check_Object(page);
// _ASSERT(gos_GetCurrentHeap() == Heap);
lightMask = MLRState::FaceLightingMode | MLRState::VertexLightingMode;
float inner = 0.0f;
page->GetEntry("InnerRadius", &inner);
float outer = 100.0;
page->GetEntry("OuterRadius", &outer);
SetFalloffDistance(inner, outer);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRInfiniteLightWithFalloff::~MLRInfiniteLightWithFalloff() {}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::Save(std::iostream stream)
{
// Check_Object(this);
Check_Object(stream);
MLRLight::Save(stream);
*stream << innerRadius << outerRadius;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::Write(Stuff::Page* page)
{
// Check_Object(this);
Check_Object(page);
MLRLight::Write(page);
page->SetEntry("InnerRadius", innerRadius);
page->SetEntry("OuterRadius", outerRadius);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::TestInstance()
{
_ASSERT(IsDerivedFrom(DefaultData));
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::SetFalloffDistance(float ir, float or)
{
// Check_Object(this);
innerRadius = ir;
outerRadius = or ;
oneOverDistance = 1.0f / (outerRadius - innerRadius);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
bool
MLRInfiniteLightWithFalloff::GetFalloffDistance(float& ir, float& or)
{
// Check_Object(this);
ir = innerRadius;
or = outerRadius;
return true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
MLRInfiniteLightWithFalloff::LightVertex(const MLRVertexData& vertexData)
{
UnitVector3D light_z;
GetInShapeDirection(light_z);
//
//-------------------------------------------------------------------
// Now we reduce the light level falling on the vertex based upon the
// cosine of the angle between light and normal
//-------------------------------------------------------------------
//
float cosine = -(light_z * (*vertexData.normal)) * intensity;
RGBcolour light_color(color);
Point3D vertex_to_light;
_ASSERT(GetFalloffDistance(vertex_to_light.x, vertex_to_light.y));
GetInShapePosition(vertex_to_light);
vertex_to_light -= *vertexData.point;
//
//--------------------------------------------------------------
// If the distance to the vertex is zero, the light will not
// contribute to the vertex coloration. Otherwise, decrease the
// light level as appropriate to the distance
//--------------------------------------------------------------
//
float length = vertex_to_light.GetApproximateLength();
float falloff = 1.0f;
#if COLOR_AS_DWORD
TO_DO;
#else
if (GetFalloff(length, falloff))
{
light_color.red *= falloff;
light_color.green *= falloff;
light_color.blue *= falloff;
}
else
{
return;
}
if (cosine > SMALL)
{
light_color.red *= cosine;
light_color.green *= cosine;
light_color.blue *= cosine;
vertexData.color->red += light_color.red;
vertexData.color->green += light_color.green;
vertexData.color->blue += light_color.blue;
}
#endif
}
} // namespace MidLevelRenderer
| 29.696335 | 100 | 0.540197 | mechasource |
636b5aff0ad61ecc4287300b959542bb1bde3573 | 982 | cpp | C++ | uva/524.cpp | larc/competitive_programming | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | 1 | 2019-05-23T19:05:39.000Z | 2019-05-23T19:05:39.000Z | uva/524.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | uva/524.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | // 524 - Prime Ring Problem
#include <cstdio>
#include <cstring>
#define N 16
#define M 32
int ring[N];
bool not_prime[M];
bool selected[N];
void init_prime()
{
memset(not_prime, 0, sizeof(not_prime));
for(int i = 2; i < M; ++i)
if(!not_prime[i])
for(int j = i * i; j < M; j += i)
not_prime[j] = 1;
}
void prime_ring(const int & n, const int & p)
{
if(n == p && !not_prime[ring[p - 1] + ring[0]])
{
printf("%d", ring[0]);
for(int i = 1; i < p; ++i)
printf(" %d", ring[i]);
putchar('\n');
return;
}
for(int i = 2 + !(p & 1); i <= n; i += 2)
if(!selected[i] && !not_prime[i + ring[p - 1]])
{
selected[i] = 1;
ring[p] = i;
prime_ring(n, p + 1);
selected[i] = 0;
}
}
int main()
{
init_prime();
int n, n_cases = 1;
ring[0] = 1;
scanf("%d", &n);
while(1)
{
printf("Case %d:\n", n_cases++);
memset(selected, 0, sizeof(selected));
prime_ring(n, 1);
if(scanf("%d", &n) == EOF) break;
putchar('\n');
}
return 0;
}
| 14.441176 | 49 | 0.525458 | larc |