hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
244546eb2b118641f2f3fcb75187eece06c19cae | 4,257 | cpp | C++ | Game/OGRE/OgreMain/src/OgreDynLib.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/OgreMain/src/OgreDynLib.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/OgreMain/src/OgreDynLib.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreDynLib.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
# include "macPlugins.h"
#endif
namespace Ogre {
//-----------------------------------------------------------------------
DynLib::DynLib( const String& name )
{
OgreGuard("DynLib::DynLib");
mName = name;
m_hInst = NULL;
OgreUnguard();
}
//-----------------------------------------------------------------------
DynLib::~DynLib()
{
}
//-----------------------------------------------------------------------
void DynLib::load()
{
OgreGuard("DynLib::load");
// Log library load
LogManager::getSingleton().logMessage("Loading library " + mName);
std::string name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
// dlopen() does not add .so to the filename, like windows does for .dll
if (name.substr(name.length() - 3, 3) != ".so")
name += ".so";
#endif
m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
if( !m_hInst )
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Could not load dynamic library " + mName +
". System Error: " + dynlibError(),
"DynLib::load" );
OgreUnguard();
}
//-----------------------------------------------------------------------
void DynLib::unload()
{
OgreGuard("DynLib::unload");
// Log library unload
LogManager::getSingleton().logMessage("Unloading library " + mName);
if( DYNLIB_UNLOAD( m_hInst ) )
{
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Could not unload dynamic library " + mName +
". System Error: " + dynlibError(),
"DynLib::unload");
}
OgreUnguard();
}
//-----------------------------------------------------------------------
void* DynLib::getSymbol( const String& strName ) const throw()
{
return (void*)DYNLIB_GETSYM( m_hInst, strName.c_str() );
}
//-----------------------------------------------------------------------
String DynLib::dynlibError( void )
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL
);
String ret = (char*)lpMsgBuf;
// Free the buffer.
LocalFree( lpMsgBuf );
return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
return String(dlerror());
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
return String(mac_errorBundle());
#else
return StringUtil::BLANK;
#endif
}
}
| 29.978873 | 85 | 0.5323 | [
"object"
] |
244e1007aa5b1008bc3c95edce4721d2e49cbb67 | 845 | hpp | C++ | production/include/datasource/data_view.hpp | ratelware/logreader | 6ca96c49a342dcaef59221dd3497563f54b63ae7 | [
"MIT"
] | null | null | null | production/include/datasource/data_view.hpp | ratelware/logreader | 6ca96c49a342dcaef59221dd3497563f54b63ae7 | [
"MIT"
] | 3 | 2017-11-21T22:16:51.000Z | 2017-11-21T23:34:31.000Z | production/include/datasource/data_view.hpp | ratelware/logreader | 6ca96c49a342dcaef59221dd3497563f54b63ae7 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <compressor/chunk.hpp>
#include <compressor/compressor.hpp>
#include <datasource/cache.hpp>
namespace datasource {
const std::size_t MAX_CACHE_SIZE = 10;
class data_view {
public:
typedef std::vector<std::shared_ptr<compressor::uncompressed_chunk>> chunks;
virtual ~data_view();
virtual chunks get_bytes(std::size_t byte_range_start, std::size_t byte_range_end) = 0;
};
class compressed_view : public data_view {
public:
compressed_view(std::deque<compressor::chunk>&);
virtual chunks get_bytes(std::size_t start, std::size_t end);
private:
std::deque<compressor::chunk>& chunks;
cache<std::size_t, std::shared_ptr<compressor::uncompressed_chunk> > local_memory;
compressor::compressor compressor;
};
} | 22.837838 | 89 | 0.745562 | [
"vector"
] |
2454b49358cef506f439b96027985fdc63ff85d8 | 5,553 | cpp | C++ | Src/scaleMEF.cpp | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | 4 | 2019-04-24T13:33:35.000Z | 2021-08-24T07:11:22.000Z | Src/scaleMEF.cpp | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | 4 | 2020-02-25T01:58:46.000Z | 2022-02-01T20:22:49.000Z | Src/scaleMEF.cpp | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | 6 | 2018-11-05T11:53:20.000Z | 2021-03-22T10:44:54.000Z | #include <string>
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <AMReX_ParmParse.H>
#include <AMReX_MultiFab.H>
#include <AMReX_Utility.H>
#include <AMReX_VisMF.H>
using namespace amrex;
using std::vector;
using std::map;
using std::string;
using std::cerr;
using std::endl;
using std::cout;
using std::ofstream;
void
read_iso(const std::string& infile,
FArrayBox& nodes,
Vector<int>& faceData,
int& nElts,
vector<string>& names,
string& label);
void
write_iso(const std::string& outfile,
const FArrayBox& nodes,
const Vector<int>& faceData,
int nElts,
const vector<string>& names,
const string& label);
static
std::vector<std::string> parseVarNames(std::istream& is)
{
std::string line;
std::getline(is,line);
return Tokenize(line,std::string(", "));
}
static std::string parseTitle(std::istream& is)
{
std::string line;
std::getline(is,line);
return line;
}
int
main (int argc,
char* argv[])
{
amrex::Initialize(argc,argv);
ParmParse pp;
int nElts;
string infile; pp.get("infile",infile);
string outfile; pp.get("outfile",outfile);
FArrayBox nodes;
Vector<int> faceData;
vector<string> names;
string label;
read_iso(infile,nodes,faceData,nElts,names,label);
int nodesPerElt = faceData.size() / nElts;
BL_ASSERT(nodesPerElt*nElts == faceData.size());
nElts = faceData.size() / nodesPerElt;
int nCompMEF = nodes.nComp();
BL_ASSERT(nElts*nodesPerElt == faceData.size());
Vector<int> comps;
if (pp.countval("comps"))
{
int nComp = pp.countval("comps");
comps.resize(nComp);
pp.getarr("comps",comps,0,nComp);
}
else
{
int sComp = 0;
pp.query("sComp",sComp);
int nc = 1;
pp.query("nComp",nc);
BL_ASSERT(sComp+nc <= nCompMEF);
comps.resize(nc);
for (int i=0; i<nc; ++i)
comps[i] = sComp + i;
}
int nComp = comps.size();
Vector<Real> vals(nComp);
BL_ASSERT(pp.countval("vals")==nComp);
pp.getarr("vals",vals,0,nComp);
int nNodes = nodes.box().numPts();
for (int j=0; j<nComp; ++j)
{
BL_ASSERT(comps[j]<nCompMEF);
Real* dat=nodes.dataPtr(comps[j]);
for (int i=0; i<nNodes; ++i)
dat[i] = dat[i]*vals[j];
}
if (pp.countval("newNames"))
{
int numNew = pp.countval("newNames");
int numNewComps = pp.countval("newComps");
BL_ASSERT(numNew==numNewComps);
Vector<std::string> newNames(numNew);
Vector<int> newComps(numNewComps);
pp.getarr("newNames",newNames,0,newNames.size());
pp.getarr("newComps",newComps,0,newComps.size());
for (int i=0; i<numNew; ++i) {
BL_ASSERT(newComps[i] <= names.size());
names[newComps[i]] = newNames[i];
}
}
write_iso(outfile,nodes,faceData,nElts,names,label);
amrex::Finalize();
return 0;
}
void
write_iso(const std::string& outfile,
const FArrayBox& nodes,
const Vector<int>& faceData,
int nElts,
const vector<string>& names,
const string& label)
{
// Rotate data to vary quickest on component
int nCompSurf = nodes.nComp();
int nNodes = nodes.box().numPts();
FArrayBox tnodes(nodes.box(),nCompSurf);
const Real** np = new const Real*[nCompSurf];
for (int j=0; j<nCompSurf; ++j)
np[j] = nodes.dataPtr(j);
Real* ndat = tnodes.dataPtr();
for (int i=0; i<nNodes; ++i)
{
for (int j=0; j<nCompSurf; ++j)
{
ndat[j] = np[j][i];
}
ndat += nCompSurf;
}
delete [] np;
std::ofstream ofs;
ofs.open(outfile.c_str(),std::ios::out|std::ios::trunc|std::ios::binary);
ofs << label << endl;
for (int i=0; i<nCompSurf; ++i)
{
ofs << names[i];
if (i < nCompSurf-1)
ofs << " ";
else
ofs << std::endl;
}
int nodesPerElt = faceData.size() / nElts;
ofs << nElts << " " << nodesPerElt << endl;
tnodes.writeOn(ofs);
ofs.write((char*)faceData.dataPtr(),sizeof(int)*faceData.size());
ofs.close();
}
void
read_iso(const std::string& infile,
FArrayBox& nodes,
Vector<int>& faceData,
int& nElts,
vector<string>& names,
string& label)
{
std::ifstream ifs;
ifs.open(infile.c_str(),std::ios::in|std::ios::binary);
label = parseTitle(ifs);
names = parseVarNames(ifs);
const int nCompSurf = names.size();
int nodesPerElt;
ifs >> nElts;
ifs >> nodesPerElt;
FArrayBox tnodes;
tnodes.readFrom(ifs);
const int nNodes = tnodes.box().numPts();
// "rotate" the data so that the components are 'in the right spot for fab data'
nodes.resize(tnodes.box(),nCompSurf);
Real** np = new Real*[nCompSurf];
for (int j=0; j<nCompSurf; ++j)
np[j] = nodes.dataPtr(j);
Real* ndat = tnodes.dataPtr();
for (int i=0; i<nNodes; ++i)
{
for (int j=0; j<nCompSurf; ++j)
{
np[j][i] = ndat[j];
}
ndat += nCompSurf;
}
delete [] np;
tnodes.clear();
faceData.resize(nElts*nodesPerElt,0);
ifs.read((char*)faceData.dataPtr(),sizeof(int)*faceData.size());
}
| 25.013514 | 84 | 0.556276 | [
"vector"
] |
245c160b36d29e06cce027e9d98bc29cf32a30d7 | 1,348 | hpp | C++ | include/hydro/engine/document/SnapshotContextSymbol.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/engine/document/SnapshotContextSymbol.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/engine/document/SnapshotContextSymbol.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#ifndef __h3o_engine_SnapshotContextSymbol__
#define __h3o_engine_SnapshotContextSymbol__
#include "Symbol.hpp"
namespace hydro::engine
{
/**
* The SnapshotContextSymbol class represents a snapshot context symbol in a Performance document.
*/
class SnapshotContextSymbol final : public Symbol
{
public:
/**
* Creates a SnapshotContextSymbol object with a name.
* @param name The name of the snapshot domain.
*/
SnapshotContextSymbol(std::string name);
/**
* Destroys the SnapshotContextSymbol object.
*/
virtual ~SnapshotContextSymbol();
/**
* Compares the snapshot context symbol to another symbol to test equality.
* @param symbol The symbol to compare.
* @return Returns true if the supplied symbol can be assumed to be identitical. Otherwise returns false.
*/
virtual bool compare(Symbol* symbol) const override;
};
} // namespace hydro::engine
#endif /* __h3o_engine_SnapshotContextSymbol__ */
| 28.083333 | 109 | 0.58457 | [
"object"
] |
245da3bf62fe9a26ed2bb3fcc3bc0f804806acdf | 307,977 | cpp | C++ | src/fastdb/database.cpp | mage-game/metagame-server-engine | 8b6eb0a258d6dae4330cb3be769de162874841ed | [
"MIT"
] | 4 | 2021-12-16T13:57:26.000Z | 2022-03-26T07:49:42.000Z | src/fastdb/database.cpp | mage-game/metagame-server-engine | 8b6eb0a258d6dae4330cb3be769de162874841ed | [
"MIT"
] | null | null | null | src/fastdb/database.cpp | mage-game/metagame-server-engine | 8b6eb0a258d6dae4330cb3be769de162874841ed | [
"MIT"
] | 1 | 2022-03-26T07:49:46.000Z | 2022-03-26T07:49:46.000Z | //-< DATABASE.CPP >--------------------------------------------------*--------*
// FastDB Version 1.0 (c) 1999 GARRET * ? *
// (Main Memory Database Management System) * /\| *
// * / \ *
// Created: 20-Nov-98 K.A. Knizhnik * / [] \ *
// Last update: 14-Jan-99 K.A. Knizhnik * GARRET *
//-------------------------------------------------------------------*--------*
// Database memory management, query execution, scheme evaluation
//-------------------------------------------------------------------*--------*
#define INSIDE_FASTDB
#include "fastdb.h"
#include "compiler.h"
#include "symtab.h"
#include "hashtab.h"
#include "ttree.h"
#include "rtree.h"
#include <ctype.h>
#include <wctype.h>
#include <math.h>
#ifndef _WINCE
#include <sys/stat.h>
#endif
#ifdef VXWORKS
#include "fastdbShim.h"
#endif // VXWORKS
BEGIN_FASTDB_NAMESPACE
#ifdef HANDLE_ASSERTION_FAILURES
#define FASTDB_ASSERT(_cond) do { if (!(_cond)) handleError(AssertionFailed, __FILE__ ":" #_cond, __LINE__); } while (0)
#define FASTDB_ASSERT_EX(_db, _cond) do { if (!(_cond)) (_db)->handleError(AssertionFailed, __FILE__ ":" #_cond, __LINE__); } while (0)
#else
#define FASTDB_ASSERT(_cond) assert(_cond)
#define FASTDB_ASSERT_EX(_db, _cond) assert(_cond)
#endif
dbNullReference null;
char const* const dbMetaTableName = "Metatable";
size_t dbDatabase::internalObjectSize[] = {
0,
dbPageSize,
sizeof(dbTtree),
sizeof(dbTtreeNode),
sizeof(dbHashTable),
sizeof(dbHashTableItem),
sizeof(dbRtree),
sizeof(dbRtreePage)
};
int dbDatabase::getVersion()
{
return header->getVersion();
}
FixedSizeAllocator::FixedSizeAllocator()
{
minSize = 0;
maxSize = 0;
bufSize = 0;
quantum = 0;
nChains = 0;
chains = NULL;
holes = NULL;
vacant = NULL;
}
FixedSizeAllocator::~FixedSizeAllocator()
{
TRACE_MSG(("hits=%ld, faults=%ld, retries=%ld\n", (long)hits, (long)faults, (long)retries));
delete[] chains;
delete[] holes;
}
void FixedSizeAllocator::reset()
{
memset(chains, 0, sizeof(Hole*)*nChains);
if (bufSize > 0) {
for (size_t i = 1; i < bufSize; i++) {
holes[i-1].next = &holes[i];
}
holes[bufSize-1].next = NULL;
}
vacant = holes;
hits = 0;
faults = 0;
retries = 0;
}
void FixedSizeAllocator::init(size_t minSize, size_t maxSize, size_t quantum, size_t bufSize)
{
delete[] chains;
delete[] holes;
this->minSize = minSize;
this->maxSize = maxSize;
this->quantum = quantum;
this->bufSize = bufSize;
nChains = (maxSize - minSize + quantum - 1) / quantum + 1;
chains = new Hole*[nChains];
holes = new Hole[bufSize];
reset();
}
coord_t FASTDB_DLL_ENTRY distance(rectangle const& r, rectangle const& q)
{
if (r & q) {
return 0;
}
coord_t d = 0;;
for (int i = 0; i < rectangle::dim; i++) {
if (r.boundary[i] > q.boundary[rectangle::dim+i]) {
coord_t di = r.boundary[i] - q.boundary[rectangle::dim+i];
d += di*di;
} else if (q.boundary[i] > r.boundary[rectangle::dim+i]) {
coord_t di = q.boundary[i] - r.boundary[rectangle::dim+i];
d += di*di;
}
}
return (coord_t)sqrt((double)d);
}
inline void convertIntToString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
char buf[32];
sattr.array.size = sprintf(buf, INT8_FORMAT, sattr.ivalue) + 1;
sattr.array.base = dbStringValue::create(buf, iattr);
sattr.array.comparator = NULL;
}
inline void convertRealToString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
char buf[32];
sattr.array.size = sprintf(buf, "%f", sattr.fvalue) + 1;
sattr.array.base = dbStringValue::create(buf, iattr);
sattr.array.comparator = NULL;
}
inline void convertWcsToMbs(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
size_t bufSize = sattr.array.size*MAX_MULTIBYTE_CHARACTER_LENGTH;
char* buf = dbStringValue::create(bufSize, iattr);
size_t size = wcstombs(buf, (wchar_t*)sattr.array.base, bufSize-1);
sattr.array.size = (int)size+1;
sattr.array.base = buf;
buf[size] = '\0';
}
inline void convertMbsToWcs(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
size_t bufSize = sattr.array.size*sizeof(wchar_t);
char* buf = dbStringValue::create(bufSize, iattr);
size_t size = mbstowcs((wchar_t*)buf, sattr.array.base, sattr.array.size-1);
sattr.array.size = (int)size+1;
sattr.array.base = buf;
*((wchar_t*)buf + size) = '\0';
}
inline void concatenateStrings(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
char* str =
dbStringValue::create(sattr.array.size + sattr.array.size - 1, iattr);
memcpy(str, sattr.array.base, sattr.array.size-1);
memcpy(str + sattr.array.size - 1, sattr2.array.base, sattr2.array.size);
sattr.array.base = str;
sattr.array.size += sattr2.array.size-1;
}
inline void concatenateWStrings(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
char* str =
dbStringValue::create((sattr.array.size + sattr.array.size - 1)*sizeof(wchar_t), iattr);
memcpy(str, sattr.array.base, (sattr.array.size-1)*sizeof(wchar_t));
memcpy(str + (sattr.array.size-1)*sizeof(wchar_t), sattr2.array.base, sattr2.array.size*sizeof(wchar_t));
sattr.array.base = str;
sattr.array.size += sattr2.array.size-1;
}
inline bool compareStringsForEquality(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2)
{
if (sattr1.array.comparator != NULL) {
return sattr1.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH) == 0;
} else if (sattr2.array.comparator != NULL) {
return sattr2.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH) == 0;
} else {
#ifdef IGNORE_CASE
return stricmp(sattr1.array.base, sattr2.array.base) == 0;
#else
return sattr1.array.size == sattr2.array.size && memcmp(sattr1.array.base, sattr2.array.base, sattr1.array.size) == 0;
#endif
}
}
inline bool compareWStringsForEquality(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2)
{
if (sattr1.array.comparator != NULL) {
return sattr1.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH) == 0;
} else if (sattr2.array.comparator != NULL) {
return sattr2.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH) == 0;
} else {
#ifdef IGNORE_CASE
return wcsicmp((wchar_t*)sattr1.array.base, (wchar_t*)sattr2.array.base) == 0;
#else
return sattr1.array.size == sattr2.array.size && memcmp(sattr1.array.base, sattr2.array.base, sattr1.array.size*sizeof(wchar_t)) == 0;
#endif
}
}
inline int compareStrings(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2)
{
if (sattr1.array.comparator != NULL) {
return sattr1.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH);
} else if (sattr2.array.comparator != NULL) {
return sattr2.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH);
} else {
#ifdef USE_LOCALE_SETTINGS
#ifdef IGNORE_CASE
return stricoll(sattr1.array.base, sattr2.array.base);
#else
return strcoll(sattr1.array.base, sattr2.array.base);
#endif
#else
#ifdef IGNORE_CASE
return stricmp(sattr1.array.base, sattr2.array.base);
#else
return strcmp(sattr1.array.base, sattr2.array.base);
#endif
#endif
}
}
inline int compareWStrings(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2)
{
if (sattr1.array.comparator != NULL) {
return sattr1.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH);
} else if (sattr2.array.comparator != NULL) {
return sattr2.array.comparator(sattr1.array.base, sattr2.array.base, MAX_STRING_LENGTH);
} else {
#ifdef IGNORE_CASE
return wcsicmp((wchar_t*)sattr1.array.base, (wchar_t*)sattr2.array.base);
#else
return wcscmp((wchar_t*)sattr1.array.base, (wchar_t*)sattr2.array.base);
#endif
}
}
#ifdef IGNORE_CASE
#define GET_CHAR(c) toupper((byte)(c))
#define GET_WCHAR(c) towupper(c)
#else
#define GET_CHAR(c) (c)
#define GET_WCHAR(c) (c)
#endif
dbException::dbException(int p_err_code, char const* p_msg, int p_arg)
: err_code (p_err_code),
msg (NULL),
arg (p_arg)
{
if (p_msg != NULL) {
msg = new char[strlen(p_msg)+1];
strcpy(msg, p_msg);
}
}
dbException::dbException(dbException const& ex)
{
err_code = ex.err_code;
arg = ex.arg;
if (ex.msg != NULL) {
msg = new char[strlen(ex.msg)+1];
strcpy(msg, ex.msg);
} else {
msg = NULL;
}
}
dbException::~dbException() throw()
{
delete[] msg;
}
const char* dbException::what() const throw()
{
return getMsg();
}
inline bool matchStrings(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2,
char escapeChar)
{
char *str = sattr1.array.base;
char *pattern = sattr2.array.base;
char *wildcard = NULL;
char *strpos = NULL;
dbUDTComparator comparator = sattr1.array.comparator;
if (comparator != NULL) {
while (true) {
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (*str == '\0') {
return (*pattern == '\0');
} else if (*pattern == escapeChar && comparator(pattern+1, str, 1) == 0) {
str += 1;
pattern += 2;
} else if (*pattern != escapeChar
&& (comparator(pattern, str, 1) == 0 || *pattern == dbMatchAnyOneChar))
{
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
} else {
while (true) {
int ch = GET_CHAR(*str);
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (ch == '\0') {
return (*pattern == '\0');
} else if (*pattern == escapeChar && GET_CHAR(pattern[1]) == ch) {
str += 1;
pattern += 2;
} else if (*pattern != escapeChar
&& (ch == GET_CHAR(*pattern)
|| *pattern == dbMatchAnyOneChar))
{
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
}
}
inline bool matchStrings(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2)
{
char *str = sattr1.array.base;
char *pattern = sattr2.array.base;
char *wildcard = NULL;
char *strpos = NULL;
dbUDTComparator comparator = sattr1.array.comparator;
if (comparator != NULL) {
while (true) {
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (*str == '\0') {
return (*pattern == '\0');
} else if (comparator(pattern, str, 1) == 0 || *pattern == dbMatchAnyOneChar) {
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
} else {
while (true) {
int ch = GET_CHAR(*str);
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (ch == '\0') {
return (*pattern == '\0');
} else if (ch == GET_CHAR(*pattern) || *pattern == dbMatchAnyOneChar) {
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
}
}
inline void lowercaseString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
char *dst = dbStringValue::create(sattr.array.size, iattr);
char *src = sattr.array.base;
sattr.array.base = dst;
while ((*dst++ = tolower(byte(*src++))) != '\0');
}
inline void uppercaseString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
char *dst = dbStringValue::create(sattr.array.size, iattr);
char *src = sattr.array.base;
sattr.array.base = dst;
while ((*dst++ = toupper(byte(*src++))) != '\0');
}
inline void copyString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr, char* str)
{
sattr.array.base = dbStringValue::create(str, iattr);
sattr.array.size = (int)strlen(str) + 1;
sattr.array.comparator = NULL;
delete[] str;
}
inline bool matchWStrings(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2,
wchar_t escapeChar)
{
wchar_t *str = (wchar_t*)sattr1.array.base;
wchar_t *pattern = (wchar_t*)sattr2.array.base;
wchar_t *wildcard = NULL;
wchar_t *strpos = NULL;
dbUDTComparator comparator = sattr1.array.comparator;
if (comparator != NULL) {
while (true) {
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (*str == '\0') {
return (*pattern == '\0');
} else if (*pattern == escapeChar && comparator(pattern+1, str, 1) == 0) {
str += 1;
pattern += 2;
} else if (*pattern != escapeChar
&& (comparator(pattern, str, 1) == 0 || *pattern == dbMatchAnyOneChar))
{
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
} else {
while (true) {
int ch = GET_WCHAR(*str);
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (ch == '\0') {
return (*pattern == '\0');
} else if (*pattern == escapeChar && GET_WCHAR(pattern[1]) == ch) {
str += 1;
pattern += 2;
} else if (*pattern != escapeChar
&& (ch == GET_WCHAR(*pattern)
|| *pattern == dbMatchAnyOneChar))
{
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
}
}
inline bool matchWStrings(dbSynthesizedAttribute& sattr1,
dbSynthesizedAttribute& sattr2)
{
wchar_t *str = (wchar_t*)sattr1.array.base;
wchar_t *pattern = (wchar_t*)sattr2.array.base;
wchar_t *wildcard = NULL;
wchar_t *strpos = NULL;
dbUDTComparator comparator = sattr1.array.comparator;
if (comparator != NULL) {
while (true) {
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (*str == '\0') {
return (*pattern == '\0');
} else if (comparator(pattern, str, 1) == 0 || *pattern == dbMatchAnyOneChar) {
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
} else {
while (true) {
int ch = GET_WCHAR(*str);
if (*pattern == dbMatchAnySubstring) {
wildcard = ++pattern;
strpos = str;
} else if (ch == '\0') {
return (*pattern == '\0');
} else if (ch == GET_WCHAR(*pattern) || *pattern == dbMatchAnyOneChar) {
str += 1;
pattern += 1;
} else if (wildcard) {
str = ++strpos;
pattern = wildcard;
} else {
return false;
}
}
}
}
inline void lowercaseWString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
wchar_t *dst = (wchar_t*)dbStringValue::create(sattr.array.size*sizeof(wchar_t), iattr);
wchar_t *src = (wchar_t*)sattr.array.base;
sattr.array.base = (char*)dst;
while ((*dst++ = towlower(*src++)) != '\0');
}
inline void uppercaseWString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
wchar_t *dst = (wchar_t*)dbStringValue::create(sattr.array.size*sizeof(wchar_t), iattr);
wchar_t *src = (wchar_t*)sattr.array.base;
sattr.array.base = (char*)dst;
while ((*dst++ = towupper(*src++)) != '\0');
}
inline void copyWString(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr, wchar_t* str)
{
size_t len = wcslen(str);
sattr.array.base = dbStringValue::create(len + 1, iattr);
sattr.array.size = (int)len + 1;
sattr.array.comparator = NULL;
memcpy(sattr.array.base, str, (len + 1)*sizeof(wchar_t));
delete[] str;
}
inline void searchArrayOfBool(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
bool *p = (bool*)sattr2.array.base;
int n = sattr2.array.size;
bool v = (bool)sattr.bvalue;
while (--n >= 0) {
if (v == *p++) {
sattr.bvalue = true;
return;
}
}
sattr.bvalue = false;
}
inline void searchArrayOfInt1(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
int1 *p = (int1*)sattr2.array.base;
int n = sattr2.array.size;
int1 v = (int1)sattr.ivalue;
while (--n >= 0) {
if (v == *p++) {
sattr.bvalue = true;
return;
}
}
sattr.bvalue = false;
}
inline void searchArrayOfInt2(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
int2 *p = (int2*)sattr2.array.base;
int n = sattr2.array.size;
int2 v = (int2)sattr.ivalue;
while (--n >= 0) {
if (v == *p++) {
sattr.bvalue = true;
return;
}
}
sattr.bvalue = false;
}
inline void searchArrayOfInt4(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
int4 *p = (int4*)sattr2.array.base;
int n = sattr2.array.size;
int4 v = (int4)sattr.ivalue;
while (--n >= 0) {
if (v == *p++) {
sattr.bvalue = true;
return;
}
}
sattr.bvalue = false;
}
inline void searchArrayOfInt8(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
db_int8 *p = (db_int8*)sattr2.array.base;
int n = sattr2.array.size;
db_int8 v = sattr.ivalue;
while (--n >= 0) {
if (v == *p) {
sattr.bvalue = true;
return;
}
p += 1;
}
sattr.bvalue = false;
}
inline void searchArrayOfReal4(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
real4* p = (real4*)sattr2.array.base;
int n = sattr2.array.size;
real4 v = (real4)sattr.fvalue;
while (--n >= 0) {
if (v == *p++) {
sattr.bvalue = true;
return;
}
}
sattr.bvalue = false;
}
inline void searchArrayOfReal8(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
real8 *p = (real8*)sattr2.array.base;
int n = sattr2.array.size;
real8 v = sattr.fvalue;
while (--n >= 0) {
if (v == *p) {
sattr.bvalue = true;
return;
}
p += 1;
}
sattr.bvalue = false;
}
inline void searchArrayOfReference(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
oid_t *p = (oid_t*)sattr2.array.base;
int n = sattr2.array.size;
oid_t v = sattr.oid;
while (--n >= 0) {
if (v == *p) {
sattr.bvalue = true;
return;
}
p += 1;
}
sattr.bvalue = false;
}
inline void searchArrayOfRectangle(dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
rectangle *p = (rectangle*)sattr2.array.base;
int n = sattr2.array.size;
rectangle v = sattr.rvalue;
sattr.bvalue = false;
while (--n >= 0) {
if (v == *p) {
sattr.bvalue = true;
break;
}
p += 1;
}
}
inline void searchArrayOfString(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
dbVarying *p = (dbVarying*)sattr2.array.base;
int n = sattr2.array.size;
char* str = sattr.array.base;
char* base = (char*)sattr2.base;
while (--n >= 0) {
if (strcmp(base + p->offs, str) == 0) {
sattr.bvalue = true;
return;
}
p += 1;
}
sattr.bvalue = false;
}
inline void searchInString(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
if (sattr.array.size > sattr2.array.size) {
sattr.bvalue = false;
} else if (sattr2.array.size > dbBMsearchThreshold) {
int len = sattr.array.size - 2;
int n = sattr2.array.size - 1;
int i, j, k;
int shift[256];
byte* pattern = (byte*)sattr.array.base;
byte* str = (byte*)sattr2.array.base;
for (i = 0; i < (int)itemsof(shift); i++) {
shift[i] = len+1;
}
for (i = 0; i < len; i++) {
shift[pattern[i]] = len-i;
}
for (i = len; i < n; i += shift[str[i]]) {
j = len;
k = i;
while (pattern[j] == str[k]) {
k -= 1;
if (--j < 0) {
sattr.bvalue = true;
return;
}
}
}
sattr.bvalue = false;
} else {
sattr.bvalue = strstr(sattr2.array.base, sattr.array.base) != NULL;
}
}
inline void searchArrayOfWString(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
dbVarying *p = (dbVarying*)sattr2.array.base;
int n = sattr2.array.size;
wchar_t* str = (wchar_t*)sattr.array.base;
char* base = (char*)sattr2.base;
while (--n >= 0) {
if (wcscmp((wchar_t*)(base + p->offs), str) == 0) {
sattr.bvalue = true;
return;
}
p += 1;
}
sattr.bvalue = false;
}
inline void searchInWString(dbSynthesizedAttribute& sattr,
dbSynthesizedAttribute& sattr2)
{
if (sattr.array.size > sattr2.array.size) {
sattr.bvalue = false;
} else {
sattr.bvalue = wcsstr((wchar_t*)sattr2.array.base, (wchar_t*)sattr.array.base) != NULL;
}
}
inline db_int8 powerIntInt(db_int8 x, db_int8 y)
{
db_int8 res = 1;
if (y < 0) {
x = 1/x;
y = -y;
}
while (y != 0) {
if (y & 1) {
res *= x;
}
x *= x;
y >>= 1;
}
return res;
}
inline real8 powerRealInt(real8 x, db_int8 y)
{
real8 res = 1.0;
if (y < 0) {
x = 1/x;
y = -y;
}
while (y != 0) {
if (y & 1) {
res *= x;
}
x *= x;
y >>= 1;
}
return res;
}
bool dbDatabase::evaluate(dbExprNode* expr, oid_t oid, dbTable* table, dbAnyCursor* cursor)
{
dbInheritedAttribute iattr;
dbSynthesizedAttribute sattr;
iattr.db = this;
iattr.oid = oid;
iattr.table = table;
iattr.record = (byte*)getRow(oid);
iattr.paramBase = (size_t)cursor->paramBase;
execute(expr, iattr, sattr);
return sattr.bvalue != 0;
}
void _fastcall dbDatabase::execute(dbExprNode* expr,
dbInheritedAttribute& iattr,
dbSynthesizedAttribute& sattr)
{
dbSynthesizedAttribute sattr2, sattr3;
switch (expr->cop) {
case dbvmVoid:
sattr.bvalue = true; // empty condition
return;
case dbvmCurrent:
sattr.oid = iattr.oid;
return;
case dbvmFirst:
sattr.oid = iattr.table->firstRow;
return;
case dbvmLast:
sattr.oid = iattr.table->lastRow;
return;
case dbvmLoadBool:
execute(expr->operand[0], iattr, sattr);
sattr.bvalue = *(bool*)(sattr.base+expr->offs);
return;
case dbvmLoadInt1:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = *(int1*)(sattr.base+expr->offs);
return;
case dbvmLoadInt2:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = *(int2*)(sattr.base+expr->offs);
return;
case dbvmLoadInt4:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = *(int4*)(sattr.base+expr->offs);
return;
case dbvmLoadInt8:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = *(db_int8*)(sattr.base+expr->offs);
return;
case dbvmLoadReal4:
execute(expr->operand[0], iattr, sattr);
sattr.fvalue = *(real4*)(sattr.base+expr->offs);
return;
case dbvmLoadReal8:
execute(expr->operand[0], iattr, sattr);
sattr.fvalue = *(real8*)(sattr.base+expr->offs);
return;
case dbvmLoadReference:
execute(expr->operand[0], iattr, sattr);
sattr.oid = *(oid_t*)(sattr.base+expr->offs);
return;
case dbvmLoadRectangle:
execute(expr->operand[0], iattr, sattr);
sattr.rvalue = *(rectangle*)(sattr.base+expr->offs);
return;
case dbvmLoadArray:
case dbvmLoadString:
case dbvmLoadWString:
execute(expr->operand[0], iattr, sattr2);
sattr.array.base = (char*)sattr2.base
+ ((dbVarying*)(sattr2.base + expr->offs))->offs;
sattr.array.size = ((dbVarying*)(sattr2.base + expr->offs))->size;
sattr.array.comparator = expr->ref.field->_comparator;
return;
case dbvmLoadRawBinary:
execute(expr->operand[0], iattr, sattr);
sattr.raw = (void*)(sattr.base+expr->offs);
return;
case dbvmLoadSelfBool:
sattr.bvalue = *(bool*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfInt1:
sattr.ivalue = *(int1*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfInt2:
sattr.ivalue = *(int2*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfInt4:
sattr.ivalue = *(int4*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfInt8:
sattr.ivalue = *(db_int8*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfReal4:
sattr.fvalue = *(real4*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfReal8:
sattr.fvalue = *(real8*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfReference:
sattr.oid = *(oid_t*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfRectangle:
sattr.rvalue = *(rectangle*)(iattr.record+expr->offs);
return;
case dbvmLoadSelfArray:
case dbvmLoadSelfString:
case dbvmLoadSelfWString:
sattr.array.base = (char*)iattr.record +
((dbVarying*)(iattr.record + expr->offs))->offs;
sattr.array.size = ((dbVarying*)(iattr.record + expr->offs))->size;
sattr.array.comparator = expr->ref.field->_comparator;
return;
case dbvmLoadSelfRawBinary:
sattr.raw = (void*)(iattr.record+expr->offs);
return;
case dbvmInvokeMethodBool:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.bvalue);
sattr.bvalue = *(bool*)&sattr.bvalue;
return;
case dbvmInvokeMethodInt1:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.ivalue);
sattr.ivalue = *(int1*)&sattr.ivalue;
return;
case dbvmInvokeMethodInt2:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.ivalue);
sattr.ivalue = *(int2*)&sattr.ivalue;
return;
case dbvmInvokeMethodInt4:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.ivalue);
sattr.ivalue = *(int4*)&sattr.ivalue;
return;
case dbvmInvokeMethodInt8:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.ivalue);
return;
case dbvmInvokeMethodReal4:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.fvalue);
sattr.fvalue = *(real4*)&sattr.fvalue;
return;
case dbvmInvokeMethodReal8:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.fvalue);
return;
case dbvmInvokeMethodReference:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr.oid);
return;
case dbvmInvokeMethodString:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr2.array.base);
sattr.array.size = (int)strlen(sattr2.array.base) + 1;
sattr.array.base = dbStringValue::create(sattr2.array.base, iattr);
sattr.array.comparator = NULL;
delete[] sattr2.array.base;
return;
case dbvmInvokeMethodWString:
execute(expr->ref.base, iattr, sattr);
expr->ref.field->method->invoke(sattr.base, &sattr2.array.base);
sattr.array.size = (int)wcslen((wchar_t*)sattr2.array.base) + 1;
sattr.array.base = dbStringValue::create(sattr.array.size*sizeof(wchar_t), iattr);
sattr.array.comparator = NULL;
memcpy(sattr.array.base, sattr2.array.base, sattr.array.size*sizeof(wchar_t));
delete[] (wchar_t*)sattr2.array.base;
return;
case dbvmInvokeSelfMethodBool:
expr->ref.field->method->invoke(iattr.record, &sattr.bvalue);
sattr.bvalue = *(bool*)&sattr.bvalue;
return;
case dbvmInvokeSelfMethodInt1:
expr->ref.field->method->invoke(iattr.record, &sattr.ivalue);
sattr.ivalue = *(int1*)&sattr.ivalue;
return;
case dbvmInvokeSelfMethodInt2:
expr->ref.field->method->invoke(iattr.record, &sattr.ivalue);
sattr.ivalue = *(int2*)&sattr.ivalue;
return;
case dbvmInvokeSelfMethodInt4:
expr->ref.field->method->invoke(iattr.record, &sattr.ivalue);
sattr.ivalue = *(int4*)&sattr.ivalue;
return;
case dbvmInvokeSelfMethodInt8:
expr->ref.field->method->invoke(iattr.record, &sattr.ivalue);
return;
case dbvmInvokeSelfMethodReal4:
expr->ref.field->method->invoke(iattr.record, &sattr.fvalue);
sattr.fvalue = *(real4*)&sattr.fvalue;
return;
case dbvmInvokeSelfMethodReal8:
expr->ref.field->method->invoke(iattr.record, &sattr.fvalue);
return;
case dbvmInvokeSelfMethodReference:
expr->ref.field->method->invoke(iattr.record, &sattr.oid);
return;
case dbvmInvokeSelfMethodString:
expr->ref.field->method->invoke(iattr.record, &sattr2.array.base);
sattr.array.size = (int)strlen(sattr2.array.base) + 1;
sattr.array.base = dbStringValue::create(sattr2.array.base, iattr);
sattr.array.comparator = NULL;
delete[] sattr2.array.base;
return;
case dbvmInvokeSelfMethodWString:
expr->ref.field->method->invoke(iattr.record, &sattr2.array.base);
sattr.array.size = (int)wcslen((wchar_t*)sattr2.array.base) + 1;
sattr.array.base = dbStringValue::create(sattr.array.size*sizeof(wchar_t), iattr);
sattr.array.comparator = NULL;
memcpy(sattr.array.base, sattr2.array.base, sattr.array.size*sizeof(wchar_t));
delete[] (wchar_t*)sattr2.array.base;
return;
case dbvmLength:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = sattr.array.size;
return;
case dbvmStringLength:
case dbvmWStringLength:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = sattr.array.size - 1;
return;
case dbvmGetAt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if ((nat8)sattr2.ivalue >= (nat8)sattr.array.size) {
if (expr->operand[1]->cop == dbvmVariable) {
longjmp(iattr.exists_iterator[expr->operand[1]->offs].unwind, 1);
}
iattr.removeTemporaries();
iattr.db->handleError(IndexOutOfRangeError, NULL,
int(sattr2.ivalue));
}
sattr.base = (byte*)sattr.array.base + int(sattr2.ivalue)*expr->offs;
return;
case dbvmRectangleCoord:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if ((nat8)sattr2.ivalue >= rectangle::dim*2) {
if (expr->operand[1]->cop == dbvmVariable) {
longjmp(iattr.exists_iterator[expr->operand[1]->offs].unwind, 1);
}
iattr.removeTemporaries();
iattr.db->handleError(IndexOutOfRangeError, NULL,
int(sattr2.ivalue));
}
sattr.fvalue = sattr.rvalue.boundary[int(sattr2.ivalue)];
return;
case dbvmCharAt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if ((nat8)sattr2.ivalue >= (nat8)(sattr.array.size-1)) {
if (expr->operand[1]->cop == dbvmVariable) {
longjmp(iattr.exists_iterator[expr->operand[1]->offs].unwind, 1);
}
iattr.removeTemporaries();
iattr.db->handleError(IndexOutOfRangeError, NULL,
int(sattr2.ivalue));
}
sattr.ivalue = (byte)sattr.array.base[int(sattr2.ivalue)];
return;
case dbvmWCharAt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if ((nat8)sattr2.ivalue >= (nat8)(sattr.array.size-1)) {
if (expr->operand[1]->cop == dbvmVariable) {
longjmp(iattr.exists_iterator[expr->operand[1]->offs].unwind, 1);
}
iattr.removeTemporaries();
iattr.db->handleError(IndexOutOfRangeError, NULL,
int(sattr2.ivalue));
}
sattr.ivalue = *((wchar_t*)sattr.array.base + int(sattr2.ivalue));
return;
case dbvmExists:
iattr.exists_iterator[expr->offs].index = 0;
if (setjmp(iattr.exists_iterator[expr->offs].unwind) == 0) {
do {
execute(expr->operand[0], iattr, sattr);
iattr.exists_iterator[expr->offs].index += 1;
} while (!sattr.bvalue);
} else {
sattr.bvalue = false;
}
return;
case dbvmVariable:
sattr.ivalue = iattr.exists_iterator[expr->offs].index;
return;
case dbvmLoadVarBool:
sattr.bvalue = *(bool*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarInt1:
sattr.ivalue = *(int1*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarInt2:
sattr.ivalue = *(int2*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarInt4:
sattr.ivalue = *(int4*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarInt8:
sattr.ivalue = *(db_int8*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarReal4:
sattr.fvalue = *(real4*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarReal8:
sattr.fvalue = *(real8*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarReference:
sattr.oid = *(oid_t*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarRectangle:
sattr.rvalue = *(rectangle*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarRectanglePtr:
sattr.rvalue = **(rectangle**)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarString:
sattr.array.base = ((char*)expr->var + iattr.paramBase);
sattr.array.size = (int)strlen((char*)sattr.array.base) + 1;
sattr.array.comparator = NULL;
return;
case dbvmLoadVarWString:
sattr.array.base = ((char*)expr->var + iattr.paramBase);
sattr.array.size = (int)wcslen((wchar_t*)sattr.array.base) + 1;
sattr.array.comparator = NULL;
return;
case dbvmLoadVarStringPtr:
sattr.array.base = *(char**)((char*)expr->var + iattr.paramBase);
sattr.array.size = (int)strlen((char*)sattr.array.base) + 1;
sattr.array.comparator = NULL;
return;
case dbvmLoadVarWStringPtr:
sattr.array.base = *(char**)((char*)expr->var + iattr.paramBase);
sattr.array.size = (int)wcslen((wchar_t*)sattr.array.base) + 1;
sattr.array.comparator = NULL;
return;
case dbvmLoadVarArrayOfOid:
case dbvmLoadVarArrayOfInt4:
case dbvmLoadVarArrayOfInt8:
sattr.array.base = (char*)((dbAnyArray*)((char*)expr->var + iattr.paramBase))->base();
sattr.array.size = (int)((dbAnyArray*)((char*)expr->var + iattr.paramBase))->length();
sattr.array.comparator = NULL;
return;
case dbvmLoadVarArrayOfOidPtr:
case dbvmLoadVarArrayOfInt4Ptr:
case dbvmLoadVarArrayOfInt8Ptr:
{
dbAnyArray* arr = *(dbAnyArray**)((char*)expr->var + iattr.paramBase);
sattr.array.base = (char*)arr->base();
sattr.array.size = (int)arr->length();
sattr.array.comparator = NULL;
return;
}
case dbvmLoadVarRawBinary:
sattr.raw = (void*)((char*)expr->var + iattr.paramBase);
return;
case dbvmLoadVarRawBinaryPtr:
sattr.raw = *(void**)((char*)expr->var + iattr.paramBase);
return;
#ifdef USE_STD_STRING
case dbvmLoadVarStdString:
sattr.array.base = (char*)((std::string*)((char*)expr->var + iattr.paramBase))->c_str();
sattr.array.size = (int)((std::string*)((char*)expr->var + iattr.paramBase))->length() + 1;
sattr.array.comparator = NULL;
return;
case dbvmLoadVarStdWString:
sattr.array.base = (char*)((std::wstring*)((char*)expr->var + iattr.paramBase))->c_str();
sattr.array.size = (int)((std::wstring*)((char*)expr->var + iattr.paramBase))->length() + 1;
sattr.array.comparator = NULL;
return;
#endif
case dbvmLoadTrue:
sattr.bvalue = true;
return;
case dbvmLoadFalse:
sattr.bvalue = false;
return;
case dbvmLoadNull:
sattr.oid = 0;
return;
case dbvmLoadIntConstant:
sattr.ivalue = expr->ivalue;
return;
case dbvmLoadRealConstant:
sattr.fvalue = expr->fvalue;
return;
case dbvmLoadRectangleConstant:
sattr.rvalue = expr->rvalue;
return;
case dbvmLoadStringConstant:
sattr.array.base = expr->svalue.str;
sattr.array.size = expr->svalue.len;
sattr.array.comparator = NULL;
return;
case dbvmLoadWStringConstant:
sattr.array.base = (char*)expr->wsvalue.str;
sattr.array.size = expr->wsvalue.len;
sattr.array.comparator = NULL;
return;
case dbvmOrBool:
execute(expr->operand[0], iattr, sattr);
if (sattr.bvalue == 0) {
execute(expr->operand[1], iattr, sattr);
}
return;
case dbvmAndBool:
execute(expr->operand[0], iattr, sattr);
if (sattr.bvalue != 0) {
execute(expr->operand[1], iattr, sattr);
}
return;
case dbvmNotBool:
execute(expr->operand[0], iattr, sattr);
sattr.bvalue = !sattr.bvalue;
return;
case dbvmIsNull:
execute(expr->operand[0], iattr, sattr);
sattr.bvalue = sattr.oid == 0;
return;
case dbvmAddRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.rvalue += sattr2.rvalue;
return;
case dbvmNegInt:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = -sattr.ivalue;
return;
case dbvmAddInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.ivalue += sattr2.ivalue;
return;
case dbvmSubInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.ivalue -= sattr2.ivalue;
return;
case dbvmMulInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.ivalue *= sattr2.ivalue;
return;
case dbvmDivInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr2.ivalue == 0) {
iattr.removeTemporaries();
iattr.db->handleError(ArithmeticError, "Division by zero");
} else {
sattr.ivalue /= sattr2.ivalue;
}
return;
case dbvmAndInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.ivalue &= sattr2.ivalue;
return;
case dbvmOrInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.ivalue |= sattr2.ivalue;
return;
case dbvmNotInt:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = ~sattr.ivalue;
return;
case dbvmAbsInt:
execute(expr->operand[0], iattr, sattr);
if (sattr.ivalue < 0) {
sattr.ivalue = -sattr.ivalue;
}
return;
case dbvmPowerInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr.ivalue == 2) {
sattr.ivalue = sattr2.ivalue < 64
? (nat8)1 << (int)sattr2.ivalue : 0;
} else if (sattr.ivalue == 0 && sattr2.ivalue < 0) {
iattr.removeTemporaries();
iattr.db->handleError(ArithmeticError,
"Raise zero to negative power");
} else {
sattr.ivalue = powerIntInt(sattr.ivalue, sattr2.ivalue);
}
return;
case dbvmEqInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.ivalue == sattr2.ivalue;
return;
case dbvmNeInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.ivalue != sattr2.ivalue;
return;
case dbvmGtInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.ivalue > sattr2.ivalue;
return;
case dbvmGeInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.ivalue >= sattr2.ivalue;
return;
case dbvmLtInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.ivalue < sattr2.ivalue;
return;
case dbvmLeInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.ivalue <= sattr2.ivalue;
return;
case dbvmBetweenInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr.ivalue < sattr2.ivalue) {
sattr.bvalue = false;
} else {
execute(expr->operand[2], iattr, sattr2);
sattr.bvalue = sattr.ivalue <= sattr2.ivalue;
}
return;
case dbvmEqArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) == 0;
return;
case dbvmNeArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) != 0;
return;
case dbvmLeArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) <= 0;
return;
case dbvmLtArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) < 0;
return;
case dbvmGeArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) >= 0;
return;
case dbvmGtArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) > 0;
return;
case dbvmBetweenArray:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if ((*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) < 0)
{
sattr.bvalue = false;
} else {
execute(expr->operand[2], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(&dbArray<char>(sattr.array.base, sattr.array.size),
&dbArray<char>(sattr2.array.base, sattr2.array.size),
0) <= 0;
}
return;
case dbvmEqRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue == sattr2.rvalue;
return;
case dbvmNeRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue != sattr2.rvalue;
return;
case dbvmGtRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue > sattr2.rvalue;
return;
case dbvmGeRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue >= sattr2.rvalue;
return;
case dbvmLtRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue < sattr2.rvalue;
return;
case dbvmLeRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue <= sattr2.rvalue;
return;
case dbvmOverlapsRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.rvalue & sattr2.rvalue;
return;
case dbvmRectangleArea:
execute(expr->operand[0], iattr, sattr);
sattr.fvalue = (double)area(sattr.rvalue);
return;
case dbvmNegReal:
execute(expr->operand[0], iattr, sattr);
sattr.fvalue = -sattr.fvalue;
return;
case dbvmAddReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.fvalue += sattr2.fvalue;
return;
case dbvmSubReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.fvalue -= sattr2.fvalue;
return;
case dbvmMulReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.fvalue *= sattr2.fvalue;
return;
case dbvmDivReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr2.fvalue == 0.0) {
iattr.removeTemporaries();
iattr.db->handleError(ArithmeticError, "Division by zero");
} else {
sattr.fvalue /= sattr2.fvalue;
}
return;
case dbvmAbsReal:
execute(expr->operand[0], iattr, sattr);
if (sattr.fvalue < 0) {
sattr.fvalue = -sattr.fvalue;
}
return;
case dbvmPowerReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr.fvalue < 0) {
iattr.removeTemporaries();
iattr.db->handleError(ArithmeticError,
"Power operator returns complex result");
} else if (sattr.fvalue == 0.0 && sattr2.fvalue < 0) {
iattr.removeTemporaries();
iattr.db->handleError(ArithmeticError,
"Raise zero to negative power");
} else {
sattr.fvalue = pow(sattr.fvalue, sattr2.fvalue);
}
return;
case dbvmPowerRealInt:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr.fvalue == 0.0 && sattr2.ivalue < 0) {
iattr.removeTemporaries();
iattr.db->handleError(ArithmeticError,
"Raise zero to negative power");
} else {
sattr.fvalue = powerRealInt(sattr.fvalue, sattr2.ivalue);
}
return;
case dbvmEqReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.fvalue == sattr2.fvalue;
return;
case dbvmNeReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.fvalue != sattr2.fvalue;
return;
case dbvmGtReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.fvalue > sattr2.fvalue;
return;
case dbvmGeReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.fvalue >= sattr2.fvalue;
return;
case dbvmLtReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.fvalue < sattr2.fvalue;
return;
case dbvmLeReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.fvalue <= sattr2.fvalue;
return;
case dbvmBetweenReal:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (sattr.fvalue < sattr2.fvalue) {
sattr.bvalue = false;
} else {
execute(expr->operand[2], iattr, sattr2);
sattr.bvalue = sattr.fvalue <= sattr2.fvalue;
}
return;
case dbvmEqBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) == 0;
return;
case dbvmNeBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) != 0;
return;
case dbvmGtBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) > 0;
return;
case dbvmGeBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) >= 0;
return;
case dbvmLtBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) < 0;
return;
case dbvmLeBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) <= 0;
return;
case dbvmBetweenBinary:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if ((*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) < 0) {
sattr.bvalue = false;
} else {
execute(expr->operand[2], iattr, sattr2);
sattr.bvalue = (*(dbUDTComparator)expr->func.fptr)(sattr.raw, sattr2.raw, expr->offs) <= 0;
}
return;
case dbvmIntToReference:
execute(expr->operand[0], iattr, sattr);
sattr.oid = (oid_t)sattr.ivalue;
return;
case dbvmIntToReal:
execute(expr->operand[0], iattr, sattr);
sattr.fvalue = (real8)sattr.ivalue;
return;
case dbvmRealToInt:
execute(expr->operand[0], iattr, sattr);
sattr.ivalue = (db_int8)sattr.fvalue;
return;
case dbvmIntToString:
execute(expr->operand[0], iattr, sattr);
convertIntToString(iattr, sattr);
return;
case dbvmRealToString:
execute(expr->operand[0], iattr, sattr);
convertRealToString(iattr, sattr);
return;
case dbvmWcsToMbs:
execute(expr->operand[0], iattr, sattr);
convertWcsToMbs(iattr, sattr);
return;
case dbvmMbsToWcs:
execute(expr->operand[0], iattr, sattr);
convertMbsToWcs(iattr, sattr);
return;
case dbvmStringConcat:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
concatenateStrings(iattr, sattr, sattr2);
return;
case dbvmUpperString:
execute(expr->operand[0], iattr, sattr);
uppercaseString(iattr, sattr);
return;
case dbvmLowerString:
execute(expr->operand[0], iattr, sattr);
lowercaseString(iattr, sattr);
return;
case dbvmWStringConcat:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
concatenateWStrings(iattr, sattr, sattr2);
return;
case dbvmUpperWString:
execute(expr->operand[0], iattr, sattr);
uppercaseWString(iattr, sattr);
return;
case dbvmLowerWString:
execute(expr->operand[0], iattr, sattr);
lowercaseWString(iattr, sattr);
return;
case dbvmEqString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareStringsForEquality(sattr, sattr2);
return;
case dbvmNeString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = !compareStringsForEquality(sattr, sattr2);
return;
case dbvmGtString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareStrings(sattr, sattr2) > 0;
return;
case dbvmGeString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareStrings(sattr, sattr2) >= 0;
return;
case dbvmLtString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareStrings(sattr, sattr2) < 0;
return;
case dbvmLeString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareStrings(sattr, sattr2) <= 0;
return;
case dbvmEqWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareWStringsForEquality(sattr, sattr2);
return;
case dbvmNeWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = !compareWStringsForEquality(sattr, sattr2);
return;
case dbvmGtWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareWStrings(sattr, sattr2) > 0;
return;
case dbvmGeWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareWStrings(sattr, sattr2) >= 0;
return;
case dbvmLtWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareWStrings(sattr, sattr2) < 0;
return;
case dbvmLeWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = compareWStrings(sattr, sattr2) <= 0;
return;
#ifdef USE_REGEX
case dbvmMatchString:
execute(expr->regex.opd, iattr, sattr);
sattr.bvalue = regexec(&expr->regex.re, (char*)sattr.array.base, 0, NULL, 0) == 0;
return;
#endif
case dbvmLikeString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = matchStrings(sattr, sattr2);
return;
case dbvmLikeEscapeString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
execute(expr->operand[2], iattr, sattr3);
sattr.bvalue = matchStrings(sattr, sattr2, *sattr3.array.base);
return;
case dbvmBetweenString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (compareStrings(sattr, sattr2) < 0) {
sattr.bvalue = false;
} else {
execute(expr->operand[2], iattr, sattr2);
sattr.bvalue = compareStrings(sattr, sattr2) <= 0;
}
return;
case dbvmLikeWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = matchWStrings(sattr, sattr2);
return;
case dbvmLikeEscapeWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
execute(expr->operand[2], iattr, sattr3);
sattr.bvalue = matchWStrings(sattr, sattr2, *sattr3.array.base);
return;
case dbvmBetweenWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
if (compareWStrings(sattr, sattr2) < 0) {
sattr.bvalue = false;
} else {
execute(expr->operand[2], iattr, sattr2);
sattr.bvalue = compareWStrings(sattr, sattr2) <= 0;
}
return;
case dbvmEqBool:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.bvalue == sattr2.bvalue;
return;
case dbvmNeBool:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.bvalue != sattr2.bvalue;
return;
case dbvmEqReference:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.oid == sattr2.oid;
return;
case dbvmNeReference:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
sattr.bvalue = sattr.oid != sattr2.oid;
return;
case dbvmDeref:
execute(expr->operand[0], iattr, sattr);
if (sattr.oid == 0) {
iattr.removeTemporaries();
iattr.db->handleError(NullReferenceError);
}
FASTDB_ASSERT_EX(iattr.db, !(iattr.db->currIndex[sattr.oid]
& (dbInternalObjectMarker|dbFreeHandleMarker)));
sattr.base = iattr.db->baseAddr + iattr.db->currIndex[sattr.oid];
return;
case dbvmFuncArg2Bool:
sattr.bvalue = (*(bool(*)(dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0));
return;
case dbvmFuncArg2Int:
sattr.ivalue = (*(db_int8(*)(dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0));
return;
case dbvmFuncArg2Real:
sattr.fvalue = (*(real8(*)(dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0));
return;
case dbvmFuncArg2Str:
copyString(iattr, sattr,
(*(char*(*)(dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0)));
return;
case dbvmFuncArg2WStr:
copyWString(iattr, sattr,
(*(wchar_t*(*)(dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0)));
return;
case dbvmFuncArgArg2Bool:
sattr.bvalue = (*(bool(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1));
return;
case dbvmFuncArgArg2Int:
sattr.ivalue = (*(db_int8(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1));
return;
case dbvmFuncArgArg2Real:
sattr.fvalue = (*(real8(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1));
return;
case dbvmFuncArgArg2Str:
copyString(iattr, sattr,
(*(char*(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1)));
return;
case dbvmFuncArgArg2WStr:
copyWString(iattr, sattr,
(*(wchar_t*(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1)));
return;
case dbvmFuncArgArgArg2Bool:
sattr.bvalue = (*(bool(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1),
dbUserFunctionArgument(expr, iattr, sattr, 2));
return;
case dbvmFuncArgArgArg2Int:
sattr.ivalue = (*(db_int8(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1),
dbUserFunctionArgument(expr, iattr, sattr, 2));
return;
case dbvmFuncArgArgArg2Real:
sattr.fvalue = (*(real8(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1),
dbUserFunctionArgument(expr, iattr, sattr, 2));
return;
case dbvmFuncArgArgArg2Str:
copyString(iattr, sattr,
(*(char*(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1),
dbUserFunctionArgument(expr, iattr, sattr, 2)));
return;
case dbvmFuncArgArgArg2WStr:
copyWString(iattr, sattr,
(*(wchar_t*(*)(dbUserFunctionArgument const&, dbUserFunctionArgument const&, dbUserFunctionArgument const&))expr->func.fptr)
(dbUserFunctionArgument(expr, iattr, sattr, 0),
dbUserFunctionArgument(expr, iattr, sattr, 1),
dbUserFunctionArgument(expr, iattr, sattr, 2)));
return;
case dbvmFuncInt2Bool:
execute(expr->func.arg[0], iattr, sattr);
sattr.bvalue = (*(bool(*)(db_int8))expr->func.fptr)(sattr.ivalue);
return;
case dbvmFuncReal2Bool:
execute(expr->func.arg[0], iattr, sattr);
sattr.bvalue = (*(bool(*)(real8))expr->func.fptr)(sattr.fvalue);
return;
case dbvmFuncStr2Bool:
execute(expr->func.arg[0], iattr, sattr);
sattr.bvalue =
(*(bool(*)(char const*))expr->func.fptr)(sattr.array.base);
return;
case dbvmFuncWStr2Bool:
execute(expr->func.arg[0], iattr, sattr);
sattr.bvalue =
(*(bool(*)(wchar_t const*))expr->func.fptr)((wchar_t*)sattr.array.base);
return;
case dbvmFuncInt2Int:
execute(expr->func.arg[0], iattr, sattr);
sattr.ivalue = (*(db_int8(*)(db_int8))expr->func.fptr)(sattr.ivalue);
return;
case dbvmFuncReal2Int:
execute(expr->func.arg[0], iattr, sattr);
sattr.ivalue = (*(db_int8(*)(real8))expr->func.fptr)(sattr.fvalue);
return;
case dbvmFuncStr2Int:
execute(expr->func.arg[0], iattr, sattr);
sattr.ivalue =
(*(db_int8(*)(char const*))expr->func.fptr)(sattr.array.base);
return;
case dbvmFuncWStr2Int:
execute(expr->func.arg[0], iattr, sattr);
sattr.ivalue =
(*(db_int8(*)(wchar_t const*))expr->func.fptr)((wchar_t*)sattr.array.base);
return;
case dbvmFuncInt2Real:
execute(expr->func.arg[0], iattr, sattr);
sattr.fvalue = (*(real8(*)(db_int8))expr->func.fptr)(sattr.ivalue);
return;
case dbvmFuncReal2Real:
execute(expr->func.arg[0], iattr, sattr);
sattr.fvalue = (*(real8(*)(real8))expr->func.fptr)(sattr.fvalue);
return;
case dbvmFuncStr2Real:
execute(expr->func.arg[0], iattr, sattr);
sattr.fvalue =
(*(real8(*)(char const*))expr->func.fptr)(sattr.array.base);
return;
case dbvmFuncWStr2Real:
execute(expr->func.arg[0], iattr, sattr);
sattr.fvalue =
(*(real8(*)(wchar_t const*))expr->func.fptr)((wchar_t*)sattr.array.base);
return;
case dbvmFuncInt2Str:
execute(expr->func.arg[0], iattr, sattr);
copyString(iattr, sattr,
(*(char*(*)(db_int8))expr->func.fptr)(sattr.ivalue));
return;
case dbvmFuncReal2Str:
execute(expr->func.arg[0], iattr, sattr);
copyString(iattr, sattr,
(*(char*(*)(real8))expr->func.fptr)(sattr.fvalue));
return;
case dbvmFuncStr2Str:
execute(expr->func.arg[0], iattr, sattr);
copyString(iattr, sattr,
(*(char*(*)(char const*))expr->func.fptr)(sattr.array.base));
return;
case dbvmFuncWStr2Str:
execute(expr->func.arg[0], iattr, sattr);
copyString(iattr, sattr,
(*(char*(*)(wchar_t const*))expr->func.fptr)((wchar_t*)sattr.array.base));
return;
case dbvmFuncInt2WStr:
execute(expr->func.arg[0], iattr, sattr);
copyWString(iattr, sattr,
(*(wchar_t*(*)(db_int8))expr->func.fptr)(sattr.ivalue));
return;
case dbvmFuncReal2WStr:
execute(expr->func.arg[0], iattr, sattr);
copyWString(iattr, sattr,
(*(wchar_t*(*)(real8))expr->func.fptr)(sattr.fvalue));
return;
case dbvmFuncStr2WStr:
execute(expr->func.arg[0], iattr, sattr);
copyWString(iattr, sattr,
(*(wchar_t*(*)(char const*))expr->func.fptr)(sattr.array.base));
return;
case dbvmFuncWStr2WStr:
execute(expr->func.arg[0], iattr, sattr);
copyWString(iattr, sattr,
(*(wchar_t*(*)(wchar_t const*))expr->func.fptr)((wchar_t*)sattr.array.base));
return;
case dbvmInArrayBool:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfBool(sattr, sattr2);
return;
case dbvmInArrayInt1:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfInt1(sattr, sattr2);
return;
case dbvmInArrayInt2:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfInt2(sattr, sattr2);
return;
case dbvmInArrayInt4:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfInt4(sattr, sattr2);
return;
case dbvmInArrayInt8:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfInt8(sattr, sattr2);
return;
case dbvmInArrayReal4:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfReal4(sattr, sattr2);
return;
case dbvmInArrayReal8:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfReal8(sattr, sattr2);
return;
case dbvmInArrayString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfString(sattr, sattr2);
return;
case dbvmInArrayWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfWString(sattr, sattr2);
return;
case dbvmInArrayReference:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfReference(sattr, sattr2);
return;
case dbvmInArrayRectangle:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchArrayOfRectangle(iattr, sattr, sattr2);
return;
case dbvmInString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchInString(sattr, sattr2);
return;
case dbvmInWString:
execute(expr->operand[0], iattr, sattr);
execute(expr->operand[1], iattr, sattr2);
searchInWString(sattr, sattr2);
return;
case dbvmList:
return;
default:
FASTDB_ASSERT_EX(iattr.db, false);
}
}
char const* const dbDatabase::errorMessage[] =
{
"No error",
"Query syntax error",
"Arithmetic exception",
"Index out of range",
"Database open error",
"File access error",
"Out of memory",
"Deadlock",
"Null reference",
"Lock revoked",
"File limit exeeded",
"Inconsistent inverse reference",
"Attempt to modify read-only database",
"Assertion failed",
"Access to deleted object",
"No current record",
"Cursor is read-only",
"Incompatible schema change"
};
#ifdef _WIN32
#define snprintf _snprintf
#endif
void dbDatabase::formatErrorMessage(char* buf, size_t bufSize, dbErrorClass error, char const* msg, int arg)
{
switch (error) {
case QueryError:
snprintf(buf, bufSize, "%s in position %d", msg, arg);
break;
case ArithmeticError:
snprintf(buf, bufSize, "%s", msg);
break;
case IndexOutOfRangeError:
snprintf(buf, bufSize, "Index %d is out of range", arg);
break;
case DatabaseOpenError:
snprintf(buf, bufSize, "%s", msg);
break;
case FileError:
snprintf(buf, bufSize, "%s: %s", msg, dbFile::errorText(arg, buf, sizeof(buf)));
break;
case OutOfMemoryError:
snprintf(buf, bufSize,"Not enough memory: failed to allocate %d bytes", arg);
break;
case NullReferenceError:
snprintf(buf, bufSize, "Null object reference is accessed");
break;
case Deadlock:
snprintf(buf, bufSize, "Deadlock is caused by upgrading shared locks to exclusive");
break;
case LockRevoked:
snprintf(buf, bufSize, "Lock is revoked by some other client");
break;
case InconsistentInverseReference:
snprintf(buf, bufSize, "%s", msg);
break;
case DatabaseReadOnly:
snprintf(buf, bufSize, "Attempt to modify readonly database");
break;
case AssertionFailed:
snprintf(buf, bufSize, "Assertion failed %s at line %d", msg, arg);
break;
default:
snprintf(buf, bufSize, "Error %d: %s", error, msg);
}
}
void dbDatabase::fatalError()
{
abort();
}
void dbDatabase::handleError(dbErrorClass error, char const* msg, int arg)
{
if (errorHandler != NULL) {
(*errorHandler)(error, msg, arg, errorHandlerContext);
}
#ifdef THROW_EXCEPTION_ON_ERROR
if (error != NoError) {
if (msg == NULL) {
msg = errorMessage[error];
}
if (error == DatabaseOpenError || (error == InconsistentInverseReference && dbTableDescriptor::chain == NULL)) {
fprintf(stderr, "%s\n", msg);
} else {
throw dbException(error, msg, arg);
}
}
#else
char buf[256];
switch (error) {
case QueryError:
fprintf(stderr, "%s in position %d\n", msg, arg);
return;
case ArithmeticError:
fprintf(stderr, "%s\n", msg);
break;
case IndexOutOfRangeError:
fprintf(stderr, "Index %d is out of range\n", arg);
break;
case DatabaseOpenError:
fprintf(stderr, "%s\n", msg);
return;
case FileError:
fprintf(stderr, "%s: %s\n", msg,
dbFile::errorText(arg, buf, sizeof(buf)));
break;
case OutOfMemoryError:
fprintf(stderr,"Not enough memory: failed to allocate %d bytes\n",arg);
break;
case NullReferenceError:
fprintf(stderr, "Null object reference is accessed\n");
break;
case Deadlock:
fprintf(stderr, "Deadlock is caused by upgrading shared locks to exclusive");
break;
case LockRevoked:
fprintf(stderr, "Lock is revoked by some other client\n");
break;
case InconsistentInverseReference:
fprintf(stderr, "%s\n", msg);
break;
case DatabaseReadOnly:
fprintf(stderr, "Attempt to modify readonly database\n");
break;
case AssertionFailed:
fprintf(stderr, "Assertion failed %s at line %d\n", error, arg);
break
default:
return;
}
fflush(stderr);
fatalError();
#endif
}
bool dbDatabase::isReplicated()
{
return false;
}
void dbDatabase::initializeMetaTable()
{
static struct {
char const* name;
int type;
int size;
int offs;
} metaTableFields[] = {
{ "name", dbField::tpString, sizeof(dbVarying),
offsetof(dbTable, name)},
{ "fields", dbField::tpArray, sizeof(dbVarying),
offsetof(dbTable, fields)},
{ "fields[]", dbField::tpStructure, sizeof(dbField), 0},
{ "fields[].name", dbField::tpString, sizeof(dbVarying),
offsetof(dbField, name)},
{ "fields[].tableName",dbField::tpString,sizeof(dbVarying),
offsetof(dbField, tableName)},
{ "fields[].inverse", dbField::tpString, sizeof(dbVarying),
offsetof(dbField, inverse)},
// { "fields[].type", dbField::tpInt4, 4, offsetof(dbField, type)},
{ "fields[].type", dbField::tpInt4, 4, offsetof(dbField, offset)-4},
{ "fields[].offset", dbField::tpInt4, 4, offsetof(dbField, offset)},
{ "fields[].size", dbField::tpInt4, 4, offsetof(dbField, size)},
{ "fields[].hashTable", dbField::tpReference, sizeof(oid_t),
offsetof(dbField, hashTable)},
{ "fields[].tTree", dbField::tpReference, sizeof(oid_t),
offsetof(dbField, tTree)},
{ "fixedSize", dbField::tpInt4, 4, offsetof(dbTable, fixedSize)},
{ "nRows", dbField::tpInt4, 4, offsetof(dbTable, nRows)},
{ "nColumns", dbField::tpInt4, 4, offsetof(dbTable, nColumns)},
{ "firstRow", dbField::tpReference, sizeof(oid_t), offsetof(dbTable, firstRow)},
{ "lastRow", dbField::tpReference, sizeof(oid_t), offsetof(dbTable, lastRow)}
#ifdef AUTOINCREMENT_SUPPORT
,{ "count", dbField::tpInt4, 4, offsetof(dbTable, count)}
#endif
};
unsigned i;
size_t varyingSize = strlen(dbMetaTableName)+1;
for (i = 0; i < itemsof(metaTableFields); i++) {
varyingSize += strlen(metaTableFields[i].name) + 3;
}
offs_t metaTableOffs = allocate(sizeof(dbTable)
+ sizeof(dbField)*itemsof(metaTableFields)
+ varyingSize);
index[0][dbMetaTableId] = metaTableOffs;
dbTable* table = (dbTable*)(baseAddr + metaTableOffs);
table->size = (nat4)(sizeof(dbTable) + sizeof(dbField)*itemsof(metaTableFields)
+ varyingSize);
table->next = table->prev = 0;
int offs = sizeof(dbTable) + sizeof(dbField)*itemsof(metaTableFields);
table->name.offs = offs;
table->name.size = (nat4)strlen(dbMetaTableName)+1;
strcpy((char*)table + offs, dbMetaTableName);
offs += table->name.size;
table->fields.offs = sizeof(dbTable);
table->fields.size = itemsof(metaTableFields);
table->fixedSize = sizeof(dbTable);
table->nRows = 0;
table->nColumns = 5;
table->firstRow = 0;
table->lastRow = 0;
#ifdef AUTOINCREMENT_SUPPORT
table->count = 0;
#endif
dbField* field = (dbField*)((char*)table + table->fields.offs);
offs -= sizeof(dbTable);
for (i = 0; i < itemsof(metaTableFields); i++) {
field->name.offs = offs;
field->name.size = (nat4)strlen(metaTableFields[i].name) + 1;
strcpy((char*)field + offs, metaTableFields[i].name);
offs += field->name.size;
field->tableName.offs = offs;
field->tableName.size = 1;
*((char*)field + offs++) = '\0';
field->inverse.offs = offs;
field->inverse.size = 1;
*((char*)field + offs++) = '\0';
field->flags = 0;
field->type = metaTableFields[i].type;
field->size = metaTableFields[i].size;
field->offset = metaTableFields[i].offs;
field->hashTable = 0;
field->tTree = 0;
field += 1;
offs -= sizeof(dbField);
}
}
void dbDatabase::cleanup(dbInitializationMutex::initializationStatus status, int step)
{
switch (step) {
case 9:
if (status == dbInitializationMutex::NotYetInitialized) {
file.close();
}
// no break
case 8:
if (accessType == dbConcurrentUpdate || accessType == dbConcurrentRead) {
mutatorCS.close();
}
// no break
case 7:
if (delayedCommitEventsOpened) {
delayedCommitStopTimerEvent.close();
delayedCommitStartTimerEvent.close();
commitThreadSyncEvent.close();
delayedCommitEventsOpened = false;
}
// no break
case 6:
cs.close();
// no break
case 5:
backupCompletedEvent.close();
// no break
case 4:
upgradeSem.close();
// no break
case 3:
readSem.close();
// no break
case 2:
writeSem.close();
// no break
case 1:
shm.close();
// no break
default:
if (status == dbInitializationMutex::NotYetInitialized) {
initMutex.done();
}
initMutex.close();
}
}
bool dbDatabase::open(OpenParameters& params)
{
accessType = params.accessType;
fileOpenFlags = params.fileOpenFlags;
if (accessType == dbReadOnly || accessType == dbConcurrentRead) {
fileOpenFlags |= dbFile::read_only;
}
extensionQuantum = params.extensionQuantum;
initIndexSize = params.initIndexSize;
initSize = params.initSize;
freeSpaceReuseThreshold = params.freeSpaceReuseThreshold;
parallelScanThreshold = params.parallelScanThreshold;
setConcurrency(params.nThreads);
return open(params.databaseName, params.databaseFilePath, params.waitLockTimeoutMsec, params.transactionCommitDelay);
}
bool dbDatabase::open(char_t const* dbName, char_t const* fiName,
time_t waitLockTimeoutMsec, time_t commitDelaySec)
{
waitLockTimeout = (unsigned)waitLockTimeoutMsec;
delete[] databaseName;
delete[] fileName;
commitDelay = 0;
commitTimeout = 0;
commitTimerStarted = 0;
delayedCommitEventsOpened = false;
backupFileName = NULL;
backupPeriod = 0;
opened = false;
stopDelayedCommitThread = false;
memset(tableHash, 0, sizeof tableHash);
databaseNameLen = (int)_tcslen(dbName);
char_t* name = new char_t[databaseNameLen+16];
_stprintf(name, _T("%s.in"), dbName);
databaseName = name;
if (fiName == NULL) {
fileName = new char_t[databaseNameLen + 5];
_stprintf(fileName, _T("%s.fdb"), dbName);
} else {
fileName = new char_t[_tcslen(fiName)+1];
_stprintf(fileName, fiName);
}
dbInitializationMutex::initializationStatus status = initMutex.initialize(name);
if (status == dbInitializationMutex::InitializationError) {
handleError(DatabaseOpenError,
"Failed to start database initialization");
return false;
}
_stprintf(name, _T("%s.dm"), dbName);
if (!shm.open(name)) {
handleError(DatabaseOpenError, "Failed to open database monitor");
cleanup(status, 0);
return false;
}
monitor = shm.get();
_stprintf(name, _T("%s.ws"), dbName);
if (!writeSem.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database writers semaphore");
cleanup(status, 1);
return false;
}
_stprintf(name, _T("%s.rs"), dbName);
if (!readSem.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database readers semaphore");
cleanup(status, 2);
return false;
}
_stprintf(name, _T("%s.us"), dbName);
if (!upgradeSem.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database upgrade semaphore");
cleanup(status, 3);
return false;
}
_stprintf(name, _T("%s.bce"), dbName);
if (!backupCompletedEvent.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database backup completed event");
cleanup(status, 4);
return false;
}
if (commitDelaySec != 0) {
_stprintf(name, _T("%s.dce"), dbName);
delayedCommitEventsOpened = true;
if (!delayedCommitStopTimerEvent.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize delayed commit event");
cleanup(status, 5);
return false;
}
delayedCommitStartTimerEvent.open();
commitThreadSyncEvent.open();
}
backupInitEvent.open();
backupFileName = NULL;
fixedSizeAllocator.reset();
allocatedSize = 0;
deallocatedSize = 0;
size_t indexSize = initIndexSize < dbFirstUserId
? size_t(dbFirstUserId) : initIndexSize;
indexSize = DOALIGN(indexSize, dbHandlesPerPage);
size_t fileSize = initSize ? initSize : dbDefaultInitDatabaseSize;
if (fileSize < indexSize*sizeof(offs_t)*4) {
fileSize = indexSize*sizeof(offs_t)*4;
}
fileSize = DOALIGN(fileSize, dbBitmapSegmentSize);
for (int i = dbBitmapId + dbBitmapPages; --i >= 0;) {
bitmapPageAvailableSpace[i] = INT_MAX;
}
currRBitmapPage = currPBitmapPage = dbBitmapId;
currRBitmapOffs = currPBitmapOffs = 0;
reservedChain = NULL;
tables = NULL;
modified = false;
selfId = 0;
maxClientId = 0;
threadContextList.reset();
attach();
if (status == dbInitializationMutex::NotYetInitialized) {
_stprintf(name, _T("%s.cs"), dbName);
if (!cs.create(name, &monitor->sem)) {
handleError(DatabaseOpenError, "Failed to initialize database monitor");
cleanup(status, 6);
return false;
}
if (accessType == dbConcurrentUpdate || accessType == dbConcurrentRead) {
_stprintf(name, _T("%s.mcs"), dbName);
if (!mutatorCS.create(name, &monitor->mutatorSem)) {
handleError(DatabaseOpenError,
"Failed to initialize database monitor");
cleanup(status, 7);
return false;
}
}
readSem.reset();
writeSem.reset();
upgradeSem.reset();
monitor->nReaders = 0;
monitor->nWriters = 0;
monitor->nWaitReaders = 0;
monitor->nWaitWriters = 0;
monitor->waitForUpgrade = false;
monitor->version = version = 1;
monitor->users = 0;
monitor->backupInProgress = 0;
monitor->forceCommitCount = 0;
monitor->lastDeadlockRecoveryTime = 0;
monitor->delayedCommitContext = NULL;
monitor->concurrentTransId = 1;
monitor->commitInProgress = false;
monitor->uncommittedChanges = false;
monitor->clientId = 0;
monitor->upgradeId = 0;
monitor->modified = false;
monitor->exclusiveLockOwner = 0;
memset(monitor->dirtyPagesMap, 0, dbDirtyPageBitmapSize);
memset(monitor->sharedLockOwner, 0, sizeof(monitor->sharedLockOwner));
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
monitor->sessionFreeList[0].head = monitor->sessionFreeList[0].tail = 0;
monitor->sessionFreeList[1].head = monitor->sessionFreeList[1].tail = 0;
#endif
_stprintf(databaseName, _T("%s.%d"), dbName, version);
int rc = file.open(fileName, databaseName, fileOpenFlags, fileSize, false);
if (rc != dbFile::ok)
{
char msgbuf[64];
file.errorText(rc, msgbuf, sizeof msgbuf);
TRACE_MSG(("File open error: %s\n", msgbuf));
handleError(DatabaseOpenError, "Failed to create database file");
cleanup(status, 8);
return false;
}
baseAddr = (byte*)file.getAddr();
monitor->size = (offs_t)(fileSize = file.getSize());
header = (dbHeader*)baseAddr;
updatedRecordId = 0;
if ((unsigned)header->curr > 1) {
handleError(DatabaseOpenError, "Database file was corrupted: "
"invalid root index");
cleanup(status, 9);
return false;
}
if (header->initialized != 1) {
if (accessType == dbReadOnly || accessType == dbConcurrentRead) {
handleError(DatabaseOpenError, "Can not open uninitialized "
"file in read only mode");
cleanup(status, 9);
return false;
}
monitor->curr = header->curr = 0;
header->size = (offs_t)fileSize;
size_t used = dbPageSize;
header->root[0].index = (offs_t)used;
header->root[0].indexSize = (oid_t)indexSize;
header->root[0].indexUsed = dbFirstUserId;
header->root[0].freeList = 0;
used += indexSize*sizeof(offs_t);
header->root[1].index = (offs_t)used;
header->root[1].indexSize = (oid_t)indexSize;
header->root[1].indexUsed = dbFirstUserId;
header->root[1].freeList = 0;
used += indexSize*sizeof(offs_t);
header->root[0].shadowIndex = header->root[1].index;
header->root[1].shadowIndex = header->root[0].index;
header->root[0].shadowIndexSize = (oid_t)indexSize;
header->root[1].shadowIndexSize = (oid_t)indexSize;
header->majorVersion= FASTDB_MAJOR_VERSION;
header->minorVersion = FASTDB_MINOR_VERSION;
header->mode = dbHeader::getCurrentMode();
header->used = used;
index[0] = (offs_t*)(baseAddr + header->root[0].index);
index[1] = (offs_t*)(baseAddr + header->root[1].index);
index[0][dbInvalidId] = dbFreeHandleMarker;
size_t bitmapPages =
(used + dbPageSize*(dbAllocationQuantum*8-1) - 1)
/ (dbPageSize*(dbAllocationQuantum*8-1));
memset(baseAddr+used, 0xFF, (used + bitmapPages*dbPageSize)
/ (dbAllocationQuantum*8));
size_t i;
for (i = 0; i < bitmapPages; i++) {
index[0][dbBitmapId + i] = (offs_t)(used + dbPageObjectMarker);
used += dbPageSize;
}
while (i < dbBitmapPages) {
index[0][dbBitmapId+i] = dbFreeHandleMarker;
i += 1;
}
currIndex = index[0];
currIndexSize = dbFirstUserId;
committedIndexSize = 0;
initializeMetaTable();
header->dirty = true;
memcpy(index[1], index[0], currIndexSize*sizeof(offs_t));
file.markAsDirty(0, used);
file.flush(true);
header->initialized = true;
file.markAsDirty(0, sizeof(dbHeader));
file.flush(true);
} else {
if (!header->isCompatible()) {
handleError(DatabaseOpenError, "Incompatible database mode");
cleanup(status, 9);
return false;
}
monitor->curr = header->curr;
if (header->dirty) {
TRACE_MSG(("Database was not normally closed: start recovery\n"));
if (accessType == dbReadOnly || accessType == dbConcurrentRead) {
handleError(DatabaseOpenError,
"Can not open dirty file in read only mode");
cleanup(status, 9);
return false;
}
recovery();
TRACE_MSG(("Recovery completed\n"));
} else {
if (file.getSize() != header->size) {
handleError(DatabaseOpenError, "Database file was "
"corrupted: file size in header differs "
"from actual file size");
cleanup(status, 9);
return false;
}
}
}
} else {
_stprintf(name, _T("%s.cs"), dbName);
if (!cs.open(name, &monitor->sem)) {
handleError(DatabaseOpenError, "Failed to open shared semaphore");
cleanup(status, 6);
return false;
}
if (accessType == dbConcurrentUpdate || accessType == dbConcurrentRead) {
_stprintf(name, _T("%s.mcs"), dbName);
if (!mutatorCS.open(name, &monitor->mutatorSem)) {
handleError(DatabaseOpenError, "Failed to open shared semaphore");
cleanup(status, 7);
return false;
}
}
version = 0;
}
cs.enter();
monitor->users += 1;
selfId = ++monitor->clientId;
#ifdef AUTO_DETECT_PROCESS_CRASH
sprintf(databaseName + databaseNameLen, ".pid.%d", selfId);
selfWatchDog.create(databaseName);
watchDogMutex = new dbMutex();
#endif
cs.leave();
if (status == dbInitializationMutex::NotYetInitialized) {
if (!loadScheme(true)) {
cleanup(status, 9);
return false;
}
initMutex.done();
} else {
if (!loadScheme(false)) {
cleanup(status, 9);
return false;
}
}
opened = true;
if (commitDelaySec != 0) {
dbCriticalSection cs(delayedCommitStartTimerMutex);
commitTimeout = commitDelay = commitDelaySec;
commitThread.create((dbThread::thread_proc_t)delayedCommitProc, this);
commitThreadSyncEvent.wait(delayedCommitStartTimerMutex);
}
return true;
}
void dbDatabase::scheduleBackup(char_t const* fileName, time_t period)
{
if (backupFileName == NULL) {
backupFileName = new char_t[_tcslen(fileName) + 1];
_tcscpy(backupFileName, fileName);
backupPeriod = period;
backupThread.create((dbThread::thread_proc_t)backupSchedulerProc, this);
}
}
void dbDatabase::backupScheduler()
{
backupThread.setPriority(dbThread::THR_PRI_LOW);
dbCriticalSection cs(backupMutex);
while (true) {
time_t timeout = backupPeriod;
if (backupFileName[_tcslen(backupFileName)-1] != '?') {
#if defined(_WINCE) || defined(_WIN32)
WIN32_FIND_DATA lData;
HANDLE lFile = ::FindFirstFile(backupFileName, &lData);
FILETIME lATime;
if (::GetFileTime(lFile, 0l, &lATime, 0l) == TRUE)
{
ULARGE_INTEGER lNTime = *(ULARGE_INTEGER*)&lATime;
time_t howOld = time(NULL) - *(time_t*)&lNTime;
if (timeout < howOld) {
timeout = 0;
} else {
timeout -= howOld;
}
}
::FindClose(lFile);
#else
STATSTRUCT st;
if (::_tstat(backupFileName, &st) == 0) {
time_t howOld = time(NULL) - st.st_atime;
if (timeout < howOld) {
timeout = 0;
} else {
timeout -= howOld;
}
}
#endif
}
backupInitEvent.wait(backupMutex, timeout*1000);
if (backupFileName != NULL) {
if (backupFileName[_tcslen(backupFileName)-1] == _T('?')) {
time_t currTime = time(NULL);
char_t* fileName = new char_t[_tcslen(backupFileName) + 32];
struct tm* t = localtime(&currTime);
_stprintf(fileName, _T("%.*s-%04d.%02d.%02d_%02d.%02d.%02d"),
(int)_tcslen(backupFileName)-1, backupFileName,
t->tm_year + 1900, t->tm_mon+1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec);
backup(fileName, false);
delete[] fileName;
} else {
char_t* newFileName = new char_t[_tcslen(backupFileName) + 5];
_stprintf(newFileName,_T("%s.new"), backupFileName);
backup(newFileName, false);
#ifdef _WINCE
DeleteFile(backupFileName);
MoveFile(newFileName, backupFileName);
#else
::_tremove(backupFileName);
::_trename(newFileName, backupFileName);
#endif
delete[] newFileName;
}
} else {
return;
}
}
}
void dbDatabase::recovery()
{
int curr = header->curr;
header->size = (offs_t)file.getSize();
header->root[1-curr].indexUsed = header->root[curr].indexUsed;
header->root[1-curr].freeList = header->root[curr].freeList;
header->root[1-curr].index = header->root[curr].shadowIndex;
header->root[1-curr].indexSize =
header->root[curr].shadowIndexSize;
header->root[1-curr].shadowIndex = header->root[curr].index;
header->root[1-curr].shadowIndexSize =
header->root[curr].indexSize;
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
monitor->sessionFreeList[1-curr] = monitor->sessionFreeList[curr];
#endif
offs_t* dst = (offs_t*)(baseAddr+header->root[1-curr].index);
offs_t* src = (offs_t*)(baseAddr+header->root[curr].index);
currIndex = dst;
for (oid_t i = 0, n = header->root[curr].indexUsed; i < n; i++) {
if (dst[i] != src[i]) {
dst[i] = src[i];
file.markAsDirty(header->root[1-curr].index + i*sizeof(offs_t), sizeof(offs_t));
}
}
//
// Restore consistency of table rows l2-list
//
restoreTablesConsistency();
file.markAsDirty(0, sizeof(dbHeader));
}
void dbDatabase::restoreTablesConsistency()
{
dbTable* table = (dbTable*)getRow(dbMetaTableId);
oid_t lastId = table->lastRow;
if (lastId != 0) {
dbRecord* record = getRow(lastId);
if (record->next != 0) {
record->next = 0;
file.markAsDirty(currIndex[lastId], sizeof(dbRecord));
}
}
oid_t tableId = table->firstRow;
while (tableId != 0) {
table = (dbTable*)getRow(tableId);
lastId = table->lastRow;
if (lastId != 0) {
dbRecord* record = getRow(lastId);
if (record->next != 0) {
record->next = 0;
file.markAsDirty(currIndex[lastId], sizeof(dbRecord));
}
}
tableId = table->next;
}
}
void dbDatabase::setConcurrency(unsigned nThreads)
{
if (nThreads == 0) { // autodetect number of processors
nThreads = dbThread::numberOfProcessors();
}
if (nThreads > dbMaxParallelSearchThreads) {
nThreads = dbMaxParallelSearchThreads;
}
parThreads = nThreads;
}
bool dbDatabase::loadScheme(bool alter)
{
if (!beginTransaction((alter && accessType != dbReadOnly && accessType != dbConcurrentRead)
|| accessType == dbConcurrentUpdate
? dbExclusiveLock : dbSharedLock))
{
return false;
}
dbTable* metaTable = (dbTable*)getRow(dbMetaTableId);
oid_t first = metaTable->firstRow;
oid_t last = metaTable->lastRow;
int nTables = metaTable->nRows;
oid_t tableId = first;
if (dbTableDescriptor::chain != NULL) {
dbTableDescriptor *desc, *next;
dbCriticalSection cs(dbTableDescriptor::getChainMutex());
for (desc = dbTableDescriptor::chain; desc != NULL; desc = next) {
next = desc->next;
if (desc->db != NULL && desc->db != DETACHED_TABLE && desc->db != this) {
continue;
}
if (desc->db == DETACHED_TABLE) {
desc = desc->clone();
}
dbFieldDescriptor* fd;
for (fd = desc->firstField; fd != NULL; fd = fd->nextField) {
fd->tTree = 0;
fd->hashTable = 0;
fd->attr &= ~dbFieldDescriptor::Updated;
}
int n = nTables;
while (--n >= 0) {
dbTable* table = (dbTable*)getRow(tableId);
if (table == NULL) {
handleError(DatabaseOpenError, "Database scheme is corrupted");
return false;
}
oid_t next = table->next;
if (strcmp(desc->name, (char*)table + table->name.offs) == 0) {
if (!desc->equal(table)) {
if (!alter) {
handleError(DatabaseOpenError, "Incompatible class"
" definition in application");
return false;
}
beginTransaction(dbExclusiveLock);
modified = true;
if (table->nRows == 0) {
TRACE_MSG(("Replace definition of table '%s'\n", desc->name));
desc->match(table, true, true);
updateTableDescriptor(desc, tableId);
} else {
reformatTable(tableId, desc);
}
} else {
linkTable(desc, tableId);
}
desc->setFlags();
break;
}
if (tableId == last) {
tableId = first;
} else {
tableId = next;
}
}
if (n < 0) { // no match found
if (accessType == dbReadOnly || accessType == dbConcurrentRead) {
TRACE_IMSG(("Table '%s' can not be added to the read-only database\n", desc->name));
handleError(DatabaseOpenError, "New table definition can not "
"be added to read only database");
return false;
} else {
TRACE_MSG(("Create new table '%s' in database\n", desc->name));
addNewTable(desc);
modified = true;
}
}
if (accessType != dbReadOnly && accessType != dbConcurrentRead) {
if (!addIndices(alter, desc)) {
handleError(DatabaseOpenError, "Failed to alter indices with"
" active applications");
rollback();
return false;
}
}
}
for (desc = tables; desc != NULL; desc = desc->nextDbTable) {
if (desc->cloneOf != NULL) {
for (dbFieldDescriptor *fd = desc->firstField; fd != NULL; fd = fd->nextField)
{
if (fd->refTable != NULL) {
fd->refTable = lookupTable(fd->refTable);
}
}
}
desc->checkRelationship();
}
}
commit();
return true;
}
void dbDatabase::reformatTable(oid_t tableId, dbTableDescriptor* desc)
{
dbTable* table = (dbTable*)putRow(tableId);
if (desc->match(table, confirmDeleteColumns, false)) {
TRACE_MSG(("New version of table '%s' is compatible with old one\n",
desc->name));
updateTableDescriptor(desc, tableId);
} else {
TRACE_MSG(("Reformat table '%s'\n", desc->name));
oid_t oid = table->firstRow;
updateTableDescriptor(desc, tableId);
while (oid != 0) {
dbRecord* record = getRow(oid);
size_t size =
desc->columns->calculateNewRecordSize((byte*)record,
desc->fixedSize);
offs_t offs = currIndex[oid];
record = putRow(oid, size);
byte* dst = (byte*)record;
byte* src = baseAddr + offs;
if (dst == src) {
dbSmallBuffer buf(size);
dst = (byte*)buf.base();
desc->columns->convertRecord(dst, src, desc->fixedSize);
memcpy(record+1, dst+sizeof(dbRecord), size-sizeof(dbRecord));
} else {
desc->columns->convertRecord(dst, src, desc->fixedSize);
}
oid = record->next;
}
}
}
void dbDatabase::deleteTable(dbTableDescriptor* desc)
{
beginTransaction(dbExclusiveLock);
modified = true;
dbTable* table = (dbTable*)putRow(desc->tableId);
oid_t rowId = table->firstRow;
table->firstRow = table->lastRow = 0;
table->nRows = 0;
while (rowId != 0) {
dbRecord* record = getRow(rowId);
oid_t nextId = record->next;
size_t size = record->size;
removeInverseReferences(desc, rowId);
if (rowId < committedIndexSize && index[0][rowId] == index[1][rowId]) {
cloneBitmap(currIndex[rowId], size);
} else {
deallocate(currIndex[rowId], size);
}
freeId(rowId);
rowId = nextId;
}
dbFieldDescriptor* fd;
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField) {
dbHashTable::purge(this, fd->hashTable);
}
for (fd = desc->indexedFields; fd != NULL; fd = fd->nextIndexedField) {
if (fd->type == dbField::tpRectangle) {
dbRtree::purge(this, fd->tTree);
} else {
dbTtree::purge(this, fd->tTree);
}
}
}
void dbDatabase::dropHashTable(dbFieldDescriptor* fd)
{
beginTransaction(dbExclusiveLock);
modified = true;
dbHashTable::drop(this, fd->hashTable);
fd->hashTable = 0;
fd->indexType &= ~HASHED;
dbFieldDescriptor** fpp = &fd->defTable->hashedFields;
while (*fpp != fd) {
fpp = &(*fpp)->nextHashedField;
}
*fpp = fd->nextHashedField;
dbTable* table = (dbTable*)putRow(fd->defTable->tableId);
dbField* field = (dbField*)((char*)table + table->fields.offs);
field[fd->fieldNo].hashTable = 0;
}
void dbDatabase::dropIndex(dbFieldDescriptor* fd)
{
beginTransaction(dbExclusiveLock);
modified = true;
if (fd->type == dbField::tpRectangle) {
dbRtree::drop(this, fd->tTree);
} else {
dbTtree::drop(this, fd->tTree);
}
fd->tTree = 0;
fd->indexType &= ~INDEXED;
dbFieldDescriptor** fpp = &fd->defTable->indexedFields;
while (*fpp != fd) {
fpp = &(*fpp)->nextIndexedField;
}
*fpp = fd->nextIndexedField;
dbTable* table = (dbTable*)putRow(fd->defTable->tableId);
dbField* field = (dbField*)((char*)table + table->fields.offs);
field[fd->fieldNo].tTree = 0;
}
void dbDatabase::createHashTable(dbFieldDescriptor* fd)
{
beginTransaction(dbExclusiveLock);
modified = true;
dbTable* table = (dbTable*)getRow(fd->defTable->tableId);
size_t nRows = table->nRows;
fd->hashTable = dbHashTable::allocate(this, 2*nRows);
fd->attr &= ~dbFieldDescriptor::Updated;
fd->nextHashedField = fd->defTable->hashedFields;
fd->defTable->hashedFields = fd;
fd->indexType |= HASHED;
table = (dbTable*)putRow(fd->defTable->tableId);
dbField* field = (dbField*)((char*)table + table->fields.offs);
field[fd->fieldNo].hashTable = fd->hashTable;
for (oid_t oid = table->firstRow; oid != 0; oid = getRow(oid)->next) {
dbHashTable::insert(this, fd, oid, nRows);
}
}
void dbDatabase::createIndex(dbFieldDescriptor* fd)
{
beginTransaction(dbExclusiveLock);
modified = true;
if (fd->type == dbField::tpRectangle) {
fd->tTree = dbRtree::allocate(this);
} else {
fd->tTree = dbTtree::allocate(this);
}
fd->attr &= ~dbFieldDescriptor::Updated;
fd->nextIndexedField = fd->defTable->indexedFields;
fd->defTable->indexedFields = fd;
fd->indexType |= INDEXED;
dbTable* table = (dbTable*)putRow(fd->defTable->tableId);
dbField* field = (dbField*)((char*)table + table->fields.offs);
field[fd->fieldNo].tTree = fd->tTree;
for (oid_t oid = table->firstRow; oid != 0; oid = getRow(oid)->next) {
if (fd->type == dbField::tpRectangle) {
dbRtree::insert(this, fd->tTree, oid, fd->dbsOffs);
} else {
dbTtree::insert(this, fd->tTree, oid, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
}
void dbDatabase::dropTable(dbTableDescriptor* desc)
{
deleteTable(desc);
freeRow(dbMetaTableId, desc->tableId);
dbFieldDescriptor* fd;
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField) {
dbHashTable::drop(this, fd->hashTable);
}
for (fd = desc->indexedFields; fd != NULL; fd = fd->nextIndexedField) {
if (fd->type == dbField::tpRectangle) {
dbRtree::drop(this, fd->tTree);
} else {
dbTtree::drop(this, fd->tTree);
}
}
}
#define NEW_INDEX 0x80000000u
bool dbDatabase::addIndices(bool alter, dbTableDescriptor* desc)
{
dbFieldDescriptor* fd;
oid_t tableId = desc->tableId;
dbTable* table = (dbTable*)getRow(tableId);
int nRows = table->nRows;
oid_t firstId = table->firstRow;
int nNewIndices = 0;
int nDelIndices = 0;
for (fd = desc->firstField; fd != NULL; fd = fd->nextField) {
if ((fd->indexType & HASHED) && fd->type != dbField::tpStructure) {
if (fd->hashTable == 0) {
if (!alter && tableId < committedIndexSize
&& index[0][tableId] == index[1][tableId])
{
// If there are some other active applications which
// can use this table, then they will not know
// about newly created index, which leads to inconsistency
return false;
}
fd->indexType |= NEW_INDEX;
fd->hashTable = dbHashTable::allocate(this, nRows);
nNewIndices += 1;
TRACE_MSG(("Create hash table for field '%s'\n", fd->name));
}
} else if (fd->hashTable != 0) {
if (alter) {
TRACE_MSG(("Remove hash table for field '%s'\n", fd->name));
nDelIndices += 1;
fd->hashTable = 0;
} else {
return false;
}
}
if ((fd->indexType & INDEXED) && fd->type != dbField::tpStructure) {
if (fd->tTree == 0) {
if (!alter && tableId < committedIndexSize
&& index[0][tableId] == index[1][tableId])
{
return false;
}
fd->indexType |= NEW_INDEX;
fd->tTree = (fd->type == dbField::tpRectangle) ? dbRtree::allocate(this) : dbTtree::allocate(this);
nNewIndices += 1;
TRACE_MSG(("Create index for field '%s'\n", fd->name));
}
} else if (fd->tTree != 0) {
if (alter) {
nDelIndices += 1;
TRACE_MSG(("Remove index for field '%s'\n", fd->name));
fd->tTree = 0;
} else {
return false;
}
}
}
if (nNewIndices > 0) {
modified = true;
for (oid_t rowId = firstId; rowId != 0; rowId = getRow(rowId)->next) {
for (fd = desc->hashedFields; fd != NULL; fd=fd->nextHashedField) {
if (fd->indexType & NEW_INDEX) {
dbHashTable::insert(this, fd, rowId, 2*nRows);
}
}
for (fd=desc->indexedFields; fd != NULL; fd=fd->nextIndexedField) {
if (fd->indexType & NEW_INDEX) {
if (fd->type == dbField::tpRectangle) {
dbRtree::insert(this, fd->tTree, rowId, fd->dbsOffs);
} else {
dbTtree::insert(this, fd->tTree, rowId,
fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
}
}
for (fd = desc->firstField; fd != NULL; fd = fd->nextField) {
fd->indexType &= ~NEW_INDEX;
}
}
if (nNewIndices + nDelIndices != 0) {
table = (dbTable*)putRow(tableId);
offs_t fieldOffs = currIndex[tableId] + table->fields.offs;
for (fd = desc->firstField; fd != NULL; fd = fd->nextField) {
dbField* field = (dbField*)(baseAddr + fieldOffs);
if (field->hashTable != fd->hashTable) {
if (field->hashTable != 0) {
FASTDB_ASSERT(fd->hashTable == 0);
modified = true;
dbHashTable::drop(this, field->hashTable);
field = (dbField*)(baseAddr + fieldOffs);
}
field->hashTable = fd->hashTable;
}
if (field->tTree != fd->tTree) {
if (field->tTree != 0) {
FASTDB_ASSERT(fd->tTree == 0);
modified = true;
if (field->type == dbField::tpRectangle) {
dbRtree::drop(this, field->tTree);
} else {
dbTtree::drop(this, field->tTree);
}
field = (dbField*)(baseAddr + fieldOffs);
}
field->tTree = fd->tTree;
}
fieldOffs += sizeof(dbField);
}
}
return true;
}
void dbDatabase::updateTableDescriptor(dbTableDescriptor* desc, oid_t tableId)
{
size_t newSize = sizeof(dbTable) + desc->nFields*sizeof(dbField)
+ desc->totalNamesLength();
linkTable(desc, tableId);
dbTable* table = (dbTable*)getRow(tableId);
int nRows = table->nRows;
oid_t first = table->firstRow;
oid_t last = table->lastRow;
#ifdef AUTOINCREMENT_SUPPORT
desc->autoincrementCount = table->count;
#endif
int nFields = table->fields.size;
offs_t fieldOffs = currIndex[tableId] + table->fields.offs;
while (--nFields >= 0) {
dbField* field = (dbField*)(baseAddr + fieldOffs);
fieldOffs += sizeof(dbField);
oid_t hashTableId = field->hashTable;
oid_t tTreeId = field->tTree;
int fieldType = field->type;
if (hashTableId != 0) {
dbHashTable::drop(this, hashTableId);
}
if (tTreeId != 0) {
if (fieldType == dbField::tpRectangle) {
dbRtree::drop(this, tTreeId);
} else {
dbTtree::drop(this, tTreeId);
}
}
}
table = (dbTable*)putRow(tableId, newSize);
desc->storeInDatabase(table);
table->firstRow = first;
table->lastRow = last;
table->nRows = nRows;
}
oid_t dbDatabase::addNewTable(dbTableDescriptor* desc)
{
oid_t tableId = allocateRow(dbMetaTableId,
sizeof(dbTable) + desc->nFields*sizeof(dbField)
+ desc->totalNamesLength());
linkTable(desc, tableId);
desc->storeInDatabase((dbTable*)getRow(tableId));
return tableId;
}
void dbDatabase::close()
{
if (opened) {
close0();
}
}
void dbDatabase::close0()
{
detach();
if (backupFileName != NULL) {
{
dbCriticalSection cs(backupMutex);
delete[] backupFileName;
backupFileName = NULL;
backupInitEvent.signal();
}
backupThread.join();
}
if (commitDelay != 0) {
delayedCommitStopTimerEvent.signal();
{
dbCriticalSection cs(delayedCommitStartTimerMutex);
stopDelayedCommitThread = true;
delayedCommitStartTimerEvent.signal();
}
commitDelay = 0;
commitThread.join();
delayedCommitStartTimerEvent.close();
commitThreadSyncEvent.close();
}
{
dbCriticalSection cs(threadContextListMutex);
while (!threadContextList.isEmpty()) {
delete (dbDatabaseThreadContext*)threadContextList.next;
}
}
backupInitEvent.close();
#ifdef AUTO_DETECT_PROCESS_CRASH
watchDogMutex->lock();
#endif
if (accessType == dbConcurrentUpdate) {
mutatorCS.enter();
}
cs.enter();
#ifdef AUTO_DETECT_PROCESS_CRASH
dbL2List* wdc = &watchDogThreadContexts;
while ((wdc = wdc->next) != &watchDogThreadContexts) {
((dbWatchDogContext*)wdc)->db = NULL;
}
if (watchDogThreadContexts.isEmpty()) {
watchDogMutex->unlock();
delete watchDogMutex;
} else {
watchDogThreadContexts.unlink();
watchDogMutex->unlock();
}
selfWatchDog.close();
#endif
delete[] databaseName;
delete[] fileName;
databaseName = NULL;
fileName = NULL;
opened = false;
monitor->users -= 1;
if (header != NULL && header->dirty && accessType != dbReadOnly && accessType != dbConcurrentRead && monitor->nWriters == 0)
{
file.flush(true);
header->dirty = false;
file.markAsDirty(0, sizeof(dbHeader));
}
cs.leave();
if (accessType == dbConcurrentUpdate) {
mutatorCS.leave();
}
dbTableDescriptor *desc, *next;
for (desc = tables; desc != NULL; desc = next) {
next = desc->nextDbTable;
desc->tableId = 0;
if (!desc->isStatic) {
delete desc;
} else if (!desc->fixedDatabase) {
desc->db = NULL;
}
}
file.close();
if (initMutex.close()) {
cs.erase();
readSem.erase();
writeSem.erase();
upgradeSem.erase();
backupCompletedEvent.erase();
file.erase();
if (commitDelay != 0) {
delayedCommitStopTimerEvent.erase();
}
if (accessType == dbConcurrentUpdate || accessType == dbConcurrentRead) {
mutatorCS.erase();
}
shm.erase();
initMutex.erase();
} else {
cs.close();
shm.close();
readSem.close();
writeSem.close();
upgradeSem.close();
backupCompletedEvent.close();
if (commitDelay != 0) {
delayedCommitStopTimerEvent.close();
}
if (accessType == dbConcurrentUpdate || accessType == dbConcurrentRead) {
mutatorCS.close();
}
}
}
dbTableDescriptor* dbDatabase::lookupTable(dbTableDescriptor* origDesc)
{
for (dbTableDescriptor* desc = tables; desc != NULL; desc = desc->nextDbTable)
{
if (desc == origDesc || desc->cloneOf == origDesc) {
return desc;
}
}
return NULL;
}
void dbDatabase::attach()
{
if (threadContext.get() == NULL) {
dbDatabaseThreadContext* ctx = new dbDatabaseThreadContext();
{
dbCriticalSection cs(threadContextListMutex);
threadContextList.link(ctx);
}
threadContext.set(ctx);
}
}
void dbDatabase::attach(dbDatabaseThreadContext* ctx)
{
threadContext.set(ctx);
}
void dbDatabase::detach(int flags)
{
if (flags & COMMIT) {
commit();
} else {
monitor->uncommittedChanges = true;
precommit();
}
if (flags & DESTROY_CONTEXT) {
dbDatabaseThreadContext* ctx = threadContext.get();
if (commitDelay != 0) {
dbCriticalSection cs(delayedCommitStopTimerMutex);
if (monitor->delayedCommitContext == ctx && ctx->commitDelayed) {
ctx->removeContext = true;
} else {
dbCriticalSection cs(threadContextListMutex);
delete ctx;
}
} else {
dbCriticalSection cs(threadContextListMutex);
delete ctx;
}
threadContext.set(NULL);
}
}
bool dbDatabase::existsInverseReference(dbExprNode* expr, int nExistsClauses)
{
while (true) {
switch (expr->cop) {
case dbvmLoadSelfReference:
case dbvmLoadSelfArray:
return expr->ref.field->inverseRef != NULL;
case dbvmLoadReference:
if (expr->ref.field->attr & dbFieldDescriptor::ComponentOfArray) {
expr = expr->ref.base;
continue;
}
// no break
case dbvmLoadArray:
if (expr->ref.field->inverseRef == NULL) {
return false;
}
expr = expr->ref.base;
continue;
case dbvmGetAt:
if (expr->operand[1]->cop != dbvmVariable
|| expr->operand[1]->offs != --nExistsClauses)
{
return false;
}
expr = expr->operand[0];
continue;
case dbvmDeref:
expr = expr->operand[0];
continue;
default:
return false;
}
}
}
bool dbDatabase::followInverseReference(dbExprNode* expr, dbExprNode* andExpr,
dbAnyCursor* cursor, oid_t iref)
{
while (expr->cop == dbvmGetAt || expr->cop == dbvmDeref ||
(expr->cop == dbvmLoadReference
&& (expr->ref.field->attr & dbFieldDescriptor::ComponentOfArray)))
{
expr = expr->operand[0];
}
dbTable* table = (dbTable*)getRow(cursor->table->tableId);
dbFieldDescriptor* fd = expr->ref.field->inverseRef;
if (fd->type == dbField::tpArray) {
byte* rec = (byte*)getRow(iref);
dbVarying* arr = (dbVarying*)(rec + fd->dbsOffs);
oid_t* refs = (oid_t*)(rec + arr->offs);
if (expr->cop >= dbvmLoadSelfReference) {
for (int n = arr->size; --n >= 0;) {
oid_t oid = *refs++;
if (oid != 0) {
if (andExpr == NULL || evaluate(andExpr, oid, table, cursor)) {
if (!cursor->add(oid)) {
return false;
}
}
}
}
} else {
for (int n = arr->size; --n >= 0;) {
oid_t oid = *refs++;
if (oid != 0) {
if (!followInverseReference(expr->ref.base, andExpr,
cursor, oid))
{
return false;
}
}
}
}
} else {
FASTDB_ASSERT(fd->type == dbField::tpReference);
oid_t oid = *(oid_t*)((byte*)getRow(iref) + fd->dbsOffs);
if (oid != 0) {
if (expr->cop >= dbvmLoadSelfReference) {
if (andExpr == NULL || evaluate(andExpr, oid, table, cursor)) {
if (!cursor->add(oid)) {
return false;
}
}
} else {
if (!followInverseReference(expr->ref.base, andExpr,
cursor, oid))
{
return false;
}
}
}
}
return true;
}
bool dbDatabase::isPrefixSearch(dbAnyCursor* cursor,
dbExprNode* expr,
dbExprNode* andExpr,
dbFieldDescriptor* &indexedField)
{
if (expr->cop == dbvmLikeString
&& expr->operand[1]->cop == dbvmStringConcat
&& expr->operand[1]->operand[0]->cop == dbvmLoadSelfString
&& expr->operand[1]->operand[0]->ref.field->tTree != 0
&& expr->operand[1]->operand[1]->cop == dbvmLoadStringConstant
&& strcmp(expr->operand[1]->operand[1]->svalue.str, "%") == 0)
{
size_t paramBase = (size_t)cursor->paramBase;
char* sval;
dbExprNode* opd = expr->operand[0];
switch (opd->cop) {
case dbvmLoadStringConstant:
sval = (char*)opd->svalue.str;
break;
case dbvmLoadVarString:
sval = (char*)((char*)opd->var + paramBase);
break;
#ifdef USE_STD_STRING
case dbvmLoadVarStdString:
sval = (char*)((std::string*)((char*)opd->var + paramBase))->c_str();
break;
#endif
case dbvmLoadVarStringPtr:
sval = *(char**)((char*)opd->var + paramBase);
break;
default:
return false;
}
dbFieldDescriptor* field = expr->operand[1]->operand[0]->ref.field;
dbSearchContext sc;
sc.db = this;
sc.type = dbField::tpString;
sc.offs = field->dbsOffs;
sc.field = field;
sc.cursor = cursor;
sc.prefixLength = 0;
sc.condition = andExpr ? andExpr->operand[1] : (dbExprNode*)0;
sc.probes = 0;
sc.firstKey = sc.lastKey = sval;
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
dbTtree::prefixSearch(this, field->tTree, sc);
TRACE_MSG(("Index prefix search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
indexedField = field;
return true;
} else if (expr->cop == dbvmLikeWString
&& expr->operand[1]->cop == dbvmWStringConcat
&& expr->operand[1]->operand[0]->cop == dbvmLoadSelfWString
&& expr->operand[1]->operand[0]->ref.field->tTree != 0
&& expr->operand[1]->operand[1]->cop == dbvmLoadWStringConstant
&& wcscmp(expr->operand[1]->operand[1]->wsvalue.str, L"%") == 0)
{
size_t paramBase = (size_t)cursor->paramBase;
wchar_t* sval;
dbExprNode* opd = expr->operand[0];
switch (opd->cop) {
case dbvmLoadWStringConstant:
sval = (wchar_t*)opd->wsvalue.str;
break;
case dbvmLoadVarWString:
sval = (wchar_t*)((char*)opd->var + paramBase);
break;
#ifdef USE_STD_STRING
case dbvmLoadVarStdWString:
sval = (wchar_t*)((std::wstring*)((char*)opd->var + paramBase))->c_str();
break;
#endif
case dbvmLoadVarWStringPtr:
sval = *(wchar_t**)((char*)opd->var + paramBase);
break;
default:
return false;
}
dbFieldDescriptor* field = expr->operand[1]->operand[0]->ref.field;
dbSearchContext sc;
sc.db = this;
sc.type = dbField::tpWString;
sc.offs = field->dbsOffs;
sc.field = field;
sc.cursor = cursor;
sc.prefixLength = 0;
sc.condition = andExpr ? andExpr->operand[1] : (dbExprNode*)0;
sc.probes = 0;
sc.firstKey = sc.lastKey = (char*)sval;
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
dbTtree::prefixSearch(this, field->tTree, sc);
TRACE_MSG(("Index prefix search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
indexedField = field;
return true;
}
return false;
}
bool dbDatabase::existsIndexedReference(dbExprNode* ref)
{
while (ref->cop == dbvmDeref) {
ref = ref->operand[0];
if ((ref->cop != dbvmLoadSelfReference && ref->cop != dbvmLoadReference)
|| (ref->ref.field->hashTable == 0 && ref->ref.field->tTree == 0))
{
return false;
}
if (ref->cop == dbvmLoadSelfReference) {
return true;
}
ref = ref->operand[0];
}
return false;
}
bool dbDatabase::isIndexApplicable(dbAnyCursor* cursor,
dbExprNode* expr, dbExprNode* andExpr,
dbFieldDescriptor* &indexedField)
{
int nExistsClauses = 0;
while (expr->cop == dbvmExists) {
expr = expr->operand[0];
nExistsClauses += 1;
}
int cmpCop = expr->cop;
if (dbExprNode::nodeOperands[cmpCop] < 2 && cmpCop != dbvmIsNull) {
return false;
}
if (isPrefixSearch(cursor, expr, andExpr, indexedField)) {
return true;
}
unsigned loadCop = expr->operand[0]->cop;
if (loadCop - dbvmLoadSelfBool > dbvmLoadSelfRawBinary - dbvmLoadSelfBool
&& loadCop - dbvmLoadBool > dbvmLoadRawBinary - dbvmLoadBool)
{
return false;
}
dbFieldDescriptor* field = expr->operand[0]->ref.field;
if (field->hashTable == 0 && field->tTree == 0) {
return false;
}
if (loadCop >= dbvmLoadSelfBool) {
if (isIndexApplicable(cursor, expr, andExpr)) {
indexedField = field;
return true;
}
}
else if (existsInverseReference(expr->operand[0]->ref.base, nExistsClauses))
{
dbAnyCursor tmpCursor(*field->defTable, dbCursorViewOnly, NULL);
tmpCursor.paramBase = cursor->paramBase;
if (isIndexApplicable(&tmpCursor, expr, NULL)) {
expr = expr->operand[0]->ref.base;
indexedField = field;
cursor->checkForDuplicates();
if (andExpr != NULL) {
andExpr = andExpr->operand[1];
}
for (dbSelection::segment* curr = tmpCursor.selection.first;
curr != NULL;
curr = curr->next)
{
for (int i = 0, n = (int)curr->nRows; i < n; i++) {
if (!followInverseReference(expr, andExpr,
cursor, curr->rows[i]))
{
return true;
}
}
}
return true;
}
} else if (existsIndexedReference(expr->operand[0]->ref.base)) {
dbExprNode* ref = expr->operand[0]->ref.base->operand[0];
dbFieldDescriptor* refField = ref->ref.field;
FASTDB_ASSERT(refField->type == dbField::tpReference);
dbAnyCursor tmpCursor[2];
int currRefCursor = 0;
tmpCursor[0].setTable(refField->refTable);
tmpCursor[0].paramBase = cursor->paramBase;
if (isIndexApplicable(&tmpCursor[0], expr, NULL)) {
oid_t oid;
dbSearchContext sc;
indexedField = field;
sc.db = this;
sc.type = dbField::tpReference;
sc.prefixLength = 0;
sc.field = refField;
sc.condition = andExpr ? andExpr->operand[1] : (dbExprNode*)0;
sc.firstKey = sc.lastKey = (char*)&oid;
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
dbAnyCursor *srcCursor, *dstCursor;
srcCursor = &tmpCursor[0];
while (true) {
sc.offs = refField->dbsOffs;
if (ref->cop == dbvmLoadSelfReference) {
dstCursor = cursor;
sc.condition = andExpr;
} else {
dstCursor = &tmpCursor[currRefCursor ^= 1];
dstCursor->setTable(refField->defTable);
dstCursor->reset();
}
sc.cursor = dstCursor;
for (dbSelection::segment* curr = srcCursor->selection.first;
curr != NULL;
curr = curr->next)
{
for (int i = 0, n = (int)curr->nRows; i < n; i++) {
oid = curr->rows[i];
sc.probes = 0;
if (refField->hashTable != 0) {
dbHashTable::find(this, refField->hashTable, sc);
TRACE_MSG(("Hash table search for field %s.%s: %d probes\n",
refField->defTable->name, refField->longName, sc.probes));
} else {
dbTtree::find(this, refField->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
refField->defTable->name, refField->longName, sc.probes));
}
}
}
if (ref->cop == dbvmLoadSelfReference) {
break;
}
srcCursor = dstCursor;
ref = ref->operand[0]->operand[0];
refField = ref->ref.field;
FASTDB_ASSERT(refField->type == dbField::tpReference);
}
return true;
}
}
return false;
}
bool dbDatabase::isIndexApplicable(dbAnyCursor* cursor,
dbExprNode* expr, dbExprNode* andExpr)
{
int n = dbExprNode::nodeOperands[expr->cop];
dbFieldDescriptor* field = expr->operand[0]->ref.field;
dbSearchContext sc;
size_t paramBase = (size_t)cursor->paramBase;
union {
bool b;
int1 i1;
int2 i2;
int4 i4;
db_int8 i8;
real4 f4;
real8 f8;
oid_t oid;
char* s;
wchar_t* ws;
rectangle* r;
dbAnyArray* a;
} literal[2];
bool strop = false;
bool binop = false;
char* s;
wchar_t* ws;
literal[0].i8 = 0;
literal[1].i8 = 0;
for (int i = 0; i < n-1; i++) {
bool bval = false;
db_int8 ival = 0;
real8 fval = 0;
oid_t oid = 0;
char* sval = NULL;
wchar_t* wsval = NULL;
rectangle* rect = NULL;
dbExprNode* opd = expr->operand[i+1];
switch (opd->cop) {
case dbvmLoadVarArrayOfOid:
case dbvmLoadVarArrayOfInt4:
case dbvmLoadVarArrayOfInt8:
literal[i].a = (dbAnyArray*)((char*)opd->var + paramBase);
strop = true;
continue;
case dbvmLoadVarArrayOfOidPtr:
case dbvmLoadVarArrayOfInt4Ptr:
case dbvmLoadVarArrayOfInt8Ptr:
literal[i].a = *(dbAnyArray**)((char*)opd->var + paramBase);
strop = true;
continue;
case dbvmLoadVarBool:
bval = *(bool*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarInt1:
ival = *(int1*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarInt2:
ival = *(int2*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarInt4:
ival = *(int4*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarInt8:
ival = *(db_int8*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarReference:
oid = *(oid_t*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarRectangle:
rect = (rectangle*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarRectanglePtr:
rect = *(rectangle**)((char*)opd->var + paramBase);
break;
case dbvmLoadNull:
oid = 0;
break;
case dbvmLoadVarReal4:
fval = *(real4*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarReal8:
fval = *(real8*)((char*)opd->var + paramBase);
break;
case dbvmLoadVarString:
sval = (char*)opd->var + paramBase;
strop = true;
break;
#ifdef USE_STD_STRING
case dbvmLoadVarStdString:
sval = (char*)((std::string*)((char*)opd->var + paramBase))->c_str();
strop = true;
break;
#endif
case dbvmLoadVarStringPtr:
sval = *(char**)((char*)opd->var + paramBase);
strop = true;
break;
case dbvmLoadVarWString:
wsval = (wchar_t*)((char*)opd->var + paramBase);
strop = true;
break;
#ifdef USE_STD_STRING
case dbvmLoadVarStdWString:
wsval = (wchar_t*)((std::wstring*)((char*)opd->var + paramBase))->c_str();
strop = true;
break;
#endif
case dbvmLoadVarWStringPtr:
wsval = *(wchar_t**)((char*)opd->var + paramBase);
strop = true;
break;
case dbvmLoadTrue:
bval = true;
break;
case dbvmLoadFalse:
bval = false;
break;
case dbvmLoadIntConstant:
ival = opd->ivalue;
break;
case dbvmLoadRealConstant:
fval = opd->fvalue;
break;
case dbvmLoadStringConstant:
sval = (char*)opd->svalue.str;
strop = true;
break;
case dbvmLoadWStringConstant:
wsval = opd->wsvalue.str;
strop = true;
break;
case dbvmLoadVarRawBinary:
sval = (char*)((char*)opd->var + paramBase);
strop = true;
binop = true;
break;
case dbvmLoadVarRawBinaryPtr:
sval = *(char**)((char*)opd->var + paramBase);
strop = true;
binop = true;
break;
default:
return false;
}
switch (field->type) {
case dbField::tpBool:
literal[i].b = bval;
break;
case dbField::tpInt1:
literal[i].i1 = (int1)ival;
break;
case dbField::tpInt2:
literal[i].i2 = (int2)ival;
break;
case dbField::tpInt4:
literal[i].i4 = (int4)ival;
break;
case dbField::tpInt8:
literal[i].i8 = ival;
break;
case dbField::tpReference:
literal[i].oid = oid;
break;
case dbField::tpRectangle:
literal[i].r = rect;
break;
case dbField::tpReal4:
literal[i].f4 = (real4)fval;
break;
case dbField::tpReal8:
literal[i].f8 = fval;
break;
case dbField::tpString:
literal[i].s = sval;
break;
case dbField::tpWString:
literal[i].ws = wsval;
break;
case dbField::tpRawBinary:
literal[i].s = sval;
break;
default:
FASTDB_ASSERT(false);
}
}
sc.db = this;
sc.type = field->type;
sc.offs = field->dbsOffs;
sc.field = field;
sc.cursor = cursor;
sc.prefixLength = 0;
sc.condition = andExpr ? andExpr->operand[1] : (dbExprNode*)0;
sc.probes = 0;
switch (expr->cop) {
case dbvmInArrayInt4:
if (field->type == dbField::tpInt4) {
dbAnyArray* arr = literal[0].a;
db_int4* items = (db_int4*)arr->base();
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
cursor->checkForDuplicates();
if (field->hashTable != 0) {
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = sc.lastKey = (char*)items;
dbHashTable::find(this, field->hashTable, sc);
}
} else {
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = sc.lastKey = (char*)items;
dbTtree::find(this, field->tTree, sc);
}
}
return true;
}
return false;
case dbvmInArrayInt8:
if (field->type == dbField::tpInt8) {
dbAnyArray* arr = literal[0].a;
db_int8* items = (db_int8*)arr->base();
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
cursor->checkForDuplicates();
if (field->hashTable != 0) {
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = sc.lastKey = (char*)items;
dbHashTable::find(this, field->hashTable, sc);
}
} else {
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = sc.lastKey = (char*)items;
dbTtree::find(this, field->tTree, sc);
}
}
return true;
}
return false;
case dbvmInArrayReference:
if (field->type == dbField::tpReference) {
dbAnyArray* arr = literal[0].a;
oid_t* items = (oid_t*)arr->base();
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
cursor->checkForDuplicates();
if (field->hashTable != 0) {
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = sc.lastKey = (char*)items;
dbHashTable::find(this, field->hashTable, sc);
}
} else {
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = sc.lastKey = (char*)items;
dbTtree::find(this, field->tTree, sc);
}
}
return true;
}
return false;
case dbvmInArrayRectangle:
if (field->type == dbField::tpRectangle) {
dbAnyArray* arr = literal[0].a;
rectangle* items = (rectangle*)arr->base();
sc.firstKeyInclusion = dbRtree::SUBSET;
cursor->checkForDuplicates();
for (int n = (int)arr->length(); --n >= 0; items++) {
sc.firstKey = (char*)items;
dbRtree::find(this, field->tTree, sc);
}
return true;
}
return false;
case dbvmEqRectangle:
case dbvmLtRectangle:
case dbvmLeRectangle:
case dbvmGtRectangle:
case dbvmGeRectangle:
sc.firstKey = (char*)literal[0].r;
sc.firstKeyInclusion = dbRtree::EQUAL + expr->cop - dbvmEqRectangle;
dbRtree::find(this, field->tTree, sc);
TRACE_MSG(("Spatial index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
case dbvmOverlapsRectangle:
sc.firstKey = (char*)literal[0].r;
sc.firstKeyInclusion = dbRtree::OVERLAPS;
dbRtree::find(this, field->tTree, sc);
TRACE_MSG(("Spatial index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
case dbvmIsNull:
case dbvmEqReference:
case dbvmEqInt:
case dbvmEqBool:
case dbvmEqReal:
case dbvmEqArray:
case dbvmEqString:
case dbvmEqWString:
case dbvmEqBinary:
sc.firstKey = sc.lastKey =
strop ? literal[0].s : (char*)&literal[0];
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
if (field->hashTable != 0) {
dbHashTable::find(this, field->hashTable, sc);
TRACE_MSG(("Hash table search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
} else {
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
}
return true;
case dbvmGtInt:
case dbvmGtReal:
case dbvmGtString:
case dbvmGtWString:
case dbvmGtBinary:
case dbvmGtArray:
if (field->tTree != 0) {
sc.firstKey = strop ? literal[0].s : (char*)&literal[0];
sc.lastKey = NULL;
sc.firstKeyInclusion = false;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
}
return false;
case dbvmGeInt:
case dbvmGeReal:
case dbvmGeString:
case dbvmGeWString:
case dbvmGeBinary:
case dbvmGeArray:
if (field->tTree != 0) {
sc.firstKey = strop ? literal[0].s : (char*)&literal[0];
sc.lastKey = NULL;
sc.firstKeyInclusion = true;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
}
return false;
case dbvmLtInt:
case dbvmLtReal:
case dbvmLtString:
case dbvmLtWString:
case dbvmLtBinary:
case dbvmLtArray:
if (field->tTree != 0) {
sc.firstKey = NULL;
sc.lastKey = strop ? literal[0].s : (char*)&literal[0];
sc.lastKeyInclusion = false;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
}
return false;
case dbvmLeInt:
case dbvmLeReal:
case dbvmLeString:
case dbvmLeWString:
case dbvmLeBinary:
case dbvmLeArray:
if (field->tTree != 0) {
sc.firstKey = NULL;
sc.lastKey = strop ? literal[0].s : (char*)&literal[0];
sc.lastKeyInclusion = true;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
}
return false;
case dbvmBetweenInt:
case dbvmBetweenReal:
case dbvmBetweenString:
case dbvmBetweenWString:
case dbvmBetweenBinary:
case dbvmBetweenArray:
if (field->hashTable != 0 &&
((strop && field->_comparator(literal[0].s, literal[1].s, binop ? field->dbsSize : MAX_STRING_LENGTH) == 0)
|| (!strop && literal[0].i8 == literal[1].i8)))
{
sc.firstKey = strop ? literal[0].s : (char*)&literal[0];
dbHashTable::find(this, field->hashTable, sc);
TRACE_MSG(("Hash table search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
} else if (field->tTree != 0) {
sc.firstKey = strop ? literal[0].s : (char*)&literal[0];
sc.firstKeyInclusion = true;
sc.lastKey = strop ? literal[1].s : (char*)&literal[1];
sc.lastKeyInclusion = true;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName, sc.probes));
return true;
}
return false;
case dbvmLikeString:
case dbvmLikeEscapeString:
if ((s = findWildcard(literal[0].s, literal[1].s)) == NULL
|| ((s[1] == '\0' || s != literal[0].s) && field->tTree != 0))
{
if (s == NULL) {
sc.firstKey = sc.lastKey = literal[0].s;
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
if (field->hashTable != 0) {
dbHashTable::find(this, field->hashTable, sc);
TRACE_MSG(("Hash table search for field %s.%s: "
"%d probes\n", field->defTable->name,
field->longName, sc.probes));
} else {
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName,
sc.probes));
}
} else {
int len = (int)(s - literal[0].s);
if (len == 0) {
if (*s != dbMatchAnySubstring) {
return false;
}
sc.firstKey = NULL;
sc.lastKey = NULL;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Use index for ordering records by field "
"%s.%s\n", field->defTable->name,
field->longName));
} else {
sc.firstKey = new char[len+1];
memcpy(sc.firstKey, literal[0].s, len);
sc.firstKey[len] = '\0';
sc.firstKeyInclusion = true;
sc.lastKey = NULL;
sc.prefixLength = len;
if (s[0] != dbMatchAnySubstring || s[1] != '\0') {
// Records selected by index do not necessarily
// match the pattern, so include pattern matching in
// condition expression
if (andExpr == NULL) {
if (expr->operand[0]->cop != dbvmLoadSelfString) {
dbExprNode load(dbvmLoadSelfString,
expr->operand[0]->ref.field);
dbExprNode like(expr->cop, &load,
expr->operand[1],
expr->operand[2]);
sc.condition = &like;
dbTtree::find(this, field->tTree, sc);
like.cop = dbvmVoid;// do not destruct operands
} else {
sc.condition = expr;
dbTtree::find(this, field->tTree, sc);
}
} else {
sc.condition = andExpr;
dbTtree::find(this, field->tTree, sc);
}
} else {
dbTtree::find(this, field->tTree, sc);
}
TRACE_MSG(("Index search for prefix in LIKE expression "
"for field %s.%s: %d probes\n",
field->defTable->name, field->longName,
sc.probes));
delete[] sc.firstKey;
delete[] sc.lastKey;
}
}
return true;
}
return false;
case dbvmLikeWString:
case dbvmLikeEscapeWString:
if ((ws = findWildcard(literal[0].ws, literal[1].ws)) == NULL
|| ((ws[1] == '\0' || ws != literal[0].ws) && field->tTree != 0))
{
if (ws == NULL) {
sc.firstKey = sc.lastKey = (char*)literal[0].ws;
sc.firstKeyInclusion = sc.lastKeyInclusion = true;
if (field->hashTable != 0) {
dbHashTable::find(this, field->hashTable, sc);
TRACE_MSG(("Hash table search for field %s.%s: "
"%d probes\n", field->defTable->name,
field->longName, sc.probes));
} else {
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Index search for field %s.%s: %d probes\n",
field->defTable->name, field->longName,
sc.probes));
}
} else {
int len = (int)(ws - literal[0].ws);
if (len == 0) {
if (*ws != dbMatchAnySubstring) {
return false;
}
sc.firstKey = NULL;
sc.lastKey = NULL;
dbTtree::find(this, field->tTree, sc);
TRACE_MSG(("Use index for ordering records by field "
"%s.%s\n", field->defTable->name,
field->longName));
} else {
wchar_t* prefix = new wchar_t[len+1];
sc.firstKey = (char*)prefix;
memcpy(prefix, literal[0].ws, len*sizeof(wchar_t));
prefix[len] = '\0';
sc.firstKeyInclusion = true;
sc.lastKey = NULL;
sc.prefixLength = len;
if (ws[0] != dbMatchAnySubstring || ws[1] != '\0') {
// Records selected by index do not necessarily
// match the pattern, so include pattern matching in
// condition expression
if (andExpr == NULL) {
if (expr->operand[0]->cop != dbvmLoadSelfWString) {
dbExprNode load(dbvmLoadSelfWString,
expr->operand[0]->ref.field);
dbExprNode like(expr->cop, &load,
expr->operand[1],
expr->operand[2]);
sc.condition = &like;
dbTtree::find(this, field->tTree, sc);
like.cop = dbvmVoid;// do not destruct operands
} else {
sc.condition = expr;
dbTtree::find(this, field->tTree, sc);
}
} else {
sc.condition = andExpr;
dbTtree::find(this, field->tTree, sc);
}
} else {
dbTtree::find(this, field->tTree, sc);
}
TRACE_MSG(("Index search for prefix in LIKE expression "
"for field %s.%s: %d probes\n",
field->defTable->name, field->longName,
sc.probes));
delete[] sc.firstKey;
delete[] sc.lastKey;
}
}
return true;
}
}
return false;
}
struct SearchThreadArgument {
dbParallelQueryContext* ctx;
int id;
};
static void thread_proc parallelSearch(void* arg)
{
SearchThreadArgument* sa = (SearchThreadArgument*)arg;
sa->ctx->search(sa->id);
}
void dbDatabase::traverse(dbAnyCursor* cursor, dbQuery& query)
{
const int defaultStackSize = 1024;
oid_t buf[defaultStackSize];
oid_t *stack = buf;
int stackSize = defaultStackSize;
int sp = 0, len;
dbAnyArray* arr;
oid_t oid, *refs;
dbTable* table = (dbTable*)getRow(cursor->table->tableId);
void* root = (void*)query.root;
switch (query.startFrom) {
case dbCompiledQuery::StartFromFirst:
oid = table->firstRow;
if (oid != 0) {
stack[sp++] = oid;
}
break;
case dbCompiledQuery::StartFromLast:
oid = table->lastRow;
if (oid != 0) {
stack[sp++] = oid;
}
break;
case dbCompiledQuery::StartFromRef:
oid = *(oid_t*)root;
if (oid != 0) {
stack[sp++] = oid;
}
break;
case dbCompiledQuery::StartFromArrayPtr:
root = *(dbAnyArray**)root;
// no break
case dbCompiledQuery::StartFromArray:
arr = (dbAnyArray*)root;
len = (int)arr->length();
if (len > stackSize) {
stackSize = len;
stack = new oid_t[stackSize];
}
refs = (oid_t*)arr->base();
while (--len >= 0) {
oid = refs[len];
if (oid != 0) {
stack[sp++] = oid;
}
}
break;
default:
FASTDB_ASSERT(false);
}
cursor->checkForDuplicates();
dbExprNode* condition = query.tree;
dbFollowByNode* follow = query.follow;
while (sp != 0) {
oid_t curr = stack[--sp];
if (condition->cop == dbvmVoid || evaluate(condition, curr, table, cursor)) {
if (!cursor->add(curr)) {
break;
}
} else {
cursor->mark(curr);
}
byte* record = (byte*)getRow(curr);
for (dbFollowByNode* fp = follow; fp != NULL; fp = fp->next) {
dbFieldDescriptor* fd = fp->field;
if (fd->type == dbField::tpArray) {
dbVarying* vp = (dbVarying*)(record + fd->dbsOffs);
len = vp->size;
if (sp + len > stackSize) {
int newSize = len > stackSize ? len*2 : stackSize*2;
oid_t* newStack = new oid_t[newSize];
memcpy(newStack, stack, stackSize*sizeof(oid_t));
stackSize = newSize;
if (stack != buf) {
delete[] stack;
}
stack = newStack;
}
refs = (oid_t*)(record + vp->offs);
while (--len >= 0) {
oid = refs[len];
if (oid != 0 && !cursor->isMarked(oid)) {
stack[sp++] = oid;
}
}
} else {
FASTDB_ASSERT(fd->type == dbField::tpReference);
if (sp == stackSize) {
int newSize = stackSize*2;
oid_t* newStack = new oid_t[newSize];
memcpy(newStack, stack, stackSize*sizeof(oid_t));
stackSize = newSize;
if (stack != buf) {
delete[] stack;
}
stack = newStack;
}
oid = *(oid_t*)(record + fd->dbsOffs);
if (oid != 0 && !cursor->isMarked(oid)) {
stack[sp++] = oid;
}
}
}
}
if (stack != buf) {
delete[] stack;
}
if (query.order != NULL) {
cursor->selection.sort(this, query.order);
}
}
bool dbDatabase::prepareQuery(dbAnyCursor* cursor, dbQuery& query)
{
if (cursor == NULL) {
return false;
}
FASTDB_ASSERT(opened);
dbDatabaseThreadContext* ctx = threadContext.get();
FASTDB_ASSERT(ctx != NULL);
{
dbCriticalSection cs(query.mutex);
query.mutexLocked = true;
if (!query.compiled() || cursor->table != query.table || schemeVersion != query.schemeVersion) {
query.schemeVersion = schemeVersion;
if (!ctx->compiler.compile(cursor->table, query)) {
query.mutexLocked = false;
return false;
}
}
query.mutexLocked = false;
return true;
}
}
#ifdef PROFILE
const size_t PROFILER_HASH_SIZE = 1013;
const size_t PROFILER_MAX_QUERY_LENGTH = 1024;
class Profiler {
dbMutex mutex;
struct QueryStat {
QueryStat* next;
char* query;
size_t count;
size_t hashCode;
time_t maxTime;
time_t totalTime;
bool sequential;
~QueryStat() {
delete[] query;
}
};
QueryStat* table[PROFILER_HASH_SIZE];
size_t nQueries;
static int orderByTime(void const* p1, void const* p2) {
QueryStat* q1 = *(QueryStat**)p1;
QueryStat* q2 = *(QueryStat**)p2;
return q1->totalTime < q2->totalTime ? -1
: q1->totalTime > q2->totalTime ? 1 : q1->count < q2->count ? -1 : q1->count == q2->count ? 0 : 1;
}
static size_t hashFunction(char const* s) {
size_t h;
for (h = 0; *s != '\0'; h = h*31 + (unsigned char)*s++);
return h;
}
public:
void add(char const* query, time_t elapsed, bool sequential)
{
dbCriticalSection cs(mutex);
size_t hash = hashFunction(query);
size_t h = hash % PROFILER_HASH_SIZE;
QueryStat* s;
for (s = table[h]; s != NULL; s = s->next)
{
if (s->hashCode == hash && strcmp(query, s->query) == 0) {
s->count += 1;
if (elapsed > s->maxTime) {
s->maxTime = elapsed;
}
s->totalTime += elapsed;
s->sequential |= sequential;
return;
}
}
s = new QueryStat();
s->query = new char[strlen(query) + 1];
strcpy(s->query, query);
s->next = table[h];
table[h] = s;
s->totalTime = elapsed;
s->maxTime = elapsed;
s->count = 1;
s->hashCode = hash;
s->sequential = sequential;
nQueries += 1;
}
void dump(char const* filePath);
void dumpToStream(FILE* f)
{
dbCriticalSection cs(mutex);
QueryStat** sa = new QueryStat*[nQueries];
QueryStat** pp = sa;
time_t total = 0;
for (size_t i = 0; i < PROFILER_HASH_SIZE; i++) {
for (QueryStat* sp = table[i]; sp != NULL; sp = sp->next) {
*pp++ = sp;
total += sp->totalTime;
}
}
qsort(sa, nQueries, sizeof(QueryStat*), &orderByTime);
fprintf(f, "S Total Count Maximum Average Percent Query\n");
while (pp != sa) {
QueryStat* s = *--pp;
fprintf(f, "%c%10ld %10ld %7d %7d %6d%% %s\n",
s->sequential ? '!' : ' ',
(long)s->totalTime, (long)s->count, (int)s->maxTime, (s->count != 0 ? (int)(s->totalTime/s->count) : 0),
(total != 0 ? (int)(s->totalTime*100/total) : 0),
s->query
);
}
delete[] sa;
}
~Profiler() {
dumpToStream(stdout);
for (size_t i = 0; i < PROFILER_HASH_SIZE; i++) {
QueryStat* next;
for (QueryStat* sp = table[i]; sp != NULL; sp = next) {
next = sp->next;
delete sp;
}
}
}
struct Measure
{
Profiler& profiler;
dbAnyCursor* cursor;
dbQuery* query;
unsigned start;
bool sequential;
Measure(Profiler& p, dbAnyCursor* c, dbQuery* q = NULL)
: profiler(p), cursor(c), query(q), start(dbSystem::getCurrentTimeMsec()), sequential(false) {}
~Measure() {
char buf[PROFILER_MAX_QUERY_LENGTH];
int n = sprintf(buf, "SELECT FROM %s", cursor->getTable()->getName());
if (query != NULL) {
n += sprintf(buf + n, " WHERE ");
query->dump(buf + n);
}
profiler.add(buf, dbSystem::getCurrentTimeMsec() - start, sequential);
}
};
};
void Profiler::dump(char const* filePath)
{
FILE* f = fopen(filePath, "w");
dumpToStream(f);
fclose(f);
}
Profiler profiler;
#endif
void dbDatabase::select(dbAnyCursor* cursor, dbQuery& query)
{
#ifdef PROFILE
Profiler::Measure measure(profiler, cursor, &query);
#endif
FASTDB_ASSERT(opened);
dbDatabaseThreadContext* ctx = threadContext.get();
dbFieldDescriptor* indexedField = NULL;
FASTDB_ASSERT(ctx != NULL);
{
dbCriticalSection cs(query.mutex);
query.mutexLocked = true;
if (!query.compiled() || cursor->table != query.table || schemeVersion != query.schemeVersion) {
query.schemeVersion = schemeVersion;
if (!ctx->compiler.compile(cursor->table, query)) {
query.mutexLocked = false;
return;
}
}
query.mutexLocked = false;
}
#if FASTDB_DEBUG == DEBUG_TRACE
char buf[4096];
if (query.elements != NULL) {
TRACE_MSG(("Query: select * from %s where %s\n", query.table->name, query.dump(buf)));
} else {
TRACE_MSG(("Query: select * from %s\n", query.table->name));
}
#endif
beginTransaction(cursor->type == dbCursorForUpdate
? dbDatabase::dbExclusiveLock : dbDatabase::dbSharedLock);
if (query.limitSpecified && query.order == NULL) {
cursor->setStatementLimit(query);
}
if (query.startFrom != dbCompiledQuery::StartFromAny) {
ctx->cursors.link(cursor);
traverse(cursor, query);
if (query.limitSpecified && query.order != NULL) {
cursor->setStatementLimit(query);
cursor->truncateSelection();
}
return;
}
dbExprNode* condition = query.tree;
if (condition->cop == dbvmVoid && query.order == NULL && !query.limitSpecified) {
// Empty select condition: select all records in the table
select(cursor);
return;
}
if (condition->cop == dbvmEqReference) {
if (condition->operand[0]->cop == dbvmCurrent) {
if (condition->operand[1]->cop == dbvmLoadVarReference) {
cursor->setCurrent(*(dbAnyReference*)((char*)condition->operand[1]->var + (size_t)cursor->paramBase));
return;
} else if (condition->operand[1]->cop == dbvmIntToReference
&& condition->operand[1]->operand[0]->cop == dbvmLoadIntConstant)
{
oid_t oid = (oid_t)condition->operand[1]->operand[0]->ivalue;
cursor->setCurrent(*(dbAnyReference*)&oid);
return;
}
}
if (condition->operand[1]->cop == dbvmCurrent) {
if (condition->operand[0]->cop == dbvmLoadVarReference) {
cursor->setCurrent(*(dbAnyReference*)((char*)condition->operand[0]->var + (size_t)cursor->paramBase));
return;
} else if (condition->operand[0]->cop == dbvmIntToReference
&& condition->operand[0]->operand[0]->cop == dbvmLoadIntConstant)
{
oid_t oid = (oid_t)condition->operand[0]->operand[0]->ivalue;
cursor->setCurrent(*(dbAnyReference*)&oid);
return;
}
}
}
ctx->cursors.link(cursor);
if (condition->cop == dbvmAndBool) {
if (isIndexApplicable(cursor, condition->operand[0],
condition, indexedField))
{
if (query.order != NULL) {
if (/*indexedField->defTable != query.table
|| */query.order->next != NULL
|| query.order->getField() != indexedField)
{
cursor->selection.sort(this, query.order);
} else if (!query.order->ascent) {
cursor->selection.reverse();
}
if (query.limitSpecified) {
cursor->setStatementLimit(query);
cursor->truncateSelection();
}
}
return;
}
} else {
if (condition->cop == dbvmOrBool) {
cursor->checkForDuplicates();
}
while (condition->cop == dbvmOrBool
&& !cursor->isLimitReached()
&& isIndexApplicable(cursor, condition->operand[0], NULL,
indexedField))
{
condition = condition->operand[1];
}
if (!cursor->isLimitReached()
&& isIndexApplicable(cursor, condition, NULL, indexedField))
{
if (query.order != NULL) {
if (/*indexedField->defTable != query.table
|| */condition != query.tree
|| query.order->next != NULL
|| query.order->getField() != indexedField)
{
cursor->selection.sort(this, query.order);
} else if (!query.order->ascent) {
cursor->selection.reverse();
}
if (query.limitSpecified) {
cursor->setStatementLimit(query);
cursor->truncateSelection();
}
}
return;
}
}
if (query.order != NULL && query.order->next == NULL
&& query.order->field != NULL && query.order->field->type != dbField::tpRectangle
&& query.order->field->tTree != 0)
{
dbFieldDescriptor* field = query.order->field;
TRACE_MSG(("Use index for ordering records by field %s.%s\n",
query.table->name, field->longName));
if (query.limitSpecified) {
cursor->setStatementLimit(query);
}
if (condition->cop == dbvmVoid) {
if (query.order->ascent) {
dbTtree::traverseForward(this, field->tTree, cursor);
} else {
dbTtree::traverseBackward(this, field->tTree, cursor);
}
} else {
if (query.order->ascent) {
dbTtree::traverseForward(this,field->tTree,cursor,condition);
} else {
dbTtree::traverseBackward(this,field->tTree,cursor,condition);
}
}
return;
}
#ifdef PROFILE
measure.sequential = true;
#endif
dbTable* table = (dbTable*)getRow(cursor->table->tableId);
int n = parThreads-1;
if (cursor->getNumberOfRecords() == 0
&& n > 0 && table->nRows >= parallelScanThreshold
&& cursor->limit >= dbDefaultSelectionLimit)
{
dbPooledThread* thread[dbMaxParallelSearchThreads];
SearchThreadArgument sa[dbMaxParallelSearchThreads];
dbParallelQueryContext par(this, table, &query, cursor);
int i;
for (i = 0; i < n; i++) {
sa[i].id = i;
sa[i].ctx = ∥
thread[i] = threadPool.create((dbThread::thread_proc_t)parallelSearch, &sa[i]);
}
par.search(i);
for (i = 0; i < n; i++) {
threadPool.join(thread[i]);
}
if (query.order != NULL) {
oid_t rec[dbMaxParallelSearchThreads];
for (i = 0; i <= n; i++) {
if (par.selection[i].first != NULL) {
rec[i] = par.selection[i].first->rows[0];
} else {
rec[i] = 0;
}
}
while (true) {
int min = -1;
for (i = 0; i <= n; i++) {
if (rec[i] != 0
&& (min < 0 || dbSelection::compare(rec[i], rec[min],
query.order) < 0))
{
min = i;
}
}
if (min < 0) {
return;
}
oid_t oid =
par.selection[min].first->rows[par.selection[min].pos];
cursor->selection.add(oid);
par.selection[min].pos += 1;
if (par.selection[min].pos == par.selection[min].first->nRows){
par.selection[min].pos = 0;
dbSelection::segment* next=par.selection[min].first->next;
delete par.selection[min].first;
if ((par.selection[min].first = next) == NULL) {
rec[min] = 0;
continue;
}
}
oid = par.selection[min].first->rows[par.selection[min].pos];
rec[min] = oid;
}
} else {
for (i = 0; i <= n; i++) {
if (par.selection[i].first != NULL) {
par.selection[i].first->prev = cursor->selection.last;
if (cursor->selection.last == NULL) {
cursor->selection.first = par.selection[i].first;
} else {
cursor->selection.last->next = par.selection[i].first;
}
cursor->selection.last = par.selection[i].last;
cursor->selection.nRows += par.selection[i].nRows;
}
}
}
} else {
oid_t oid = table->firstRow;
if (!cursor->isLimitReached()) {
while (oid != 0) {
if (evaluate(condition, oid, table, cursor)) {
if (!cursor->add(oid)) {
break;
}
}
oid = getRow(oid)->next;
}
}
if (query.order != NULL) {
cursor->selection.sort(this, query.order);
}
}
if (query.limitSpecified && query.order != NULL) {
cursor->setStatementLimit(query);
cursor->truncateSelection();
}
}
void dbDatabase::select(dbAnyCursor* cursor)
{
#ifdef PROFILE
Profiler::Measure measure(profiler, cursor);
#endif
FASTDB_ASSERT(opened);
beginTransaction(cursor->type == dbCursorForUpdate ? dbExclusiveLock : dbSharedLock);
dbTable* table = (dbTable*)getRow(cursor->table->tableId);
cursor->firstId = table->firstRow;
cursor->lastId = table->lastRow;
cursor->selection.nRows = table->nRows;
cursor->allRecords = true;
threadContext.get()->cursors.link(cursor);
}
void dbDatabase::remove(dbTableDescriptor* desc, oid_t delId)
{
modified = true;
beginTransaction(dbExclusiveLock);
removeInverseReferences(desc, delId);
dbFieldDescriptor* fd;
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField){
dbHashTable::remove(this, fd, delId);
}
for (fd = desc->indexedFields; fd != NULL; fd = fd->nextIndexedField) {
if (fd->type == dbField::tpRectangle) {
dbRtree::remove(this, fd->tTree, delId, fd->dbsOffs);
} else {
dbTtree::remove(this, fd->tTree, delId, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
freeRow(desc->tableId, delId);
updateCursors(delId, true);
}
dbRecord* dbDatabase::putRow(oid_t oid, size_t newSize)
{
offs_t offs = currIndex[oid];
if (oid < committedIndexSize && index[0][oid] == index[1][oid]) {
size_t pageNo = oid/dbHandlesPerPage;
monitor->dirtyPagesMap[pageNo >> 5] |= 1 << (pageNo & 31);
cloneBitmap(offs, getRow(oid)->size);
offs_t pos = allocate(newSize);
currIndex[oid] = pos;
} else {
size_t oldSize = getRow(oid)->size;
if (oldSize != newSize) {
offs_t pos = allocate(newSize);
currIndex[oid] = pos;
cloneBitmap(offs, oldSize);
deallocate(offs, oldSize);
}
}
dbRecord* record = (dbRecord*)(baseAddr + currIndex[oid]);
record->next = ((dbRecord*)(baseAddr + offs))->next;
record->prev = ((dbRecord*)(baseAddr + offs))->prev;
record->size = (nat4)newSize;
return record;
}
void dbDatabase::allocateRow(oid_t tableId, oid_t oid, size_t size)
{
offs_t pos = allocate(size);
currIndex[oid] = pos;
dbTable* table = (dbTable*)putRow(tableId);
dbRecord* record = getRow(oid);
record->size = (nat4)size;
record->next = 0;
record->prev = table->lastRow;
if (table->lastRow != 0) {
if (accessType == dbConcurrentUpdate) {
putRow(table->lastRow)->next = oid;
table = (dbTable*)getRow(tableId);
} else {
//
// Optimisation hack: avoid cloning of the last record.
// Possible inconsistency in L2-list will be eliminated by recovery
// procedure.
//
getRow(table->lastRow)->next = oid;
file.markAsDirty(currIndex[table->lastRow], sizeof(dbRecord));
}
} else {
table->firstRow = oid;
}
table->lastRow = oid;
table->nRows += 1;
#ifdef AUTOINCREMENT_SUPPORT
table->count += 1;
#endif
}
void dbDatabase::freeRow(oid_t tableId, oid_t oid)
{
dbTable* table = (dbTable*)putRow(tableId);
dbRecord* del = getRow(oid);
size_t size = del->size;
oid_t next = del->next;
oid_t prev = del->prev;
table->nRows -= 1;
if (prev == 0) {
table->firstRow = next;
}
if (next == 0) {
table->lastRow = prev;
}
if (prev != 0) {
putRow(prev)->next = next;
}
if (next != 0) {
putRow(next)->prev = prev;
}
if (oid < committedIndexSize && index[0][oid] == index[1][oid]) {
cloneBitmap(currIndex[oid], size);
} else {
deallocate(currIndex[oid], size);
}
freeId(oid);
}
void dbDatabase::freeObject(oid_t oid)
{
offs_t marker = currIndex[oid] & dbInternalObjectMarker;
if (oid < committedIndexSize && index[0][oid] == index[1][oid]) {
cloneBitmap(currIndex[oid] - marker, internalObjectSize[marker]);
} else {
deallocate(currIndex[oid] - marker, internalObjectSize[marker]);
}
freeId(oid);
}
void dbDatabase::update(oid_t oid, dbTableDescriptor* desc, void const* record)
{
FASTDB_ASSERT(opened);
beginTransaction(dbExclusiveLock);
size_t size =
desc->columns->calculateRecordSize((byte*)record, desc->fixedSize);
byte* src = (byte*)record;
desc->columns->markUpdatedFields((byte*)getRow(oid), src);
updatedRecordId = oid;
dbFieldDescriptor* fd;
for (fd = desc->inverseFields; fd != NULL; fd = fd->nextInverseField) {
if (fd->type == dbField::tpArray) {
dbAnyArray* arr = (dbAnyArray*)(src + fd->appOffs);
int n = (int)arr->length();
oid_t* newrefs = (oid_t*)arr->base();
byte* old = (byte*)getRow(oid);
int m = ((dbVarying*)(old + fd->dbsOffs))->size;
int offs = ((dbVarying*)(old + fd->dbsOffs))->offs;
int i, j, k;
old += offs;
for (i = j = 0; i < m; i++) {
oid_t oldref = *((oid_t*)old + i);
if (oldref != 0) {
for (k = j; j < n && newrefs[j] != oldref; j++);
if (j == n) {
for (j = k--; k >= 0 && newrefs[k] != oldref; k--);
if (k < 0) {
removeInverseReference(fd, oid, oldref);
old = (byte*)getRow(oid) + offs;
}
} else {
j += 1;
}
}
}
for (i = j = 0; i < n; i++) {
if (newrefs[i] != 0) {
for(k=j; j < m && newrefs[i] != *((oid_t*)old+j); j++);
if (j == m) {
for (j=k--; k >= 0 && newrefs[i] != *((oid_t*)old+k); k--);
if (k < 0) {
insertInverseReference(fd, oid, newrefs[i]);
old = (byte*)getRow(oid) + offs;
}
} else {
j += 1;
}
}
}
} else {
oid_t newref = *(oid_t*)(src + fd->appOffs);
byte* old = (byte*)getRow(oid);
oid_t oldref = *(oid_t*)(old + fd->dbsOffs);
if (newref != oldref) {
if (oldref != 0) {
removeInverseReference(fd, oid, oldref);
}
if (newref != 0) {
insertInverseReference(fd, oid, newref);
}
}
}
}
updatedRecordId = 0;
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField) {
if (fd->attr & dbFieldDescriptor::Updated) {
dbHashTable::remove(this, fd, oid);
}
}
for (fd = desc->indexedFields; fd != NULL; fd = fd->nextIndexedField) {
if (fd->attr & dbFieldDescriptor::Updated) {
if (fd->type == dbField::tpRectangle) {
dbRtree::remove(this, fd->tTree, oid, fd->dbsOffs);
} else {
dbTtree::remove(this, fd->tTree, oid, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
}
byte* old = (byte*)getRow(oid);
byte* dst = (byte*)putRow(oid, size);
if (dst == old) {
dbSmallBuffer buf(size);
byte* temp = (byte*)buf.base();
desc->columns->storeRecordFields(temp, src, desc->fixedSize, dbFieldDescriptor::Update);
memcpy(dst+sizeof(dbRecord), temp+sizeof(dbRecord), size-sizeof(dbRecord));
} else {
desc->columns->storeRecordFields(dst, src, desc->fixedSize, dbFieldDescriptor::Update);
}
modified = true;
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField) {
if (fd->attr & dbFieldDescriptor::Updated) {
dbHashTable::insert(this, fd, oid, 0);
}
}
for (fd = desc->indexedFields; fd != NULL; fd = fd->nextIndexedField) {
if (fd->attr & dbFieldDescriptor::Updated) {
if (fd->type == dbField::tpRectangle) {
dbRtree::insert(this, fd->tTree, oid, fd->dbsOffs);
} else {
dbTtree::insert(this, fd->tTree, oid, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
fd->attr &= ~dbFieldDescriptor::Updated;
}
}
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField) {
fd->attr &= ~dbFieldDescriptor::Updated;
}
updateCursors(oid);
}
void dbDatabase::insertRecord(dbTableDescriptor* desc, dbAnyReference* ref,
void const* record)
{
FASTDB_ASSERT(opened);
beginTransaction(dbExclusiveLock);
modified = true;
size_t size =
desc->columns->calculateRecordSize((byte*)record, desc->fixedSize);
dbTable* table = (dbTable*)getRow(desc->tableId);
#ifdef AUTOINCREMENT_SUPPORT
desc->autoincrementCount = table->count + 1;
#endif
size_t nRows = table->nRows+1;
oid_t oid = allocateRow(desc->tableId, size);
byte* src = (byte*)record;
byte* dst = (byte*)getRow(oid);
desc->columns->storeRecordFields(dst, src, desc->fixedSize, dbFieldDescriptor::Insert);
ref->oid = oid;
dbFieldDescriptor* fd;
for (fd = desc->inverseFields; fd != NULL; fd = fd->nextInverseField) {
if (fd->type == dbField::tpArray) {
dbAnyArray* arr = (dbAnyArray*)(src + fd->appOffs);
int n = (int)arr->length();
oid_t* refs = (oid_t*)arr->base();
while (--n >= 0) {
if (refs[n] != 0) {
insertInverseReference(fd, oid, refs[n]);
}
}
} else {
oid_t ref = *(oid_t*)(src + fd->appOffs);
if (ref != 0) {
insertInverseReference(fd, oid, ref);
}
}
}
for (fd = desc->hashedFields; fd != NULL; fd = fd->nextHashedField) {
dbHashTable::insert(this, fd, oid, nRows);
}
for (fd = desc->indexedFields; fd != NULL; fd = fd->nextIndexedField) {
if (fd->type == dbField::tpRectangle) {
dbRtree::insert(this, fd->tTree, oid, fd->dbsOffs);
} else {
dbTtree::insert(this, fd->tTree, oid, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
}
inline void dbDatabase::extend(offs_t size)
{
size_t oldSize = header->size;
if (size > header->used) {
header->used = size;
}
if (size > oldSize) {
#ifdef DISKLESS_CONFIGURATION
handleError(FileLimitExeeded);
#endif
if (fileSizeLimit != 0 && size > fileSizeLimit) {
handleError(FileLimitExeeded);
}
dbDatabaseThreadContext* ctx = threadContext.get();
FASTDB_ASSERT(ctx != NULL);
if (ctx->mutatorCSLocked && !ctx->writeAccess) {
beginTransaction(dbCommitLock);
}
if (oldSize*2 > size) {
if (fileSizeLimit == 0 || oldSize*2 <= fileSizeLimit) {
if (offs_t(oldSize*2) == 0) { // overflow
handleError(FileLimitExeeded);
}
size = (offs_t)(oldSize*2);
} else if (fileSizeLimit > size) {
size = (offs_t)fileSizeLimit;
}
}
TRACE_MSG(("Extend database file from %ld to %ld bytes\n",
(long)header->size, (long)size));
header->size = size;
version = ++monitor->version;
_stprintf(databaseName + databaseNameLen, _T(".%d"), version);
int status = file.setSize(size, databaseName);
if (status != dbFile::ok) {
handleError(FileError, "Failed to extend file", status);
}
// file.markAsDirty(oldSize, size - oldSize);
byte* addr = (byte*)file.getAddr();
size_t shift = addr - baseAddr;
if (shift != 0) {
size_t base = (size_t)baseAddr;
for (dbL2List* cursor = ctx->cursors.next;
cursor != &ctx->cursors;
cursor = cursor->next)
{
((dbAnyCursor*)cursor)->adjustReferences(base, oldSize, shift);
}
baseAddr = addr;
index[0] = (offs_t*)((char*)index[0] + shift);
index[1] = (offs_t*)((char*)index[1] + shift);
currIndex = (offs_t*)((char*)currIndex + shift);
header = (dbHeader*)addr;
}
}
}
inline bool dbDatabase::wasReserved(offs_t pos, size_t size)
{
for (dbLocation* location = reservedChain; location != NULL; location = location->next) {
if (pos - location->pos < location->size || location->pos - pos < size) {
return true;
}
}
return false;
}
inline void dbDatabase::reserveLocation(dbLocation& location, offs_t pos, size_t size)
{
location.pos = pos;
location.size = size;
location.next = reservedChain;
reservedChain = &location;
}
inline void dbDatabase::commitLocation()
{
reservedChain = reservedChain->next;
}
inline int ilog2(offs_t val)
{
int log;
size_t pow;
for (log = dbAllocationQuantumBits, pow = dbAllocationQuantum; pow <= val; pow <<= 1, log += 1);
return log-1;
}
void dbDatabase::getMemoryStatistic(dbMemoryStatistic& stat)
{
stat.free = 0;
stat.used = 0;
stat.nHoles = 0;
stat.minHoleSize = (offs_t)header->size;
stat.maxHoleSize = 0;
for (int l = 0; l < dbDatabaseOffsetBits; l++) {
stat.nHolesOfSize[l] = 0;
}
offs_t holeSize = 0;
for (oid_t i = dbBitmapId; i < dbBitmapId + dbBitmapPages && currIndex[i] != dbFreeHandleMarker; i++){
register byte* bitmap = get(i);
for (size_t j = 0; j < dbPageSize; j++) {
unsigned mask = bitmap[j];
int count = 0;
while (mask != 0) {
while ((mask & 1) == 0) {
holeSize += 1;
mask >>= 1;
count += 1;
}
if (holeSize > 0) {
offs_t size = holeSize << dbAllocationQuantumBits;
if (size > stat.maxHoleSize) {
stat.maxHoleSize = size;
}
if (size < stat.minHoleSize) {
stat.minHoleSize = size;
}
stat.nHolesOfSize[ilog2(size)] += 1;
stat.free += size;
stat.nHoles += 1;
holeSize = 0;
}
while ((mask & 1) != 0) {
stat.used += dbAllocationQuantum;
count += 1;
mask >>= 1;
}
}
holeSize += 8 - count;
}
}
if (holeSize > 0) {
offs_t size = holeSize << dbAllocationQuantumBits;
if (size > stat.maxHoleSize) {
stat.maxHoleSize = size;
}
if (size < stat.minHoleSize) {
stat.minHoleSize = size;
}
stat.nHolesOfSize[ilog2(size)] += 1;
stat.free += size;
stat.nHoles += 1;
}
}
bool dbDatabase::isFree(offs_t pos, int objBitSize)
{
size_t quantNo = pos / dbAllocationQuantum;
oid_t pageId = (oid_t)(dbBitmapId + quantNo / (dbPageSize*8));
int offs = quantNo % (dbPageSize*8) / 8;
byte* p = put(pageId) + offs;
int bitOffs = quantNo & 7;
if (objBitSize > 8 - bitOffs) {
objBitSize -= 8 - bitOffs;
if ((*p++ & (-1 << bitOffs)) != 0) {
return false;
}
offs += 1;
while ((size_t)(objBitSize + offs*8) > dbPageSize*8) {
int n = dbPageSize - offs;
while (--n >= 0) {
if (*p++ != 0) {
return false;
}
}
p = put(++pageId);
objBitSize -= (dbPageSize - offs)*8;
offs = 0;
}
while ((objBitSize -= 8) > 0) {
if (*p++ != 0) {
return false;
}
}
return (*p & ((1 << (objBitSize + 8)) - 1)) == 0;
} else {
return (*p & (((1 << objBitSize) - 1) << bitOffs)) == 0;
}
}
void dbDatabase::markAsAllocated(offs_t pos, int objBitSize)
{
size_t quantNo = pos / dbAllocationQuantum;
oid_t pageId = (oid_t)(dbBitmapId + quantNo / (dbPageSize*8));
int offs = quantNo % (dbPageSize*8) / 8;
byte* p = put(pageId) + offs;
int bitOffs = quantNo & 7;
if (objBitSize > 8 - bitOffs) {
objBitSize -= 8 - bitOffs;
*p++ |= -1 << bitOffs;
offs += 1;
while ((size_t)(objBitSize + offs*8) > dbPageSize*8) {
memset(p, 0xFF, dbPageSize - offs);
p = put(++pageId);
objBitSize -= (dbPageSize - offs)*8;
offs = 0;
}
while ((objBitSize -= 8) > 0) {
*p++ = 0xFF;
}
*p |= (1 << (objBitSize + 8)) - 1;
} else {
*p |= ((1 << objBitSize) - 1) << bitOffs;
}
}
offs_t dbDatabase::allocate(size_t size, oid_t oid)
{
static byte const firstHoleSize [] = {
8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0
};
static byte const lastHoleSize [] = {
8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
static byte const maxHoleSize [] = {
8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
5,4,3,3,2,2,2,2,3,2,2,2,2,2,2,2,4,3,2,2,2,2,2,2,3,2,2,2,2,2,2,2,
6,5,4,4,3,3,3,3,3,2,2,2,2,2,2,2,4,3,2,2,2,1,1,1,3,2,1,1,2,1,1,1,
5,4,3,3,2,2,2,2,3,2,1,1,2,1,1,1,4,3,2,2,2,1,1,1,3,2,1,1,2,1,1,1,
7,6,5,5,4,4,4,4,3,3,3,3,3,3,3,3,4,3,2,2,2,2,2,2,3,2,2,2,2,2,2,2,
5,4,3,3,2,2,2,2,3,2,1,1,2,1,1,1,4,3,2,2,2,1,1,1,3,2,1,1,2,1,1,1,
6,5,4,4,3,3,3,3,3,2,2,2,2,2,2,2,4,3,2,2,2,1,1,1,3,2,1,1,2,1,1,1,
5,4,3,3,2,2,2,2,3,2,1,1,2,1,1,1,4,3,2,2,2,1,1,1,3,2,1,1,2,1,1,0
};
static byte const maxHoleOffset [] = {
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,0,1,5,5,5,5,5,5,0,5,5,5,5,5,5,5,
0,1,2,2,0,3,3,3,0,1,6,6,0,6,6,6,0,1,2,2,0,6,6,6,0,1,6,6,0,6,6,6,
0,1,2,2,3,3,3,3,0,1,4,4,0,4,4,4,0,1,2,2,0,1,0,3,0,1,0,2,0,1,0,5,
0,1,2,2,0,3,3,3,0,1,0,2,0,1,0,4,0,1,2,2,0,1,0,3,0,1,0,2,0,1,0,7,
0,1,2,2,3,3,3,3,0,4,4,4,4,4,4,4,0,1,2,2,0,5,5,5,0,1,5,5,0,5,5,5,
0,1,2,2,0,3,3,3,0,1,0,2,0,1,0,4,0,1,2,2,0,1,0,3,0,1,0,2,0,1,0,6,
0,1,2,2,3,3,3,3,0,1,4,4,0,4,4,4,0,1,2,2,0,1,0,3,0,1,0,2,0,1,0,5,
0,1,2,2,0,3,3,3,0,1,0,2,0,1,0,4,0,1,2,2,0,1,0,3,0,1,0,2,0,1,0,0
};
setDirty();
size = DOALIGN(size, dbAllocationQuantum);
int objBitSize = (int)(size >> dbAllocationQuantumBits);
offs_t pos;
oid_t i, firstPage, lastPage;
int holeBitSize = 0;
register int alignment = size & (dbPageSize-1);
const size_t inc = dbPageSize/dbAllocationQuantum/8;
register size_t offs;
const int pageBits = dbPageSize*8;
int holeBeforeFreePage = 0;
oid_t freeBitmapPage = 0;
dbLocation location;
lastPage = dbBitmapId + dbBitmapPages;
allocatedSize += (offs_t)size;
if (alignment == 0) {
firstPage = (oid_t)currPBitmapPage;
offs = DOALIGN(currPBitmapOffs, inc);
} else {
int retries = -1;
do {
retries += 1;
pos = fixedSizeAllocator.allocate(size);
} while (pos != 0 && (wasReserved(pos, size) || !isFree(pos, objBitSize)));
fixedSizeAllocator.retries = retries;
if (pos != 0) {
reserveLocation(location, pos, size);
if (oid != 0) {
offs_t prev = currIndex[oid];
memcpy(baseAddr+pos,
baseAddr+(prev&~dbInternalObjectMarker), size);
currIndex[oid] = (prev & dbInternalObjectMarker) + pos;
}
markAsAllocated(pos, objBitSize);
commitLocation();
file.markAsDirty(pos, size);
return pos;
}
firstPage = (oid_t)currRBitmapPage;
offs = currRBitmapOffs;
}
while (true) {
if (alignment == 0) {
// allocate page object
for (i = firstPage; i < lastPage && currIndex[i] != dbFreeHandleMarker; i++){
int spaceNeeded = objBitSize - holeBitSize < pageBits
? objBitSize - holeBitSize : pageBits;
if (bitmapPageAvailableSpace[i] <= spaceNeeded) {
holeBitSize = 0;
offs = 0;
continue;
}
register byte* begin = get(i);
size_t startOffs = offs;
while (offs < dbPageSize) {
if (begin[offs++] != 0) {
offs = DOALIGN(offs, inc);
holeBitSize = 0;
} else if ((holeBitSize += 8) == objBitSize) {
pos = (offs_t)(((offs_t(i-dbBitmapId)*dbPageSize + offs)*8
- holeBitSize) << dbAllocationQuantumBits);
if (wasReserved(pos, size)) {
offs += objBitSize >> 3;
startOffs = offs = DOALIGN(offs, inc);
holeBitSize = 0;
continue;
}
extend(pos + (offs_t)size);
reserveLocation(location, pos, size);
currPBitmapPage = i;
currPBitmapOffs = offs;
if (oid != 0) {
offs_t prev = currIndex[oid];
memcpy(baseAddr+pos,
baseAddr+(prev&~dbInternalObjectMarker), size);
currIndex[oid] = (prev & dbInternalObjectMarker) + pos;
}
begin = put(i);
size_t holeBytes = holeBitSize >> 3;
if (holeBytes > offs) {
memset(begin, 0xFF, offs);
holeBytes -= offs;
begin = put(--i);
offs = dbPageSize;
}
while (holeBytes > dbPageSize) {
memset(begin, 0xFF, dbPageSize);
holeBytes -= dbPageSize;
bitmapPageAvailableSpace[i] = 0;
begin = put(--i);
}
memset(&begin[offs-holeBytes], 0xFF, holeBytes);
commitLocation();
file.markAsDirty(pos, size);
return pos;
}
}
if (startOffs == 0 && holeBitSize == 0
&& spaceNeeded < bitmapPageAvailableSpace[i])
{
bitmapPageAvailableSpace[i] = spaceNeeded;
}
offs = 0;
}
} else {
for (i=firstPage; i<lastPage && currIndex[i] != dbFreeHandleMarker; i++){
int spaceNeeded = objBitSize - holeBitSize < pageBits
? objBitSize - holeBitSize : pageBits;
if (bitmapPageAvailableSpace[i] <= spaceNeeded) {
holeBitSize = 0;
offs = 0;
continue;
}
register byte* begin = get(i);
size_t startOffs = offs;
while (offs < dbPageSize) {
int mask = begin[offs];
if (holeBitSize + firstHoleSize[mask] >= objBitSize) {
pos = (offs_t)(((offs_t(i-dbBitmapId)*dbPageSize + offs)*8
- holeBitSize) << dbAllocationQuantumBits);
if (wasReserved(pos, size)) {
startOffs = offs += (objBitSize + 7) >> 3;
holeBitSize = 0;
continue;
}
extend(pos + (offs_t)size);
reserveLocation(location, pos, size);
currRBitmapPage = i;
currRBitmapOffs = offs;
if (oid != 0) {
offs_t prev = currIndex[oid];
memcpy(baseAddr+pos,
baseAddr+(prev&~dbInternalObjectMarker), size);
currIndex[oid] = (prev & dbInternalObjectMarker) + pos;
}
begin = put(i);
begin[offs] |= (1 << (objBitSize - holeBitSize)) - 1;
if (holeBitSize != 0) {
if (size_t(holeBitSize) > offs*8) {
memset(begin, 0xFF, offs);
holeBitSize -= (int)offs*8;
begin = put(--i);
offs = dbPageSize;
}
while (holeBitSize > pageBits) {
memset(begin, 0xFF, dbPageSize);
holeBitSize -= pageBits;
bitmapPageAvailableSpace[i] = 0;
begin = put(--i);
}
while ((holeBitSize -= 8) > 0) {
begin[--offs] = 0xFF;
}
begin[offs-1] |= ~((1 << -holeBitSize) - 1);
}
commitLocation();
file.markAsDirty(pos, size);
return pos;
} else if (maxHoleSize[mask] >= objBitSize) {
int holeBitOffset = maxHoleOffset[mask];
pos = (offs_t)(((offs_t(i-dbBitmapId)*dbPageSize + offs)*8 +
holeBitOffset) << dbAllocationQuantumBits);
if (wasReserved(pos, size)) {
startOffs = offs += (objBitSize + 7) >> 3;
holeBitSize = 0;
continue;
}
extend(pos + (offs_t)size);
reserveLocation(location, pos, size);
currRBitmapPage = i;
currRBitmapOffs = offs;
if (oid != 0) {
offs_t prev = currIndex[oid];
memcpy(baseAddr+pos,
baseAddr+(prev&~dbInternalObjectMarker), size);
currIndex[oid] = (prev & dbInternalObjectMarker) + pos;
}
begin = put(i);
begin[offs] |= ((1 << objBitSize) - 1) << holeBitOffset;
commitLocation();
file.markAsDirty(pos, size);
return pos;
}
offs += 1;
if (lastHoleSize[mask] == 8) {
holeBitSize += 8;
} else {
holeBitSize = lastHoleSize[mask];
}
}
if (startOffs == 0 && holeBitSize == 0
&& spaceNeeded < bitmapPageAvailableSpace[i])
{
bitmapPageAvailableSpace[i] = spaceNeeded;
}
offs = 0;
}
}
if (firstPage == dbBitmapId) {
if (freeBitmapPage > i) {
i = freeBitmapPage;
holeBitSize = holeBeforeFreePage;
}
if (i == dbBitmapId + dbBitmapPages) {
handleError(OutOfMemoryError, NULL, (int)size);
}
FASTDB_ASSERT(currIndex[i] == dbFreeHandleMarker);
size_t extension = (size > extensionQuantum)
? size : extensionQuantum;
int morePages =
(int)((extension + dbPageSize*(dbAllocationQuantum*8-1) - 1)
/ (dbPageSize*(dbAllocationQuantum*8-1)));
if (size_t(i + morePages) > dbBitmapId + dbBitmapPages) {
morePages =
(int)((size + dbPageSize*(dbAllocationQuantum*8-1) - 1)
/ (dbPageSize*(dbAllocationQuantum*8-1)));
if (size_t(i + morePages) > dbBitmapId + dbBitmapPages) {
handleError(OutOfMemoryError, NULL, (int)size);
}
}
objBitSize -= holeBitSize;
int skip = DOALIGN(objBitSize, dbPageSize/dbAllocationQuantum);
pos = ((i-dbBitmapId) << (dbPageBits+dbAllocationQuantumBits+3))
+ (skip << dbAllocationQuantumBits);
extend(pos + morePages*dbPageSize);
file.markAsDirty(pos, morePages*dbPageSize);
memset(baseAddr + pos, 0, morePages*dbPageSize);
memset(baseAddr + pos, 0xFF, objBitSize>>3);
*(baseAddr + pos + (objBitSize>>3)) = (1 << (objBitSize&7))-1;
memset(baseAddr + pos + (skip>>3), 0xFF,
morePages*(dbPageSize/dbAllocationQuantum/8));
oid_t j = i;
while (--morePages >= 0) {
monitor->dirtyPagesMap[j/dbHandlesPerPage/32]
|= 1 << int(j/dbHandlesPerPage & 31);
currIndex[j++] = pos + dbPageObjectMarker;
pos += dbPageSize;
}
freeBitmapPage = j;
j = i + objBitSize / pageBits;
if (alignment != 0) {
currRBitmapPage = j;
currRBitmapOffs = 0;
} else {
currPBitmapPage = j;
currPBitmapOffs = 0;
}
while (j > i) {
bitmapPageAvailableSpace[--j] = 0;
}
pos = (offs_t(i-dbBitmapId)*dbPageSize*8 - holeBitSize)
<< dbAllocationQuantumBits;
if (oid != 0) {
offs_t prev = currIndex[oid];
memcpy(baseAddr + pos,
baseAddr + (prev & ~dbInternalObjectMarker), size);
currIndex[oid] = (prev & dbInternalObjectMarker) + pos;
}
if (holeBitSize != 0) {
reserveLocation(location, pos, size);
while (holeBitSize > pageBits) {
holeBitSize -= pageBits;
memset(put(--i), 0xFF, dbPageSize);
bitmapPageAvailableSpace[i] = 0;
}
byte* cur = (byte*)put(--i) + dbPageSize;
while ((holeBitSize -= 8) > 0) {
*--cur = 0xFF;
}
*(cur-1) |= ~((1 << -holeBitSize) - 1);
commitLocation();
}
file.markAsDirty(pos, size);
return pos;
}
freeBitmapPage = i;
holeBeforeFreePage = holeBitSize;
holeBitSize = 0;
lastPage = firstPage + 1;
firstPage = dbBitmapId;
offs = 0;
}
}
void dbDatabase::deallocate(offs_t pos, size_t size)
{
FASTDB_ASSERT(pos != 0 && (pos & (dbAllocationQuantum-1)) == 0);
size_t quantNo = pos / dbAllocationQuantum;
int objBitSize = (int)((size+dbAllocationQuantum-1) / dbAllocationQuantum);
oid_t pageId = (oid_t)(dbBitmapId + quantNo / (dbPageSize*8));
size_t offs = quantNo % (dbPageSize*8) / 8;
byte* p = put(pageId) + offs;
int bitOffs = quantNo & 7;
allocatedSize -= objBitSize*dbAllocationQuantum;
if ((deallocatedSize += objBitSize*dbAllocationQuantum) >= freeSpaceReuseThreshold)
{
deallocatedSize = 0;
currRBitmapPage = currPBitmapPage = dbBitmapId;
currRBitmapOffs = currPBitmapOffs = 0;
} else {
if ((size_t(pos) & (dbPageSize-1)) == 0 && size >= dbPageSize) {
if (pageId == currPBitmapPage && offs < currPBitmapOffs) {
currPBitmapOffs = offs;
}
} else {
if (fixedSizeAllocator.deallocate(pos, size)) {
deallocatedSize -= objBitSize*dbAllocationQuantum;
} else if (pageId == currRBitmapPage && offs < currRBitmapOffs) {
currRBitmapOffs = offs;
}
}
}
bitmapPageAvailableSpace[pageId] = INT_MAX;
if (objBitSize > 8 - bitOffs) {
objBitSize -= 8 - bitOffs;
*p++ &= (1 << bitOffs) - 1;
offs += 1;
while (objBitSize + offs*8 > dbPageSize*8) {
memset(p, 0, dbPageSize - offs);
p = put(++pageId);
bitmapPageAvailableSpace[pageId] = INT_MAX;
objBitSize -= (int)((dbPageSize - offs)*8);
offs = 0;
}
while ((objBitSize -= 8) > 0) {
*p++ = 0;
}
*p &= ~((1 << (objBitSize + 8)) - 1);
} else {
*p &= ~(((1 << objBitSize) - 1) << bitOffs);
}
}
void dbDatabase::cloneBitmap(offs_t pos, size_t size)
{
size_t quantNo = pos / dbAllocationQuantum;
int objBitSize = (int)((size+dbAllocationQuantum-1) / dbAllocationQuantum);
oid_t pageId = (oid_t)(dbBitmapId + quantNo / (dbPageSize*8));
size_t offs = quantNo % (dbPageSize*8) / 8;
int bitOffs = quantNo & 7;
put(pageId);
if (objBitSize > 8 - bitOffs) {
objBitSize -= 8 - bitOffs;
offs += 1;
while (objBitSize + offs*8 > dbPageSize*8) {
put(++pageId);
objBitSize -= (int)((dbPageSize - offs)*8);
offs = 0;
}
}
}
void dbDatabase::setDirty()
{
if (!header->dirty) {
if (accessType == dbReadOnly) {
handleError(DatabaseReadOnly, "Attempt to modify readonly database");
}
header->dirty = true;
file.markAsDirty(0, sizeof(dbHeader));
file.flush(true);
}
monitor->modified = true;
modified = true;
}
void dbDatabase::recoverFreeOidList()
{
beginTransaction(dbExclusiveLock);
setDirty();
oid_t next = 0;
for (oid_t oid = dbFirstUserId; oid < currIndexSize; oid++) {
if (currIndex[oid] & dbFreeHandleMarker) {
size_t i = oid / dbHandlesPerPage;
monitor->dirtyPagesMap[i >> 5] |= 1 << (i & 31);
currIndex[oid] = next + dbFreeHandleMarker;
next = oid;
}
}
header->root[1-header->curr].freeList = next;
}
oid_t dbDatabase::allocateId(int n)
{
setDirty();
oid_t oid;
int curr = 1-header->curr;
if (n == 1) {
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
if (monitor->sessionFreeList[curr].tail != 0) {
if ((oid = monitor->sessionFreeList[curr].head) != 0) {
currIndex[monitor->sessionFreeList[curr].tail] = currIndex[oid];
unsigned i = monitor->sessionFreeList[curr].tail / dbHandlesPerPage;
monitor->dirtyPagesMap[i >> 5] |= 1 << (i & 31);
monitor->sessionFreeList[curr].head = (oid_t)(currIndex[oid] - dbFreeHandleMarker);
i = oid / dbHandlesPerPage;
monitor->dirtyPagesMap[i >> 5] |= 1 << (i & 31);
return oid;
}
}
#endif
if ((oid = header->root[curr].freeList) != 0) {
header->root[curr].freeList = (oid_t)(currIndex[oid] - dbFreeHandleMarker);
size_t i = oid / dbHandlesPerPage;
monitor->dirtyPagesMap[i >> 5] |= 1 << (i & 31);
return oid;
}
}
if (currIndexSize + n > header->root[curr].indexSize) {
size_t oldIndexSize = header->root[curr].indexSize;
size_t newIndexSize = oldIndexSize * 2;
while (newIndexSize < oldIndexSize + n) {
newIndexSize = newIndexSize*2;
}
TRACE_MSG(("Extend index size from %ld to %ld\n",
oldIndexSize, newIndexSize));
offs_t newIndex = allocate(newIndexSize*sizeof(offs_t));
offs_t oldIndex = header->root[curr].index;
memcpy(baseAddr + newIndex, currIndex, currIndexSize*sizeof(offs_t));
currIndex = index[curr] = (offs_t*)(baseAddr + newIndex);
header->root[curr].index = newIndex;
header->root[curr].indexSize = (oid_t)newIndexSize;
deallocate(oldIndex, oldIndexSize*sizeof(offs_t));
}
oid = (oid_t)currIndexSize;
header->root[curr].indexUsed = (oid_t)(currIndexSize += n);
return oid;
}
void dbDatabase::freeId(oid_t oid, int n)
{
int curr = 1-header->curr;
oid_t freeList = header->root[curr].freeList;
while (--n >= 0) {
size_t i = oid / dbHandlesPerPage;
monitor->dirtyPagesMap[i >> 5] |= 1 << (i & 31);
currIndex[oid] = freeList + dbFreeHandleMarker;
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
if (monitor->sessionFreeList[curr].tail == 0) {
monitor->sessionFreeList[curr].tail = oid;
monitor->sessionFreeList[curr].head = freeList;
}
#endif
freeList = oid++;
}
header->root[curr].freeList = freeList;
}
#ifdef AUTO_DETECT_PROCESS_CRASH
void dbDatabase::watchDogThread(dbWatchDogContext* ctx) {
dbMutex* mutex = ctx->mutex;
if (ctx->watchDog.watch()) {
mutex->lock();
if (ctx->db != NULL) {
ctx->db->cs.enter();
ctx->db->revokeLock(ctx->clientId);
ctx->db->cs.leave();
}
ctx->watchDog.close();
} else {
mutex->lock();
}
bool isEmpty = false;
dbDatabase* db = ctx->db;
if (db != NULL) {
db->cs.enter();
delete ctx;
db->cs.leave();
} else {
isEmpty = ctx->isEmpty();
delete ctx;
}
mutex->unlock();
if (isEmpty) {
delete mutex;
}
}
void dbDatabase::revokeLock(int clientId)
{
TRACE_MSG(("Revoke lock: writers %d, readers %d, lock owner %d, crashed process %d\n",
monitor->nWriters, monitor->nReaders, monitor->exclusiveLockOwner, clientId));
if (monitor->nWriters != 0 && monitor->exclusiveLockOwner == clientId) {
if (accessType != dbReadOnly && accessType != dbConcurrentRead) {
TRACE_MSG(("Revoke exclusive lock, start recovery\n"));
checkVersion();
recovery();
TRACE_MSG(("Recovery completed\n"));
monitor->exclusiveLockOwner = 0;
monitor->nWriters -= 1;
monitor->ownerPid.clear();
FASTDB_ASSERT(monitor->nWriters == 0 && !monitor->waitForUpgrade);
if (monitor->nWaitWriters != 0) {
monitor->nWaitWriters -= 1;
monitor->nWriters = 1;
writeSem.signal();
} else if (monitor->nWaitReaders != 0) {
monitor->nReaders = monitor->nWaitReaders;
monitor->nWaitReaders = 0;
readSem.signal(monitor->nReaders);
}
} else {
handleError(Deadlock, "Owner of exclusive database lock is crashed");
}
} else {
int nReaders = monitor->nReaders;
for (int i = 0; i < nReaders; i++) {
if (monitor->sharedLockOwner[i] == clientId) {
TRACE_MSG(("Revoke shared lock\n"));
while (++i < nReaders) {
monitor->sharedLockOwner[i-1] = monitor->sharedLockOwner[i];
}
monitor->sharedLockOwner[i-1] = 0;
monitor->nReaders -= 1;
if (monitor->nReaders == 1 && monitor->waitForUpgrade) {
FASTDB_ASSERT(monitor->nWriters == 0);
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
removeLockOwner(monitor->upgradeId);
monitor->upgradeId = 0;
#endif
monitor->waitForUpgrade = false;
monitor->nWaitWriters -= 1;
monitor->nWriters = 1;
monitor->nReaders = 0;
upgradeSem.signal();
} else if (monitor->nReaders == 0) {
if (monitor->nWaitWriters != 0) {
FASTDB_ASSERT(monitor->nWriters == 0 && !monitor->waitForUpgrade);
monitor->nWaitWriters -= 1;
monitor->nWriters = 1;
writeSem.signal();
}
}
break;
}
}
}
}
void dbDatabase::startWatchDogThreads()
{
while (maxClientId < monitor->clientId) {
int id = ++maxClientId;
if (id != selfId) {
sprintf(databaseName + databaseNameLen, ".pid.%d", id);
dbWatchDogContext* ctx = new dbWatchDogContext();
if (ctx->watchDog.open(databaseName)) {
watchDogThreadContexts.link(ctx);
ctx->clientId = id;
ctx->db = this;
ctx->mutex = watchDogMutex;
ctx->thread.create((dbThread::thread_proc_t)watchDogThread, ctx);
} else {
revokeLock(id);
delete ctx;
}
}
}
}
#endif
void dbDatabase::addLockOwner()
{
int nReaders = monitor->nReaders;
FASTDB_ASSERT(nReaders <= dbMaxReaders && nReaders > 0);
while (monitor->sharedLockOwner[--nReaders] != 0) {
FASTDB_ASSERT(nReaders != 0);
}
#if DEBUG_LOCKS
int selfId = dbThread::getCurrentThreadId();
#endif
monitor->sharedLockOwner[nReaders] = selfId;
monitor->sharedLockOwner[nReaders] = selfId;
}
void dbDatabase::removeLockOwner(int selfId)
{
int id = 0;
int i = monitor->nReaders;
do {
FASTDB_ASSERT(i > 0);
int nextId = monitor->sharedLockOwner[--i];
monitor->sharedLockOwner[i] = id;
id = nextId;
} while (id != selfId);
}
bool dbDatabase::isInWriteTransaction()
{
dbDatabaseThreadContext* ctx = threadContext.get();
if (ctx == NULL ||
(!ctx->writeAccess && !ctx->readAccess && !ctx->mutatorCSLocked))
{
return false;
}
if (accessType != dbConcurrentUpdate) {
return ctx->writeAccess != 0;
}
return true;
}
bool dbDatabase::isCommitted()
{
dbDatabaseThreadContext* ctx = threadContext.get();
return ctx == NULL ||
(!ctx->writeAccess && !ctx->readAccess && !ctx->mutatorCSLocked);
}
bool dbDatabase::isUpdateTransaction()
{
dbDatabaseThreadContext* ctx = threadContext.get();
return ctx != NULL && ctx->isMutator;
}
bool dbDatabase::isAttached()
{
return threadContext.get() != NULL;
}
bool dbDatabase::beginTransaction(dbLockType lockType)
{
dbDatabaseThreadContext* ctx = threadContext.get();
bool delayedCommitForced = false;
#if DEBUG_LOCKS
int selfId = dbThread::getCurrentThreadId();
#endif
if (commitDelay != 0 && lockType != dbCommitLock) {
dbCriticalSection cs(delayedCommitStopTimerMutex);
if (monitor->delayedCommitContext == ctx && ctx->commitDelayed) {
// skip delayed transaction because this thread is starting new transaction
monitor->delayedCommitContext = NULL;
ctx->commitDelayed = false;
if (commitTimerStarted != 0) {
time_t elapsed = time(NULL) - commitTimerStarted;
if (commitTimeout < elapsed) {
commitTimeout = 0;
} else {
commitTimeout -= elapsed;
}
}
delayedCommitStopTimerEvent.signal();
} else {
monitor->forceCommitCount += 1;
delayedCommitForced = true;
}
}
if (lockType != dbSharedLock) {
ctx->isMutator = true;
}
if (accessType == dbConcurrentUpdate && lockType != dbCommitLock) {
if (!ctx->mutatorCSLocked) {
mutatorCS.enter();
ctx->mutatorCSLocked = true;
#ifdef RECOVERABLE_CRITICAL_SECTION
if (monitor->modified) {
// mutatorCS lock was revoked
monitor->modified = false;
checkVersion();
recovery();
}
#endif
}
} else if (lockType != dbSharedLock) {
if (!ctx->writeAccess) {
// FASTDB_ASSERT(accessType != dbReadOnly && accessType != dbConcurrentRead);
cs.enter();
#ifdef AUTO_DETECT_PROCESS_CRASH
startWatchDogThreads();
#endif
if (ctx->readAccess) {
FASTDB_ASSERT(monitor->nWriters == 0);
TRACE_MSG(("Attempt to upgrade lock from shared to exclusive can cause deadlock\n"));
if (monitor->nReaders != 1) {
if (monitor->waitForUpgrade) {
handleError(Deadlock);
}
monitor->waitForUpgrade = true;
monitor->upgradeId = selfId;
monitor->nWaitWriters += 1;
cs.leave();
if (commitDelay != 0) {
delayedCommitStopTimerEvent.signal();
}
while (!upgradeSem.wait(waitLockTimeout)
|| !(monitor->nWriters == 1 && monitor->nReaders == 0))
{
// There are no writers, so some reader was died
cs.enter();
unsigned currTime = dbSystem::getCurrentTimeMsec();
if (currTime - monitor->lastDeadlockRecoveryTime
>= waitLockTimeout)
{
// Ok, let's try to "remove" this reader
monitor->lastDeadlockRecoveryTime = currTime;
if (--monitor->nReaders == 1) {
// Looks like we are recovered
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
removeLockOwner(selfId);
#endif
monitor->nWriters = 1;
monitor->nReaders = 0;
monitor->nWaitWriters -= 1;
monitor->waitForUpgrade = false;
cs.leave();
break;
}
}
cs.leave();
}
} else {
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
removeLockOwner(selfId);
#endif
monitor->nWriters = 1;
monitor->nReaders = 0;
cs.leave();
}
} else {
if (monitor->nWriters != 0 || monitor->nReaders != 0) {
monitor->nWaitWriters += 1;
cs.leave();
if (commitDelay != 0) {
delayedCommitStopTimerEvent.signal();
}
while (!writeSem.wait(waitLockTimeout)
|| !(monitor->nWriters == 1 && monitor->nReaders == 0))
{
cs.enter();
unsigned currTime = dbSystem::getCurrentTimeMsec();
if (currTime - monitor->lastDeadlockRecoveryTime
>= waitLockTimeout)
{
monitor->lastDeadlockRecoveryTime = currTime;
if (monitor->nWriters != 0) {
// writer was died
checkVersion();
recovery();
monitor->nWriters = 1;
monitor->nWaitWriters -= 1;
cs.leave();
break;
} else {
// some reader was died
// Ok, let's try to "remove" this reader
if (--monitor->nReaders == 0) {
// Looks like we are recovered
monitor->nWriters = 1;
monitor->nWaitWriters -= 1;
cs.leave();
break;
}
}
}
cs.leave();
}
} else {
monitor->nWriters = 1;
cs.leave();
}
}
monitor->ownerPid = ctx->currPid;
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
monitor->exclusiveLockOwner = selfId;
#endif
ctx->writeAccess = true;
} else {
if (monitor->ownerPid != ctx->currPid) {
handleError(LockRevoked);
}
}
} else {
if (!ctx->readAccess && !ctx->writeAccess) {
cs.enter();
#ifdef AUTO_DETECT_PROCESS_CRASH
startWatchDogThreads();
#endif
if (monitor->nWriters + monitor->nWaitWriters != 0) {
monitor->nWaitReaders += 1;
cs.leave();
if (commitDelay != 0) {
delayedCommitStopTimerEvent.signal();
}
while (!readSem.wait(waitLockTimeout)
|| !(monitor->nWriters == 0 && monitor->nReaders > 0))
{
cs.enter();
unsigned currTime = dbSystem::getCurrentTimeMsec();
if (currTime - monitor->lastDeadlockRecoveryTime
>= waitLockTimeout)
{
monitor->lastDeadlockRecoveryTime = currTime;
if (monitor->nWriters != 0) {
// writer was died
checkVersion();
recovery();
monitor->nWriters = 0;
} else {
// some potential writer was died
monitor->nWaitWriters -= 1;
}
monitor->nReaders += 1;
monitor->nWaitReaders -= 1;
cs.leave();
break;
}
cs.leave();
}
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
cs.enter();
addLockOwner();
cs.leave();
#endif
} else {
monitor->nReaders += 1;
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
addLockOwner();
#endif
cs.leave();
}
ctx->readAccess = true;
}
}
if (lockType != dbCommitLock) {
if (delayedCommitForced) {
dbCriticalSection cs(delayedCommitStopTimerMutex);
monitor->forceCommitCount -= 1;
}
if (!checkVersion()) {
return false;
}
cs.enter();
index[0] = (offs_t*)(baseAddr + header->root[0].index);
index[1] = (offs_t*)(baseAddr + header->root[1].index);
int curr = monitor->curr;
if (accessType != dbConcurrentRead) {
currIndex = index[1-curr];
currIndexSize = header->root[1-curr].indexUsed;
committedIndexSize = header->root[curr].indexUsed;
} else {
currIndex = index[curr];
currIndexSize = header->root[curr].indexUsed;
committedIndexSize = header->root[curr].indexUsed;
}
cs.leave();
}
return true;
}
bool dbDatabase::checkVersion()
{
if (version != monitor->version) {
_stprintf(databaseName+databaseNameLen, _T(".%d"), monitor->version);
if (version == 0) {
if (file.open(fileName, databaseName, fileOpenFlags, monitor->size, false)
!= dbFile::ok)
{
handleError(DatabaseOpenError, "Failed to open database file");
endTransaction(); // release locks
return false;
}
} else {
int status = file.setSize(header->size, databaseName, false);
if (status != dbFile::ok) {
handleError(FileError, "Failed to reopen database file", status);
endTransaction(); // release locks
return false;
}
}
version = monitor->version;
baseAddr = (byte*)file.getAddr();
header = (dbHeader*)baseAddr;
if (file.getSize() != header->size) {
handleError(FileError, "File size is not matched");
endTransaction(); // release locks
return false;
}
}
return true;
}
void dbDatabase::precommit()
{
//FASTDB_ASSERT(accessType != dbConcurrentUpdate);
dbDatabaseThreadContext* ctx = threadContext.get();
if (ctx != NULL && (ctx->writeAccess || ctx->readAccess)) {
ctx->concurrentId = monitor->concurrentTransId;
endTransaction(ctx);
}
}
void dbDatabase::delayedCommit()
{
dbCriticalSection cs(delayedCommitStartTimerMutex);
commitThreadSyncEvent.signal();
while (!stopDelayedCommitThread) {
delayedCommitStartTimerEvent.wait(delayedCommitStartTimerMutex);
delayedCommitStartTimerEvent.reset();
bool deferredCommit = false;
{
dbCriticalSection cs2(delayedCommitStopTimerMutex);
if (stopDelayedCommitThread || monitor->delayedCommitContext == NULL) {
continue;
} else if (monitor->forceCommitCount == 0) {
commitTimerStarted = time(NULL);
deferredCommit = true;
}
}
if (deferredCommit) {
delayedCommitStopTimerEvent.wait((unsigned)(commitTimeout*1000));
delayedCommitStopTimerEvent.reset();
}
{
dbCriticalSection cs2(delayedCommitStopTimerMutex);
dbDatabaseThreadContext* ctx = monitor->delayedCommitContext;
if (ctx != NULL) {
commitTimeout = commitDelay;
monitor->delayedCommitContext = NULL;
threadContext.set(ctx);
commit(ctx);
ctx->commitDelayed = false;
if (ctx->removeContext) {
dbCriticalSection cs(threadContextListMutex);
delete ctx;
}
}
}
}
}
void dbDatabase::waitTransactionAcknowledgement()
{
}
void dbDatabase::commit()
{
dbDatabaseThreadContext* ctx = threadContext.get();
if (ctx != NULL && !ctx->commitDelayed) {
if (ctx->writeAccess) {
if (monitor->ownerPid != ctx->currPid) {
handleError(LockRevoked);
}
}
cs.enter();
bool hasSomethingToCommit = modified && !monitor->commitInProgress
&& (monitor->uncommittedChanges || ctx->writeAccess || ctx->mutatorCSLocked || ctx->concurrentId == monitor->concurrentTransId);
cs.leave();
if (hasSomethingToCommit) {
if (!ctx->writeAccess) {
beginTransaction(ctx->mutatorCSLocked ? dbCommitLock : dbExclusiveLock);
}
if (commitDelay != 0) {
dbCriticalSection cs(delayedCommitStartTimerMutex);
monitor->delayedCommitContext = ctx;
ctx->commitDelayed = true;
delayedCommitStopTimerEvent.reset();
delayedCommitStartTimerEvent.signal();
} else {
commit(ctx);
}
} else {
if (ctx->writeAccess || ctx->readAccess || ctx->mutatorCSLocked) {
endTransaction(ctx);
}
}
}
}
void dbDatabase::commit(dbDatabaseThreadContext* ctx)
{
//
// commit transaction
//
int curr = header->curr;
int4 *map = monitor->dirtyPagesMap;
size_t oldIndexSize = header->root[curr].indexSize;
size_t newIndexSize = header->root[1-curr].indexSize;
if (newIndexSize > oldIndexSize) {
offs_t newIndex = allocate(newIndexSize*sizeof(offs_t));
header->root[1-curr].shadowIndex = newIndex;
header->root[1-curr].shadowIndexSize = (oid_t)newIndexSize;
cloneBitmap(header->root[curr].index, oldIndexSize*sizeof(offs_t));
deallocate(header->root[curr].index, oldIndexSize*sizeof(offs_t));
}
//
// Enable read access to the database
//
cs.enter();
FASTDB_ASSERT(ctx->writeAccess);
monitor->commitInProgress = true;
monitor->sharedLockOwner[0] = monitor->exclusiveLockOwner;
monitor->exclusiveLockOwner = 0;
monitor->nWriters -= 1;
monitor->nReaders += 1;
monitor->ownerPid.clear();
if (accessType == dbConcurrentUpdate) {
// now readers will see updated data
monitor->curr ^= 1;
}
if (monitor->nWaitReaders != 0) {
monitor->nReaders += monitor->nWaitReaders;
readSem.signal(monitor->nWaitReaders);
monitor->nWaitReaders = 0;
}
ctx->writeAccess = false;
ctx->readAccess = true;
// Copy values of this fields to local variables since them can be changed by read-only transaction in concurrent update mode
size_t committedIndexSize = this->committedIndexSize;
offs_t* currIndex = this->currIndex;
size_t currIndexSize = this->currIndexSize;
cs.leave();
size_t nPages = committedIndexSize / dbHandlesPerPage;
offs_t* srcIndex = currIndex;
offs_t* dstIndex = index[curr];
for (size_t i = 0; i < nPages; i++) {
if (map[i >> 5] & (1 << (i & 31))) {
file.markAsDirty(header->root[1-curr].index + i*dbPageSize, dbPageSize);
for (size_t j = 0; j < dbHandlesPerPage; j++) {
offs_t offs = dstIndex[j];
if (srcIndex[j] != offs) {
if (!(offs & dbFreeHandleMarker)) {
size_t marker = offs & dbInternalObjectMarker;
if (marker != 0) {
deallocate(offs-(offs_t)marker, internalObjectSize[marker]);
} else {
deallocate(offs, ((dbRecord*)(baseAddr+offs))->size);
}
}
}
}
}
dstIndex += dbHandlesPerPage;
srcIndex += dbHandlesPerPage;
}
file.markAsDirty(header->root[1-curr].index + nPages*dbPageSize,
(currIndexSize - nPages*dbHandlesPerPage)*sizeof(offs_t));
offs_t* end = index[curr] + committedIndexSize;
while (dstIndex < end) {
offs_t offs = *dstIndex;
if (*srcIndex != offs) {
if (!(offs & dbFreeHandleMarker)) {
size_t marker = offs & dbInternalObjectMarker;
if (marker != 0) {
deallocate(offs-(offs_t)marker, internalObjectSize[marker]);
} else {
deallocate(offs, ((dbRecord*)(baseAddr+offs))->size);
}
}
}
dstIndex += 1;
srcIndex += 1;
}
file.markAsDirty(0, sizeof(dbHeader));
file.flush();
cs.enter();
while (monitor->backupInProgress) {
cs.leave();
backupCompletedEvent.wait();
cs.enter();
}
header->curr = curr ^= 1;
cs.leave();
file.markAsDirty(0, sizeof(dbHeader));
#ifdef SYNCHRONOUS_REPLICATION
waitTransactionAcknowledgement();
#else
file.flush();
#endif
file.markAsDirty(0, sizeof(dbHeader));
header->root[1-curr].indexUsed = (oid_t)currIndexSize;
header->root[1-curr].freeList = header->root[curr].freeList;
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
monitor->sessionFreeList[1-curr] = monitor->sessionFreeList[curr];
#endif
if (newIndexSize != oldIndexSize) {
header->root[1-curr].index=header->root[curr].shadowIndex;
header->root[1-curr].indexSize=header->root[curr].shadowIndexSize;
header->root[1-curr].shadowIndex=header->root[curr].index;
header->root[1-curr].shadowIndexSize=header->root[curr].indexSize;
file.markAsDirty(header->root[1-curr].index, currIndexSize*sizeof(offs_t));
memcpy(baseAddr + header->root[1-curr].index, currIndex,
currIndexSize*sizeof(offs_t));
memset(map, 0, 4*((currIndexSize+dbHandlesPerPage*32-1)
/ (dbHandlesPerPage*32)));
} else {
byte* srcIndex = (byte*)currIndex;
byte* dstIndex = (byte*)index[1-curr];
for (size_t i = 0; i < nPages; i++) {
if (map[i >> 5] & (1 << (i & 31))) {
map[i >> 5] -= (1 << (i & 31));
memcpy(dstIndex, srcIndex, dbPageSize);
file.markAsDirty(header->root[1-curr].index + i*dbPageSize, dbPageSize);
}
srcIndex += dbPageSize;
dstIndex += dbPageSize;
}
if (currIndexSize > nPages*dbHandlesPerPage) {
memcpy(dstIndex, srcIndex,
sizeof(offs_t)*(currIndexSize-nPages*dbHandlesPerPage));
file.markAsDirty(header->root[1-curr].index + nPages*dbPageSize,
sizeof(offs_t)*(currIndexSize-nPages*dbHandlesPerPage));
memset(map + (nPages>>5), 0,
((currIndexSize + dbHandlesPerPage*32 - 1)
/ (dbHandlesPerPage*32) - (nPages>>5))*4);
}
}
cs.enter();
modified = false;
monitor->modified = false;
monitor->uncommittedChanges = false;
monitor->commitInProgress = false;
if (accessType != dbConcurrentUpdate) {
monitor->curr = curr;
}
monitor->concurrentTransId += 1;
cs.leave();
if (ctx->writeAccess || ctx->readAccess || ctx->mutatorCSLocked) {
endTransaction(ctx);
}
}
void dbDatabase::rollback()
{
dbDatabaseThreadContext* ctx = threadContext.get();
if (modified
&& (monitor->uncommittedChanges || ctx->writeAccess || ctx->mutatorCSLocked || ctx->concurrentId == monitor->concurrentTransId))
{
if (!ctx->writeAccess && !ctx->mutatorCSLocked) {
beginTransaction(dbExclusiveLock);
}
int curr = header->curr;
byte* dstIndex = baseAddr + header->root[curr].shadowIndex;
byte* srcIndex = (byte*)index[curr];
currRBitmapPage = currPBitmapPage = dbBitmapId;
currRBitmapOffs = currPBitmapOffs = 0;
size_t nPages =
(committedIndexSize + dbHandlesPerPage - 1) / dbHandlesPerPage;
int4 *map = monitor->dirtyPagesMap;
if (header->root[1-curr].index != header->root[curr].shadowIndex) {
memcpy(dstIndex, srcIndex, nPages*dbPageSize);
file.markAsDirty( header->root[curr].shadowIndex, nPages*dbPageSize);
} else {
for (size_t i = 0; i < nPages; i++) {
if (map[i >> 5] & (1 << (i & 31))) {
memcpy(dstIndex, srcIndex, dbPageSize);
file.markAsDirty(header->root[1-curr].index + i*dbPageSize, dbPageSize);
}
srcIndex += dbPageSize;
dstIndex += dbPageSize;
}
}
header->root[1-curr].indexSize = header->root[curr].shadowIndexSize;
header->root[1-curr].indexUsed = header->root[curr].indexUsed;
header->root[1-curr].freeList = header->root[curr].freeList;
header->root[1-curr].index = header->root[curr].shadowIndex;
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
monitor->sessionFreeList[1-curr] = monitor->sessionFreeList[curr];
#endif
currIndex = index[1-curr] = (offs_t*)(baseAddr + header->root[1-curr].index);
memset(map, 0,
size_t((currIndexSize+dbHandlesPerPage*32-1) / (dbHandlesPerPage*32))*4);
file.markAsDirty(0, sizeof(dbHeader));
modified = false;
monitor->uncommittedChanges = false;
monitor->concurrentTransId += 1;
restoreTablesConsistency();
}
if (monitor->users != 0) { // if not abandon
endTransaction(ctx);
}
}
void dbDatabase::updateCursors(oid_t oid, bool removed)
{
dbDatabaseThreadContext* ctx = threadContext.get();
if (ctx != NULL) {
for (dbAnyCursor* cursor = (dbAnyCursor*)ctx->cursors.next;
cursor != &ctx->cursors;
cursor = (dbAnyCursor*)cursor->next)
{
if (cursor->currId == oid) {
if (removed) {
cursor->currId = 0;
} else if (cursor->record != NULL/* && !cursor->updateInProgress*/) {
cursor->fetch();
}
}
}
}
}
void dbDatabase::endTransaction(dbDatabaseThreadContext* ctx)
{
if (!ctx->commitDelayed) {
while (!ctx->cursors.isEmpty()) {
((dbAnyCursor*)ctx->cursors.next)->reset();
}
}
if (ctx->writeAccess) {
cs.enter();
ctx->isMutator = false;
monitor->nWriters -= 1;
monitor->exclusiveLockOwner = 0;
monitor->ownerPid.clear();
FASTDB_ASSERT(monitor->nWriters == 0 && !monitor->waitForUpgrade);
if (monitor->nWaitWriters != 0) {
monitor->nWaitWriters -= 1;
monitor->nWriters = 1;
writeSem.signal();
} else if (monitor->nWaitReaders != 0) {
monitor->nReaders = monitor->nWaitReaders;
monitor->nWaitReaders = 0;
readSem.signal(monitor->nReaders);
}
cs.leave();
} else if (ctx->readAccess) {
cs.enter();
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
#ifdef DEBUG_LOCKS
int selfId = dbThread::getCurrentThreadId();
#endif
removeLockOwner(selfId);
#endif
monitor->nReaders -= 1;
if (monitor->nReaders == 1 && monitor->waitForUpgrade) {
FASTDB_ASSERT(monitor->nWriters == 0);
#if defined(AUTO_DETECT_PROCESS_CRASH) || DEBUG_LOCKS
removeLockOwner(monitor->upgradeId);
monitor->upgradeId = 0;
#endif
monitor->waitForUpgrade = false;
monitor->nWaitWriters -= 1;
monitor->nWriters = 1;
monitor->nReaders = 0;
upgradeSem.signal();
} else if (monitor->nReaders == 0) {
if (monitor->nWaitWriters != 0) {
FASTDB_ASSERT(monitor->nWriters == 0 && !monitor->waitForUpgrade);
monitor->nWaitWriters -= 1;
monitor->nWriters = 1;
writeSem.signal();
}
}
cs.leave();
}
ctx->writeAccess = false;
ctx->readAccess = false;
if (ctx->mutatorCSLocked) {
ctx->mutatorCSLocked = false;
mutatorCS.leave();
}
}
void dbDatabase::linkTable(dbTableDescriptor* table, oid_t tableId)
{
FASTDB_ASSERT(((void)"Table can be used only in one database",
table->tableId == 0));
table->db = this;
table->nextDbTable = tables;
table->tableId = tableId;
tables = table;
size_t h = (size_t)table->name % dbTableHashSize;
table->collisionChain = tableHash[h];
tableHash[h] = table;
}
void dbDatabase::unlinkTable(dbTableDescriptor* table)
{
dbTableDescriptor** tpp;
for (tpp = &tables; *tpp != table; tpp = &(*tpp)->nextDbTable);
*tpp = table->nextDbTable;
table->tableId = 0;
size_t h = (size_t)table->name % dbTableHashSize;
for (tpp = &tableHash[h]; *tpp != table; tpp = &(*tpp)->collisionChain);
*tpp = table->collisionChain;
if (!table->fixedDatabase) {
table->db = NULL;
}
}
dbTableDescriptor* dbDatabase::findTableByName(char const* name)
{
char* sym = (char*)name;
dbSymbolTable::add(sym, tkn_ident);
return findTable(sym);
}
dbTableDescriptor* dbDatabase::findTable(char const* name)
{
size_t h = (size_t)name % dbTableHashSize;
for (dbTableDescriptor* desc = tableHash[h]; desc != NULL; desc = desc->collisionChain) {
if (desc->name == name) {
return desc;
}
}
return NULL;
}
void dbDatabase::insertInverseReference(dbFieldDescriptor* fd, oid_t inverseId,
oid_t targetId)
{
byte buf[1024];
if (inverseId == targetId) {
return;
}
fd = fd->inverseRef;
if (fd->type == dbField::tpArray) {
dbTableDescriptor* desc = fd->defTable;
dbRecord* rec = getRow(targetId);
dbVarying* arr = (dbVarying*)((byte*)rec + fd->dbsOffs);
size_t arrSize = arr->size;
size_t arrOffs = arr->offs;
offs_t oldOffs = currIndex[targetId];
size_t newSize = desc->fixedSize;
size_t lastOffs = desc->columns->sizeWithoutOneField(fd, (byte*)rec, newSize);
size_t newArrOffs = DOALIGN(newSize, sizeof(oid_t));
size_t oldSize = rec->size;
newSize = newArrOffs + (arrSize + 1)*sizeof(oid_t);
if (newSize > oldSize) {
newSize = newArrOffs + (arrSize+1)*sizeof(oid_t)*2;
} else {
newSize = oldSize;
}
byte* dst = (byte*)putRow(targetId, newSize);
byte* src = baseAddr + oldOffs;
byte* tmp = NULL;
if (dst == src) {
if (arrOffs == newArrOffs && newArrOffs > lastOffs) {
*((oid_t*)((byte*)rec + newArrOffs) + arrSize) = inverseId;
arr->size += 1;
updateCursors(targetId);
return;
}
if (oldSize > sizeof(buf)) {
src = tmp = dbMalloc(oldSize);
} else {
src = buf;
}
memcpy(src, rec, oldSize);
}
desc->columns->copyRecordExceptOneField(fd, dst, src, desc->fixedSize);
arr = (dbVarying*)(dst + fd->dbsOffs);
arr->size = (nat4)arrSize + 1;
arr->offs = (int)newArrOffs;
memcpy(dst + newArrOffs, src + arrOffs, arrSize*sizeof(oid_t));
*((oid_t*)(dst + newArrOffs) + arrSize) = inverseId;
if (tmp != NULL) {
dbFree(tmp);
}
} else {
if (fd->indexType & INDEXED) {
dbTtree::remove(this, fd->tTree, targetId, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
oid_t oldRef = *(oid_t*)((byte*)getRow(targetId) + fd->dbsOffs);
if (oldRef != 0) {
removeInverseReference(fd, targetId, oldRef);
}
*(oid_t*)((byte*)putRow(targetId) + fd->dbsOffs) = inverseId;
if (fd->indexType & INDEXED) {
dbTtree::insert(this, fd->tTree, targetId, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
updateCursors(targetId);
}
void dbDatabase::removeInverseReferences(dbTableDescriptor* desc, oid_t oid)
{
dbVisitedObject* chain = visitedChain;
dbVisitedObject vo(oid, chain);
visitedChain = &vo;
dbFieldDescriptor* fd;
for (fd = desc->inverseFields; fd != NULL; fd = fd->nextInverseField) {
if (fd->type == dbField::tpArray) {
dbVarying* arr = (dbVarying*)((byte*)getRow(oid) + fd->dbsOffs);
int n = arr->size;
int offs = arr->offs + n*sizeof(oid_t);
while (--n >= 0) {
offs -= sizeof(oid_t);
oid_t ref = *(oid_t*)((byte*)getRow(oid) + offs);
if (ref != 0) {
removeInverseReference(fd, oid, ref);
}
}
} else {
oid_t ref = *(oid_t*)((byte*)getRow(oid) + fd->dbsOffs);
if (ref != 0) {
removeInverseReference(fd, oid, ref);
}
}
}
visitedChain = chain;
}
void dbDatabase::removeInverseReference(dbFieldDescriptor* fd,
oid_t inverseId,
oid_t targetId)
{
if (inverseId == targetId || targetId == updatedRecordId ||
(currIndex[targetId] & dbFreeHandleMarker) != 0)
{
return;
}
for (dbVisitedObject* vo = visitedChain; vo != NULL; vo = vo->next) {
if (vo->oid == targetId) {
return;
}
}
byte* rec = (byte*)putRow(targetId);
if ((fd->indexType & DB_FIELD_CASCADE_DELETE)
&& ((fd->inverseRef->type != dbField::tpArray) ||
((dbVarying*)(rec + fd->inverseRef->dbsOffs))->size <= 1))
{
remove(fd->inverseRef->defTable, targetId);
return;
}
fd = fd->inverseRef;
if (fd->type == dbField::tpArray) {
dbVarying* arr = (dbVarying*)(rec + fd->dbsOffs);
oid_t* p = (oid_t*)(rec + arr->offs);
for (int n = arr->size, i = n; --i >= 0;) {
if (p[i] == inverseId) {
while (++i < n) {
p[i-1] = p[i];
}
arr->size -= 1;
break;
}
}
} else {
if (*(oid_t*)(rec + fd->dbsOffs) == inverseId) {
if (fd->indexType & INDEXED) {
dbTtree::remove(this, fd->tTree, targetId, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
*(oid_t*)((byte*)putRow(targetId) + fd->dbsOffs) = 0;
if (fd->indexType & INDEXED) {
dbTtree::insert(this, fd->tTree, targetId, fd->type, (int)fd->dbsSize, fd->_comparator, fd->dbsOffs);
}
}
}
updateCursors(targetId);
}
bool dbDatabase::completeDescriptorsInitialization()
{
bool result = true;
for (dbTableDescriptor* desc = tables; desc != NULL; desc = desc->nextDbTable) {
dbFieldDescriptor* fd;
for (fd = desc->firstField; fd != NULL; fd = fd->nextField) {
if (fd->refTableName != NULL) {
fd->refTable = findTable(fd->refTableName);
}
}
result &= desc->checkRelationship();
}
return result;
}
bool dbDatabase::backup(char_t const* file, bool compactify)
{
dbFile f;
if (f.create(file, compactify ? 0 : dbFile::no_buffering) != dbFile::ok) {
return false;
}
bool result = backup(&f, compactify);
f.close();
return result;
}
bool dbDatabase::backup(dbFile* f, bool compactify)
{
bool result = true;
cs.enter();
if (monitor->backupInProgress) {
cs.leave();
return false; // no two concurrent backups are possible
}
backupCompletedEvent.reset();
monitor->backupInProgress = true;
cs.leave();
if (compactify) {
int curr = header->curr;
size_t nObjects = header->root[1-curr].indexUsed;
size_t i;
size_t nIndexPages = (header->root[1-curr].indexSize + dbHandlesPerPage - 1) / dbHandlesPerPage;
offs_t* newIndex = new offs_t[nIndexPages*dbHandlesPerPage];
memset(newIndex, 0, nIndexPages*dbPageSize);
offs_t used = (offs_t)((nIndexPages*2 + 1)*dbPageSize);
offs_t start = used;
used += DOALIGN(getRow(dbMetaTableId)->size, dbAllocationQuantum);
for (i = dbFirstUserId; i < nObjects; i++) {
offs_t offs = currIndex[i];
if (!(offs & dbFreeHandleMarker)) {
offs_t marker = offs & dbInternalObjectMarker;
newIndex[i] = used | marker;
used += (offs_t)(DOALIGN(marker ? internalObjectSize[marker] : (size_t)getRow((oid_t)i)->size,
dbAllocationQuantum));
} else {
newIndex[i] = offs;
}
}
size_t bitmapPages =
(used + dbPageSize*(dbAllocationQuantum*8-1) - 1)
/ (dbPageSize*(dbAllocationQuantum*8-1));
size_t bitmapSize = bitmapPages*dbPageSize;
for (i = dbFirstUserId; i < nObjects; i++) {
if (!(newIndex[i] & dbFreeHandleMarker)) {
newIndex[i] += (offs_t)bitmapSize;
}
}
used += (offs_t)bitmapSize;
for (i = 0; i < bitmapPages; i++) {
newIndex[dbBitmapId+i] = start | dbPageObjectMarker;
start += dbPageSize;
}
while (i < dbBitmapPages) {
newIndex[dbBitmapId+i] = dbFreeHandleMarker;
i += 1;
}
newIndex[dbMetaTableId] = start;
newIndex[dbInvalidId] = dbFreeHandleMarker;
byte page[dbPageSize];
memset(page, 0, sizeof page);
dbHeader* newHeader = (dbHeader*)page;
offs_t newFileSize = DOALIGN(used, dbPageSize);
newHeader->size = newFileSize;
newHeader->curr = 0;
newHeader->dirty = 0;
newHeader->initialized = true;
newHeader->majorVersion = header->majorVersion;
newHeader->minorVersion = header->minorVersion;
newHeader->mode = header->mode;
newHeader->used = used;
newHeader->root[0].index = newHeader->root[1].shadowIndex = (offs_t)dbPageSize;
newHeader->root[0].shadowIndex = newHeader->root[1].index = (offs_t)(dbPageSize + nIndexPages*dbPageSize);
newHeader->root[0].shadowIndexSize = newHeader->root[0].indexSize =
newHeader->root[1].shadowIndexSize = newHeader->root[1].indexSize = (oid_t)(nIndexPages*dbHandlesPerPage);
newHeader->root[0].indexUsed = newHeader->root[1].indexUsed = (oid_t)nObjects;
newHeader->root[0].freeList = newHeader->root[1].freeList = header->root[1-curr].freeList;
result &= f->write(page, dbPageSize);
result &= f->write(newIndex, nIndexPages*dbPageSize);
result &= f->write(newIndex, nIndexPages*dbPageSize);
int bits = (int)((used >> dbAllocationQuantumBits) - (offs_t)(bitmapPages-1)*dbPageSize*8);
memset(page, 0xFF, sizeof page);
while (--bitmapPages != 0) {
result &= f->write(page, dbPageSize);
}
if (size_t(bits >> 3) < dbPageSize) {
memset(page + (bits >> 3) + 1, 0, dbPageSize - (bits >> 3) - 1);
page[bits >> 3] = (1 << (bits & 7)) - 1;
}
result &= f->write(page, dbPageSize);
result &= f->write(baseAddr + currIndex[dbMetaTableId], DOALIGN(getRow(dbMetaTableId)->size, dbAllocationQuantum));
for (i = dbFirstUserId; i < nObjects; i++) {
offs_t offs = newIndex[i];
if (!(offs & dbFreeHandleMarker)) {
offs_t marker = (int)(offs & dbInternalObjectMarker);
size_t size = DOALIGN(marker ? internalObjectSize[marker] : getRow((oid_t)i)->size,
dbAllocationQuantum);
result &= f->write(baseAddr + currIndex[i] - marker, size);
}
}
if (used != newFileSize) {
FASTDB_ASSERT(newFileSize - used < dbPageSize);
size_t align = (size_t)(newFileSize - used);
memset(page, 0, align);
result &= f->write(page, align);
}
delete[] newIndex;
} else { // end if compactify
const size_t segmentSize = 64*1024;
byte* p = baseAddr;
size_t size = (size_t)header->size;
result = true;
while (size > segmentSize && result) {
result = f->write(p, segmentSize);
p += segmentSize;
size -= segmentSize;
}
if (result) {
result = f->write(p, size);
}
}
cs.enter();
monitor->backupInProgress = false;
backupCompletedEvent.signal();
cs.leave();
return result;
}
dbDatabase::dbDatabase(dbAccessType type, size_t dbInitSize,
size_t dbExtensionQuantum, size_t dbInitIndexSize,
int nThreads
#ifdef NO_PTHREADS
, dbThreadMode threadMode
#endif
#ifdef REPLICATION_SUPPORT
, dbReplicationMode replicationMode
#endif
) : accessType(type),
initSize(dbInitSize),
extensionQuantum(dbExtensionQuantum),
initIndexSize(dbInitIndexSize),
freeSpaceReuseThreshold((offs_t)dbExtensionQuantum),
parallelScanThreshold(dbDefaultParallelScanThreshold)
{
#ifdef AUTO_DETECT_PROCESS_CRASH
FASTDB_ASSERT(type != dbConcurrentUpdate);
#endif
#if dbDatabaseOffsetBits > 32 || dbDatabaseOidBits > 32
FASTDB_ASSERT(sizeof(size_t) == 8);
#endif
bitmapPageAvailableSpace = new int[dbBitmapId + dbBitmapPages];
setConcurrency(nThreads);
tables = NULL;
commitDelay = 0;
commitTimeout = 0;
commitTimerStarted = 0;
backupFileName = NULL;
backupPeriod = 0;
databaseName = NULL;
fileName = NULL;
opened = false;
fileSizeLimit = 0;
errorHandler = NULL;
confirmDeleteColumns = false;
schemeVersion = 0;
visitedChain = NULL;
header = NULL;
xmlContext = NULL;
fileOpenFlags = 0;
}
dbDatabase::~dbDatabase()
{
delete[] bitmapPageAvailableSpace;
delete[] databaseName;
delete[] fileName;
}
dbDatabase::dbErrorHandler dbDatabase::setErrorHandler(dbDatabase::dbErrorHandler newHandler, void* context)
{
dbErrorHandler prevHandler = errorHandler;
errorHandler = newHandler;
errorHandlerContext = context;
return prevHandler;
}
dbTableDescriptor* dbDatabase::loadMetaTable()
{
dbTable* table = (dbTable*)getRow(dbMetaTableId);
dbTableDescriptor* metatable = new dbTableDescriptor(this, table);
linkTable(metatable, dbMetaTableId);
oid_t tableId = table->firstRow;
while (tableId != 0) {
table = (dbTable*)getRow(tableId);
dbTableDescriptor* desc;
for (desc = tables; desc != NULL && desc->tableId != tableId; desc = desc->nextDbTable);
if (desc == NULL) {
desc = new dbTableDescriptor(this, table);
linkTable(desc, tableId);
desc->setFlags();
}
tableId = table->next;
}
completeDescriptorsInitialization();
return metatable;
}
#ifdef REPLICATION_SUPPORT
#define MAX_LOST_TRANSACTIONS 100
char const* statusText[] = {
"OFFLINE",
"ONLINE",
"ACTIVE",
"STANDBY",
"RECOVERED"
};
char const* requestText[] = {
"CONNECT",
"RECOVERY",
"GET_STATUS",
"STATUS",
"UPDATE_PAGE",
"RECOVER_PAGE",
"NEW_ACTIVE_NODE",
"CHANGE_ACTIVE_NODE",
"CLOSE",
"READY",
"COMMITTED"
};
bool dbReplicatedDatabase::isReplicated()
{
return true;
}
dbReplicatedDatabase::dbReplicatedDatabase(dbAccessType type,
size_t dbInitSize,
size_t dbExtensionQuantum,
size_t dbInitIndexSize,
int nThreads)
: dbDatabase(type, dbInitSize, dbExtensionQuantum, dbInitIndexSize, nThreads)
{
pollInterval = dbDefaultPollInterval;
waitReadyTimeout = dbWaitReadyTimeout;
waitStatusTimeout = dbWaitStatusTimeout;
recoveryConnectionAttempts = dbRecoveryConnectionAttempts;
startupConnectionAttempts = dbStartupConnectionAttempts;
replicationWriteTimeout = dbReplicationWriteTimeout;
maxAsyncRecoveryIterations = dbMaxAsyncRecoveryIterations;
}
bool dbReplicatedDatabase::open(OpenParameters& params)
{
accessType = params.accessType;
fileOpenFlags = params.fileOpenFlags;
extensionQuantum = params.extensionQuantum;
initIndexSize = params.initIndexSize;
initSize = params.initSize;
freeSpaceReuseThreshold = params.freeSpaceReuseThreshold;
setConcurrency(params.nThreads);
pollInterval = params.pollInterval;
waitReadyTimeout = params.waitReadyTimeout;
waitStatusTimeout = params.waitStatusTimeout;
recoveryConnectionAttempts = params.recoveryConnectionAttempts;
startupConnectionAttempts = params.startupConnectionAttempts;
replicationWriteTimeout = params.replicationWriteTimeout;
maxAsyncRecoveryIterations = params.maxAsyncRecoveryIterations;
return open(params.databaseName, params.databaseFilePath, params.nodeId, params.nodeAddresses, params.nNodes);
}
bool dbReplicatedDatabase::open(char const* dbName, char const* fiName,
int id, char* servers[], int nServers)
{
int i;
char buf [64];
ReplicationRequest rr;
FASTDB_ASSERT(accessType != dbReadOnly);
this->id = id;
this->nServers = nServers;
con = new dbConnection[nServers];
serverURL = servers;
delete[] databaseName;
delete[] fileName;
commitDelay = 0;
commitTimeout = 0;
commitTimerStarted = 0;
waitLockTimeout = INFINITE;
delayedCommitEventsOpened = false;
backupFileName = NULL;
backupPeriod = 0;
opened = false;
header = NULL;
stopDelayedCommitThread = false;
onlineRecovery = false;
memset(tableHash, 0, sizeof tableHash);
databaseNameLen = strlen(dbName);
char* name = new char[databaseNameLen+16];
sprintf(name, "%s.in", dbName);
databaseName = name;
if (fiName == NULL) {
fileName = new char[databaseNameLen + 5];
sprintf(fileName, "%s.fdb", dbName);
} else {
fileName = new char[strlen(fiName)+1];
strcpy(fileName, fiName);
}
dbInitializationMutex::initializationStatus status = initMutex.initialize(name);
if (status == dbInitializationMutex::InitializationError) {
handleError(DatabaseOpenError, "Failed to start database initialization");
return false;
}
if (status != dbInitializationMutex::NotYetInitialized) {
handleError(DatabaseOpenError, "Database is already started");
return false;
}
sprintf(name, "%s.dm", dbName);
if (!shm.open(name)) {
handleError(DatabaseOpenError, "Failed to open database monitor");
cleanup(status, 0);
return false;
}
monitor = shm.get();
sprintf(name, "%s.ws", dbName);
if (!writeSem.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database writers semaphore");
cleanup(status, 1);
return false;
}
sprintf(name, "%s.rs", dbName);
if (!readSem.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database readers semaphore");
cleanup(status, 2);
return false;
}
sprintf(name, "%s.us", dbName);
if (!upgradeSem.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database upgrade semaphore");
cleanup(status, 3);
return false;
}
sprintf(name, "%s.bce", dbName);
if (!backupCompletedEvent.open(name)) {
handleError(DatabaseOpenError,
"Failed to initialize database backup completed event");
cleanup(status, 4);
return false;
}
backupInitEvent.open();
backupFileName = NULL;
fixedSizeAllocator.reset();
allocatedSize = 0;
size_t indexSize = initIndexSize < dbFirstUserId
? size_t(dbFirstUserId) : initIndexSize;
indexSize = DOALIGN(indexSize, dbHandlesPerPage);
size_t fileSize = initSize ? initSize : dbDefaultInitDatabaseSize;
fileSize = DOALIGN(fileSize, dbBitmapSegmentSize);
if (fileSize < indexSize*sizeof(offs_t)*4) {
fileSize = indexSize*sizeof(offs_t)*4;
}
for (i = dbBitmapId + dbBitmapPages; --i >= 0;) {
bitmapPageAvailableSpace[i] = INT_MAX;
}
currRBitmapPage = currPBitmapPage = dbBitmapId;
currRBitmapOffs = currPBitmapOffs = 0;
reservedChain = NULL;
tables = NULL;
modified = false;
selfId = 0;
maxClientId = 0;
attach();
sprintf(name, "%s.cs", dbName);
if (!cs.create(name, &monitor->sem)) {
handleError(DatabaseOpenError, "Failed to initialize database monitor");
cleanup(status, 5);
return false;
}
if (accessType == dbConcurrentUpdate || accessType == dbConcurrentRead) {
sprintf(name, "%s.mcs", dbName);
if (!mutatorCS.create(name, &monitor->mutatorSem)) {
cleanup(status, 6);
handleError(DatabaseOpenError,
"Failed to initialize database monitor");
return false;
}
}
readSem.reset();
writeSem.reset();
upgradeSem.reset();
monitor->nReaders = 0;
monitor->nWriters = 0;
monitor->nWaitReaders = 0;
monitor->nWaitWriters = 0;
monitor->waitForUpgrade = false;
monitor->version = version = 1;
monitor->users = 0;
monitor->backupInProgress = 0;
monitor->forceCommitCount = 0;
monitor->lastDeadlockRecoveryTime = 0;
monitor->delayedCommitContext = NULL;
monitor->concurrentTransId = 1;
monitor->commitInProgress = false;
monitor->uncommittedChanges = false;
monitor->clientId = 0;
monitor->upgradeId = 0;
monitor->modified = false;
monitor->exclusiveLockOwner = 0;
memset(monitor->dirtyPagesMap, 0, dbDirtyPageBitmapSize);
memset(monitor->sharedLockOwner, 0, sizeof(monitor->sharedLockOwner));
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
monitor->sessionFreeList[0].head = monitor->sessionFreeList[0].tail = 0;
monitor->sessionFreeList[1].head = monitor->sessionFreeList[1].tail = 0;
#endif
sprintf(databaseName, "%s.%d", dbName, version);
if (file.open(fileName, databaseName, fileOpenFlags, fileSize, true) != dbFile::ok)
{
handleError(DatabaseOpenError, "Failed to create database file");
cleanup(status, 8);
return false;
}
baseAddr = (byte*)file.getAddr();
monitor->size = fileSize = file.getSize();
header = (dbHeader*)baseAddr;
if ((unsigned)header->curr > 1) {
handleError(DatabaseOpenError, "Database file was corrupted: "
"invalid root index");
cleanup(status, 9);
return false;
}
acceptSock = socket_t::create_global(servers[id]);
if (!acceptSock->is_ok()) {
acceptSock->get_error_text(buf, sizeof buf);
dbTrace("<<<FATAL>>> Failed to create accept socket: %s\n", buf);
cleanup(status, 9);
delete acceptSock;
return false;
}
FD_ZERO(&inputSD);
socket_handle_t acceptSockHnd = acceptSock->get_handle();
FD_SET(acceptSockHnd, &inputSD);
nInputSD = acceptSockHnd+1;
startEvent.open(false);
recoveredEvent.open(false);
int connectionAttempts = startupConnectionAttempts;
bool recoveryNeeded = false;
if (!header->initialized) {
monitor->curr = header->curr = 0;
header->size = fileSize;
size_t used = dbPageSize;
header->root[0].index = used;
header->root[0].indexSize = indexSize;
header->root[0].indexUsed = dbFirstUserId;
header->root[0].freeList = 0;
used += indexSize*sizeof(offs_t);
header->root[1].index = used;
header->root[1].indexSize = indexSize;
header->root[1].indexUsed = dbFirstUserId;
header->root[1].freeList = 0;
used += indexSize*sizeof(offs_t);
header->root[0].shadowIndex = header->root[1].index;
header->root[1].shadowIndex = header->root[0].index;
header->root[0].shadowIndexSize = indexSize;
header->root[1].shadowIndexSize = indexSize;
header->majorVersion= FASTDB_MAJOR_VERSION;
header->minorVersion = FASTDB_MINOR_VERSION;
header->mode = dbHeader::getCurrentMode();
index[0] = (offs_t*)(baseAddr + header->root[0].index);
index[1] = (offs_t*)(baseAddr + header->root[1].index);
index[0][dbInvalidId] = dbFreeHandleMarker;
size_t bitmapPages =
(used + dbPageSize*(dbAllocationQuantum*8-1) - 1)
/ (dbPageSize*(dbAllocationQuantum*8-1));
memset(baseAddr+used, 0xFF, (used + bitmapPages*dbPageSize)
/ (dbAllocationQuantum*8));
size_t i;
for (i = 0; i < bitmapPages; i++) {
index[0][dbBitmapId + i] = used + dbPageObjectMarker;
used += dbPageSize;
}
while (i < dbBitmapPages) {
index[0][dbBitmapId+i] = dbFreeHandleMarker;
i += 1;
}
currIndex = index[0];
currIndexSize = dbFirstUserId;
committedIndexSize = 0;
initializeMetaTable();
header->dirty = true;
if (accessType == dbConcurrentRead) {
modified = false;
}
memcpy(index[1], index[0], currIndexSize*sizeof(offs_t));
file.markAsDirty(0, used);
file.flush(true);
header->initialized = true;
file.markAsDirty(0, sizeof(dbHeader));
con[id].status = (accessType == dbConcurrentRead) ? ST_RECOVERED : ST_ONLINE;
} else {
if (!header->isCompatible()) {
handleError(DatabaseOpenError, "Incompatible database mode");
cleanup(status, 9);
delete acceptSock;
return false;
}
monitor->curr = header->curr;
if (header->dirty) {
recoveryNeeded = true;
dbTrace("Replicated node %d was not normally closed\n", id);
con[id].status = ST_RECOVERED;
if (accessType != dbConcurrentRead) {
connectionAttempts = recoveryConnectionAttempts;
}
} else {
con[id].status = ST_ONLINE;
}
}
cs.enter();
monitor->users += 1;
selfId = ++monitor->clientId;
#ifdef AUTO_DETECT_PROCESS_CRASH
sprintf(databaseName + databaseNameLen, ".pid.%d", selfId);
selfWatchDog.create(databaseName);
watchDogMutex = new dbMutex();
#endif
opened = true;
cs.leave();
if (accessType == dbConcurrentUpdate) {
initMutex.done();
}
handshake = true;
readerThread.create(startReader, this);
pollNodes:
bool startup = true;
bool standalone;
int nOnlineNodes = 0;
int minOnlineNodes = nServers;
if (accessType == dbConcurrentRead && nServers > 1) {
minOnlineNodes = 2;
}
masterNodeId = activeNodeId = -1;
do {
standalone = true;
if (nOnlineNodes == minOnlineNodes) {
dbThread::sleep(1);
}
nOnlineNodes = 1;
for (i = 0; i < nServers && (nOnlineNodes < minOnlineNodes || activeNodeId < 0); i++) {
if (i != id) {
socket_t* s = con[i].reqSock;
if (s == NULL) {
TRACE_IMSG(("Try to connect to node %d address '%s'\n", i, servers[i]));
s = socket_t::connect(servers[i],
socket_t::sock_global_domain,
connectionAttempts);
if (!s->is_ok()) {
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to establish connection with node %d: %s\n", i, buf);
delete s;
continue;
}
TRACE_IMSG(("Establish connection with node %d address '%s'\n", i, servers[i]));
}
standalone = false;
rr.op = ReplicationRequest::RR_GET_STATUS;
rr.nodeId = id;
bool success = false;
if (con[i].reqSock == NULL) {
TRACE_IMSG(("Send GET_STATUS request to node %d and wait for response\n", i));
if (!s->write(&rr, sizeof rr) || !s->read(&rr, sizeof rr)) {
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to get status from node %d: %s\n", i, buf);
delete s;
} else {
TRACE_IMSG(("Node %d returns status %s\n", i, statusText[rr.status]));
addConnection(i, s);
con[i].status = rr.status;
con[i].updateCounter = rr.size;
success = true;
}
} else {
con[i].statusEvent.reset();
con[i].waitStatusEventFlag += 1;
TRACE_IMSG(("Send GET_STATUS request to node %d\n", i));
if (writeReq(i, rr)) {
dbCriticalSection cs(startCS);
lockConnection(i);
if (!con[i].statusEvent.wait(startCS, waitStatusTimeout)) {
dbTrace("Failed to get status from node %d\n", i);
deleteConnection(i);
} else {
TRACE_IMSG(("Received response from node %d with status %s\n", i, statusText[con[i].status]));
success = true;
}
unlockConnection(i);
}
con[i].waitStatusEventFlag -= 1;
}
if (success) {
nOnlineNodes += 1;
TRACE_IMSG(("Status of node %d is %s\n", i, statusText[con[i].status]));
if (con[i].status == ST_ACTIVE) {
startup = false;
masterNodeId = activeNodeId = i;
} else if (con[i].status == ST_STANDBY) {
startup = false;
} else if (con[i].status == ST_ONLINE
&& con[i].updateCounter > file.updateCounter)
{
TRACE_IMSG(("Change status of current node to RECOVERED because its updateCounter=%d and update counter of active node is %d\n", file.updateCounter, con[i].updateCounter));
con[id].status = ST_RECOVERED;
}
}
}
}
} while (!standalone && con[id].status == ST_RECOVERED && activeNodeId < 0 && (id != 0 || nOnlineNodes < minOnlineNodes));
if (!startup) {
//
// The node was activated after the active node start the user application
// So the node's data is out of date. Mark it as recovered.
//
TRACE_IMSG(("Change status of node connected after application startup to RECOVERED\n"));
con[id].status = ST_RECOVERED;
}
file.configure(this);
TRACE_IMSG(("My status is %s\n", statusText[con[id].status]));
if (con[id].status == ST_RECOVERED && activeNodeId < 0) {
if (recoveryNeeded) {
dbTrace("Database was not normally closed: start recovery\n");
recovery();
recoveryNeeded = false;
}
con[id].status = ST_ONLINE;
}
if (con[id].status == ST_ONLINE) {
for (activeNodeId = 0;
activeNodeId < id && con[activeNodeId].status != ST_ONLINE;
activeNodeId++);
if (activeNodeId == id && accessType != dbConcurrentRead) {
dbTrace("Node %d becomes active at startup\n", id);
//
// Nobody else pretends to be active, so I will be...
//
for (i = 0; i < nServers; i++) {
lockConnection(i);
if (i != id && con[i].status == ST_ONLINE) {
dbCriticalSection cs(startCS);
TRACE_IMSG(("Waiting ready event from node %d\n", i));
if (!con[i].readyEvent.wait(startCS, waitReadyTimeout)) {
dbTrace("Didn't receive ready event from node %d\n", i);
deleteConnection(i);
unlockConnection(i);
goto pollNodes;
}
TRACE_IMSG(("Received ready event from node %d\n", i));
}
unlockConnection(i);
}
con[id].status = ST_ACTIVE;
for (i = 0; i < nServers; i++) {
if (con[i].status == ST_ONLINE) {
con[i].status = ST_STANDBY;
rr.op = ReplicationRequest::RR_STATUS;
rr.nodeId = i;
rr.status = ST_STANDBY;
TRACE_IMSG(("Send STANDBY status to node %d\n", i));
writeReq(i, rr);
} else if (con[i].status == ST_STANDBY) {
rr.op = ReplicationRequest::RR_CHANGE_ACTIVE_NODE;
rr.nodeId = id;
con[i].status = rr.status = ST_RECOVERED;
TRACE_IMSG(("Send CHANGE_ACTIVE_NODE message to node %d\n", i));
writeReq(i, rr);
}
}
} else if (activeNodeId < id) {
rr.op = ReplicationRequest::RR_READY;
rr.nodeId = id;
masterNodeId = activeNodeId;
TRACE_IMSG(("Send READY status to node %d\n", activeNodeId));
if (!writeReq(activeNodeId, rr)) {
TRACE_IMSG(("Failed to send READY request to node %d\n", activeNodeId));
goto pollNodes;
}
}
} else if (activeNodeId >= 0) {
TRACE_IMSG(("Send RECOVERY request to node %d\n", activeNodeId));
rr.op = ReplicationRequest::RR_RECOVERY;
rr.size = file.getUpdateCountTableSize();
rr.nodeId = id;
if (!writeReq(activeNodeId, rr, file.diskUpdateCount, rr.size*sizeof(int))) {
TRACE_IMSG(("Failed to send RECOVERY request to node %d\n", activeNodeId));
goto pollNodes;
}
}
handshake = false;;
TRACE_IMSG(("My new status is %s\n", statusText[con[id].status]));
if (con[id].status != ST_ACTIVE) {
dbCriticalSection cs(startCS);
if (accessType == dbConcurrentRead) {
if (con[id].status == ST_RECOVERED) {
recoveredEvent.wait(startCS);
dbTrace("Recovery of node %d is completed\n", id);
}
monitor->curr = header->curr;
} else {
if (!standalone) {
startEvent.wait(startCS);
} else {
con[id].status = ST_ACTIVE;
}
baseAddr = (byte*)file.getAddr();
header = (dbHeader*)baseAddr;
if (opened) {
int curr = header->curr;
monitor->curr = curr;
offs_t* shadowIndex = (offs_t*)(baseAddr + header->root[curr].index);
offs_t* currIndex = (offs_t*)(baseAddr + header->root[1-curr].index);
for (size_t i = 0, size = header->root[curr].indexUsed; i < size; i++) {
if (currIndex[i] != shadowIndex[i]) {
currIndex[i] = shadowIndex[i];
file.markAsDirty(header->root[1-curr].index + i*sizeof(offs_t), sizeof(offs_t));
}
}
this->currIndex = currIndex;
header->size = file.getSize();
header->root[1-curr].index = header->root[curr].shadowIndex;
header->root[1-curr].indexSize = header->root[curr].shadowIndexSize;
header->root[1-curr].shadowIndex = header->root[curr].index;
header->root[1-curr].shadowIndexSize = header->root[curr].indexSize;
header->root[1-curr].indexUsed = header->root[curr].indexUsed;
header->root[1-curr].freeList = header->root[curr].freeList;
#ifdef DO_NOT_REUSE_OID_WITHIN_SESSION
monitor->sessionFreeList[1-curr] = monitor->sessionFreeList[curr];
#endif
file.markAsDirty(0, sizeof(dbHeader));
file.updateCounter += MAX_LOST_TRANSACTIONS;
restoreTablesConsistency();
file.flush();
}
}
}
if (opened) {
if (loadScheme(true)) {
if (accessType != dbConcurrentUpdate) {
initMutex.done();
}
return true;
} else {
if (accessType == dbConcurrentRead) {
do {
dbTableDescriptor *desc, *next;
for (desc = tables; desc != NULL; desc = next) {
next = desc->nextDbTable;
if (desc->cloneOf != NULL) {
delete desc;
} else if (!desc->fixedDatabase) {
desc->db = NULL;
}
}
tables = NULL;
TRACE_IMSG(("Database schema was not yet initialized\n"));
endTransaction(); // release locks
dbThread::sleep(1);
} while (!loadScheme(false));
return true;
}
dbTrace("Failed to load database scheme\n");
opened = false;
}
}
if (accessType != dbConcurrentUpdate) {
initMutex.done();
}
#ifdef PROTECT_DATABASE
if (accessType == dbConcurrentRead) {
file.protect(0, header->size);
}
#endif
readerThread.join();
delete[] con;
delete acceptSock;
close0();
return false;
}
void thread_proc dbReplicatedDatabase::startReader(void* arg)
{
((dbReplicatedDatabase*)arg)->reader();
}
int dbReplicatedDatabase::getNumberOfOnlineNodes()
{
int n = 0;
for (int i = 0; i < nServers; i++) {
if (con[i].status != ST_OFFLINE) {
n += 1;
}
}
return n;
}
void dbReplicatedDatabase::deleteConnection(int nodeId)
{
dbTrace("Delete connection with node %d, used counter %d\n", nodeId, con[nodeId].useCount);
{
dbCriticalSection cs(sockCS);
socket_t* reqSock = con[nodeId].reqSock;
socket_t* respSock = con[nodeId].respSock;
while (con[nodeId].useCount > 1) {
con[nodeId].waitUseEventFlag += 1;
con[nodeId].useCount -= 1;
con[nodeId].useEvent.reset();
con[nodeId].useEvent.wait(sockCS);
con[nodeId].waitUseEventFlag -= 1;
con[nodeId].useCount += 1;
}
FASTDB_ASSERT(con[nodeId].useCount == 1);
con[nodeId].status = ST_OFFLINE;
if (con[nodeId].reqSock != NULL) {
FASTDB_ASSERT(con[nodeId].reqSock == reqSock);
FD_CLR(reqSock->get_handle(), &inputSD);
delete reqSock;
con[nodeId].reqSock = NULL;
}
if (con[nodeId].respSock != NULL) {
FASTDB_ASSERT(con[nodeId].respSock == respSock);
FD_CLR(respSock->get_handle(), &inputSD);
delete respSock;
con[nodeId].respSock = NULL;
}
}
if (nodeId == activeNodeId) {
changeActiveNode();
}
}
void dbReplicatedDatabase::changeActiveNode()
{
activeNodeId = -1;
TRACE_IMSG(("Change active node\n"));
if (accessType != dbConcurrentRead && con[id].status == ST_STANDBY) {
ReplicationRequest rr;
int i;
for (i = 0; i < id; i++) {
if (con[i].status == ST_ONLINE || con[i].status == ST_STANDBY) {
rr.op = ReplicationRequest::RR_GET_STATUS;
TRACE_IMSG(("Send GET_STATUS request to node %d to choose new active node\n", i));
rr.nodeId = id;
if (writeReq(i, rr)) {
return;
}
}
}
dbTrace("Activate stand-by server %d\n", id);
for (i = 0; i < nServers; i++) {
if (con[i].status != ST_OFFLINE && i != id) {
TRACE_IMSG(("Send NEW_ACTIVE_NODE request to node %d\n", i));
rr.op = ReplicationRequest::RR_NEW_ACTIVE_NODE;
rr.nodeId = id;
if (writeReq(i, rr)) {
con[i].status = ST_STANDBY;
}
}
}
con[id].status = ST_ACTIVE;
{
dbCriticalSection cs(startCS);
startEvent.signal();
}
}
}
void dbReplicatedDatabase::reader()
{
char buf[256];
ReplicationRequest rr;
bool statusRequested = false;
bool closed = false;
dbDatabaseThreadContext* ctx = NULL;
if (accessType != dbAllAccess) { // concurrent update
ctx = new dbDatabaseThreadContext();
threadContext.set(ctx);
}
while (opened) {
timeval tv;
bool handshake = this->handshake;
if (handshake) {
tv.tv_sec = dbOpenPollInterval / 1000;
tv.tv_usec = dbOpenPollInterval % 1000 * 1000;
} else {
tv.tv_sec = pollInterval / 1000;
tv.tv_usec = pollInterval % 1000 * 1000;
}
fd_set ready = inputSD;
int rc = ::select(nInputSD, &ready, NULL, NULL, &tv);
#if 0 // for testing only
static int nIterations = 0;
if (id == 1 && ++nIterations == 50000) {
printf("Simulate timeout %d\n", nIterations);
lockConnection(masterNodeId);
deleteConnection(masterNodeId);
unlockConnection(masterNodeId);
rc = 0; // simulate timeout
}
#endif
if (rc == 0) { // timeout
if (!closed && !handshake && con[id].status == ST_STANDBY) {
if (statusRequested || activeNodeId < 0) {
if (!onlineRecovery && accessType == dbConcurrentRead && activeNodeId < 0 && masterNodeId >= 0) {
con[id].status = ST_RECOVERED;
TRACE_IMSG(("Try to reestablish connection with master node\n"));
socket_t* s = socket_t::connect(serverURL[masterNodeId],
socket_t::sock_global_domain,
1);
if (!s->is_ok()) {
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to establish connection with master node: %s\n", buf);
delete s;
} else {
activeNodeId = masterNodeId;
addConnection(masterNodeId, s);
TRACE_IMSG(("Connection with master is restored\n"));
rr.op = ReplicationRequest::RR_RECOVERY;
rr.size = file.getUpdateCountTableSize();
rr.nodeId = id;
if (writeReq(masterNodeId, rr, file.diskUpdateCount, rr.size*sizeof(int))) {
TRACE_IMSG(("Perform recovery from master\n"));
activeNodeId = masterNodeId;
con[id].nRecoveredPages = 0;
onlineRecovery = true;
beginTransaction(dbDatabase::dbCommitLock);
} else {
dbTrace("Connection with master is lost\n");
}
}
} else {
TRACE_MSG(("Initiate change of active node %d\n", activeNodeId));
changeActiveNode();
}
} else {
rr.op = ReplicationRequest::RR_GET_STATUS;
rr.nodeId = id;
if (!writeResp(activeNodeId, rr)) {
dbTrace("Connection with active server is lost\n");
changeActiveNode();
} else {
TRACE_MSG(("Send GET_STATUS request to node %d\n", activeNodeId));
statusRequested = true;
}
}
}
} else if (rc < 0) {
#ifndef _WIN32
if (errno != EINTR)
#endif
{
dbTrace("Select failed: %d\n", errno);
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&ready);
for (int i = nInputSD; --i >= 0;) {
FD_SET(i, &ready);
if (::select(i+1, &ready, NULL, NULL, &tv) < 0) {
FD_CLR(i, &inputSD);
for (int j = nServers; --j >= 0;) {
if (j != id) {
lockConnection(j);
if ((con[j].respSock != NULL && con[j].respSock->get_handle() == i) ||
(con[j].reqSock != NULL && con[j].reqSock->get_handle() == i))
{
deleteConnection(j);
}
unlockConnection(j);
}
}
}
FD_CLR(i, &ready);
}
}
} else {
statusRequested = false;
if (FD_ISSET(acceptSock->get_handle(), &ready)) {
socket_t* s = acceptSock->accept();
if (s != NULL && s->read(&rr, sizeof rr)) {
int op = rr.op;
int nodeId = rr.nodeId;
if (op == ReplicationRequest::RR_RECOVERY) {
int* updateCountTable = new int[file.getMaxPages()];
if (rr.size != 0 && !s->read(updateCountTable, rr.size*sizeof(int))) {
dbTrace("Failed to read update counter table\n");
delete[] updateCountTable;
delete s;
} else {
cs.enter();
con[nodeId].status = ST_OFFLINE;
cs.leave();
addConnection(nodeId, s);
cs.enter();
con[nodeId].status = ST_RECOVERED;
con[nodeId].nRecoveredPages = 0;
cs.leave();
file.recovery(nodeId, updateCountTable, rr.size);
}
} else if (op != ReplicationRequest::RR_GET_STATUS) {
dbTrace("Receive unexpected request %d\n", rr.op);
delete s;
} else if (nodeId >= nServers) {
dbTrace("Receive request from node %d while master was configured only for %d nodes\n", rr.op, nServers);
delete s;
} else {
TRACE_IMSG(("Send STATUS response %s for GET_STATUS request from node %d\n",
statusText[con[id].status], nodeId));
rr.op = ReplicationRequest::RR_STATUS;
rr.nodeId = id;
rr.status = con[id].status;
rr.size = file.updateCounter;
if (!s->write(&rr, sizeof rr)) {
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to write response: %s\n", buf);
delete s;
} else {
lockConnection(nodeId);
if (con[nodeId].respSock != NULL) {
deleteConnection(nodeId);
}
{
dbCriticalSection cs(sockCS);
con[nodeId].respSock = s;
socket_handle_t hnd = s->get_handle();
if ((int)hnd >= nInputSD) {
nInputSD = (int)hnd+1;
}
FD_SET(hnd, &inputSD);
}
unlockConnection(nodeId);
}
}
} else if (s == NULL) {
acceptSock->get_error_text(buf, sizeof buf);
dbTrace("Accept failed: %s\n", buf);
} else {
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to read login request: %s\n", buf);
delete s;
}
}
for (int i = nServers; --i >= 0;) {
if (i == id) {
continue;
}
lockConnection(i);
socket_t* s;
if (((s = con[i].respSock) != NULL && FD_ISSET(s->get_handle(), &ready))
|| ((s = con[i].reqSock) != NULL && FD_ISSET(s->get_handle(), &ready)))
{
if (!s->read(&rr, sizeof rr)) {
dbTrace("Failed to read response from node %d\n", i);
deleteConnection(i);
if (closed && i == activeNodeId) {
dbCriticalSection cs(startCS);
opened = false;
startEvent.signal();
delete ctx;
unlockConnection(i);
return;
}
} else {
TRACE_MSG(("Receive request %s, status %s, size %d from node %d\n",
requestText[rr.op],
((rr.status <= ST_RECOVERED) ? statusText[rr.status] : "?"),
rr.size, rr.nodeId));
switch (rr.op) {
case ReplicationRequest::RR_COMMITTED:
{
dbCriticalSection cs(commitCS);
con[i].committedEvent.signal();
break;
}
case ReplicationRequest::RR_GET_STATUS:
rr.op = ReplicationRequest::RR_STATUS;
rr.nodeId = id;
rr.status = con[id].status;
rr.size = file.updateCounter;
TRACE_MSG(("Send RR_STATUS response %s to node %d\n",
statusText[con[id].status], i));
writeResp(i, rr);
break;
case ReplicationRequest::RR_STATUS:
if (con[rr.nodeId].status == ST_RECOVERED && rr.status == ST_STANDBY) {
if (onlineRecovery) {
monitor->curr = header->curr;
dbTrace("Online recovery of node %d is completed: recover %d pages\n", id, con[id].nRecoveredPages);
endTransaction();
onlineRecovery = false;
} else {
dbCriticalSection cs(startCS);
dbTrace("Recovery of node %d is completed: recover %d pages\n", id, con[id].nRecoveredPages);
monitor->curr = header->curr;
recoveredEvent.signal();
}
}
con[rr.nodeId].status = rr.status;
con[rr.nodeId].updateCounter = rr.size;
if (con[rr.nodeId].waitStatusEventFlag) {
con[rr.nodeId].statusEvent.signal();
} else if (activeNodeId < 0 && rr.nodeId < id && rr.status == ST_RECOVERED) {
TRACE_MSG(("activeNodeId=%d rr.nodeId=%d, rr.status=%d\n", activeNodeId, rr.nodeId, rr.status));
changeActiveNode();
}
statusRequested = false;
break;
case ReplicationRequest::RR_NEW_ACTIVE_NODE:
TRACE_MSG(("New active node is %d\n", rr.nodeId));
activeNodeId = rr.nodeId;
statusRequested = false;
break;
case ReplicationRequest::RR_CHANGE_ACTIVE_NODE:
TRACE_IMSG(("Change active node to %d\n", rr.nodeId));
masterNodeId = activeNodeId = rr.nodeId;
statusRequested = false;
rr.op = ReplicationRequest::RR_RECOVERY;
rr.size = file.getUpdateCountTableSize();
rr.nodeId = id;
writeReq(activeNodeId, rr, file.diskUpdateCount, rr.size*sizeof(int));
con[id].nRecoveredPages = 0;
con[id].status = ST_RECOVERED;
if (accessType == dbConcurrentRead) {
if (!onlineRecovery) {
onlineRecovery = true;
beginTransaction(dbDatabase::dbCommitLock);
TRACE_IMSG(("Initiate online recovery from master %d\n", activeNodeId));
} else {
TRACE_IMSG(("Recovery from master %d in progress\n", activeNodeId));
}
}
break;
case ReplicationRequest::RR_CLOSE:
if (accessType != dbConcurrentRead) {
closed = true;
}
break;
case ReplicationRequest::RR_RECOVERY:
{
TRACE_IMSG(("Receive recovery request from node %d\n", rr.nodeId));
int* updateCountTable = new int[file.getMaxPages()];
if (rr.size != 0 && !s->read(updateCountTable, rr.size*sizeof(int))) {
dbTrace("Failed to read update counter table\n");
deleteConnection(i);
delete[] updateCountTable;
} else {
con[i].status = ST_RECOVERED;
file.recovery(i, updateCountTable, rr.size);
}
break;
}
case ReplicationRequest::RR_RECOVER_PAGE:
TRACE_MSG(("Recovere page at address %x size %d\n", rr.page.offs, rr.size));
con[id].nRecoveredPages += rr.size >> dbModMapBlockBits;
if (!file.updatePages(s, rr.page.offs, rr.page.updateCount, rr.size))
{
dbTrace("Failed to recover page %lx\n", (long)rr.page.offs);
activeNodeId = -1;
}
break;
case ReplicationRequest::RR_UPDATE_PAGE:
FASTDB_ASSERT(!onlineRecovery);
TRACE_MSG(("Update page at address %x size %d\n", rr.page.offs, rr.size));
if ((accessType != dbAllAccess
&& !file.concurrentUpdatePages(s, rr.page.offs, rr.page.updateCount, rr.size))
|| (accessType == dbAllAccess
&& !file.updatePages(s, rr.page.offs, rr.page.updateCount,
rr.size)))
{
dbTrace("Failed to update page %lx\n", (long)rr.page.offs);
activeNodeId = -1;
}
break;
case ReplicationRequest::RR_READY:
con[rr.nodeId].readyEvent.signal();
break;
default:
dbTrace("Unexpected request %d from node %d\n", rr.op, i);
}
}
}
unlockConnection(i);
}
}
}
delete ctx;
}
void dbReplicatedDatabase::close0()
{
detach();
opened = false;
readerThread.join();
file.flush();
if (header != NULL && header->dirty && accessType != dbConcurrentRead)
{
header->dirty = false;
file.markAsDirty(0, sizeof(dbHeader));
file.flush(false);
}
ReplicationRequest rr;
rr.op = ReplicationRequest::RR_CLOSE;
rr.nodeId = id;
for (int i = nServers; --i >= 0;) {
if (i != id
&& con[i].reqSock != NULL
&& (con[i].status == ST_STANDBY || con[i].status == ST_RECOVERED))
{
con[i].reqSock->write(&rr, sizeof rr);
}
}
dbDatabase::close0();
delete[] con;
delete acceptSock;
startEvent.close();
}
bool dbReplicatedDatabase::writeReq(int nodeId, ReplicationRequest const& hdr,
void* body, size_t bodySize)
{
bool result;
lockConnection(nodeId);
dbCriticalSection cs(con[nodeId].writeCS);
socket_t* s = con[nodeId].reqSock;
if (s == NULL) {
s = con[nodeId].respSock;
}
if (s != NULL) {
if (!s->write(&hdr, sizeof hdr, replicationWriteTimeout/1000) ||
(bodySize != 0 && !s->write(body, bodySize, replicationWriteTimeout/1000)))
{
char buf[64];
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to write request to node %d: %s\n", nodeId, buf);
deleteConnection(nodeId);
result = false;
} else {
result = true;
}
} else {
TRACE_MSG(("Connection %d request socket is not opened\n", nodeId));
result = false;
}
unlockConnection(nodeId);
return result;
}
bool dbReplicatedDatabase::writeResp(int nodeId, ReplicationRequest const& hdr)
{
lockConnection(nodeId);
bool result;
socket_t* s = con[nodeId].respSock;
if (s == NULL) {
s = con[nodeId].reqSock;
}
if (s != NULL) {
if (!s->write(&hdr, sizeof hdr)) {
char buf[64];
s->get_error_text(buf, sizeof buf);
dbTrace("Failed to write request to node %d: %s\n", nodeId, buf);
deleteConnection(nodeId);
result = false;
} else {
result = true;
}
} else {
result = false;
}
unlockConnection(nodeId);
return result;
}
void dbReplicatedDatabase::lockConnection(int nodeId)
{
dbCriticalSection cs(sockCS);
con[nodeId].useCount += 1;
}
void dbReplicatedDatabase::unlockConnection(int nodeId)
{
dbCriticalSection cs(sockCS);
if (--con[nodeId].useCount == 0 && con[nodeId].waitUseEventFlag) {
con[nodeId].useEvent.signal();
}
}
void dbReplicatedDatabase::addConnection(int nodeId, socket_t* s)
{
TRACE_MSG(("Add connection with node %d\n", nodeId));
lockConnection(nodeId);
if (con[nodeId].reqSock != NULL) {
deleteConnection(nodeId);
}
{
dbCriticalSection cs(sockCS);
con[nodeId].reqSock = s;
socket_handle_t hnd = s->get_handle();
if ((int)hnd >= nInputSD) {
nInputSD = (int)hnd+1;
}
FD_SET(hnd, &inputSD);
}
unlockConnection(nodeId);
}
void dbReplicatedDatabase::waitTransactionAcknowledgement()
{
int i;
int n = nServers;
dbCriticalSection cs(commitCS);
for (i = 0; i < n; i++) {
con[i].committedEvent.reset();
}
file.flush();
for (i = 0; i < n; i++) {
if (con[i].status == dbReplicatedDatabase::ST_STANDBY) {
con[i].committedEvent.wait(commitCS);
}
}
}
#endif
bool dbHeader::isCompatible()
{
return getVersion() < 329 || getCurrentMode() == mode;
}
int dbHeader::getCurrentMode()
{
int mode = MODE_RECTANGLE_DIM * RECTANGLE_DIMENSION * sizeof(RECTANGLE_COORDINATE_TYPE);
#if dbDatabaseOffsetBits > 32
mode |= MODE_OFFS_64;
#endif
#if dbDatabaseOidBits > 32
mode |= MODE_OID_64;
#endif
#ifdef AUTOINCREMENT_SUPPORT
mode |= MODE_AUTOINCREMENT;
#endif
return mode;
}
END_FASTDB_NAMESPACE
| 36.655201 | 196 | 0.516181 | [
"object"
] |
245e2abca205aaa46dc286a9d47eb5794a64804d | 520 | hpp | C++ | rill/syntax_analysis/error.hpp | rhysd/rill | cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb | [
"BSL-1.0"
] | null | null | null | rill/syntax_analysis/error.hpp | rhysd/rill | cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb | [
"BSL-1.0"
] | null | null | null | rill/syntax_analysis/error.hpp | rhysd/rill | cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb | [
"BSL-1.0"
] | null | null | null | //
// Copyright yutopp 2013 - .
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef RILL_SYNTAX_ANALYSIS_ERROR_HPP
#define RILL_SYNTAX_ANALYSIS_ERROR_HPP
#include <vector>
namespace rill
{
namespace syntax_analysis
{
// TODO: fix me
using error_container = std::vector<int/* dummy */>;
} // namespace sytax_analysis
} // rill
#endif /*RILL_SYNTAX_ANALYSIS_ERROR_HPP*/
| 20 | 61 | 0.705769 | [
"vector"
] |
245f130b61fa676638f2778ee6b0fefe9dc75cf6 | 12,620 | cpp | C++ | admin/activec/samples/pdc/step4/dataobj.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/activec/samples/pdc/step4/dataobj.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/activec/samples/pdc/step4/dataobj.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // This is a part of the Microsoft Management Console.
// Copyright 1995 - 1997 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Management Console and related
// electronic documentation provided with the interfaces.
#include "stdafx.h"
#include "Service.h"
#include "CSnapin.h"
#include "DataObj.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
///////////////////////////////////////////////////////////////////////////////
// Sample code to show how to Create DataObjects
// Minimal error checking for clarity
///////////////////////////////////////////////////////////////////////////////
// Snap-in NodeType in both GUID format and string format
// Note - Typically there is a node type for each different object, sample
// only uses one node type.
unsigned int CDataObject::m_cfNodeType = 0;
unsigned int CDataObject::m_cfNodeTypeString = 0;
unsigned int CDataObject::m_cfDisplayName = 0;
unsigned int CDataObject::m_cfCoClass = 0;
unsigned int CDataObject::m_cfNodeID = 0;
unsigned int CDataObject::m_cfInternal = 0;
unsigned int CDataObject::m_cfMultiSel = 0;
// Extension information
// The only additional clipboard format supported is to get the workstation name.
unsigned int CDataObject::m_cfWorkstation = 0;
/////////////////////////////////////////////////////////////////////////////
// CDataObject implementations
CDataObject::CDataObject()
{
USES_CONVERSION;
m_cfNodeType = RegisterClipboardFormat(W2T(CCF_NODETYPE));
m_cfNodeTypeString = RegisterClipboardFormat(W2T(CCF_SZNODETYPE));
m_cfDisplayName = RegisterClipboardFormat(W2T(CCF_DISPLAY_NAME));
m_cfCoClass = RegisterClipboardFormat(W2T(CCF_SNAPIN_CLASSID));
m_cfMultiSel = RegisterClipboardFormat(W2T(CCF_OBJECT_TYPES_IN_MULTI_SELECT));
m_cfNodeID = RegisterClipboardFormat(W2T(CCF_NODEID));
#ifdef UNICODE
m_cfInternal = RegisterClipboardFormat(W2T((LPTSTR)SNAPIN_INTERNAL));
m_cfWorkstation = RegisterClipboardFormat(W2T((LPTSTR)SNAPIN_WORKSTATION));
#else
m_cfInternal = RegisterClipboardFormat(W2T(SNAPIN_INTERNAL));
m_cfWorkstation = RegisterClipboardFormat(W2T(SNAPIN_WORKSTATION));
#endif //UNICODE
#ifdef _DEBUG
m_ComponentData = NULL;
dbg_refCount = 0;
#endif
m_pbMultiSelData = 0;
m_cbMultiSelData = 0;
m_bMultiSelDobj = FALSE;
}
STDMETHODIMP CDataObject::GetData(LPFORMATETC lpFormatetc, LPSTGMEDIUM lpMedium)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
HRESULT hr = DV_E_CLIPFORMAT;
const CLIPFORMAT cf = lpFormatetc->cfFormat;
if (cf == m_cfMultiSel)
{
ASSERT(m_internal.m_cookie == MMC_MULTI_SELECT_COOKIE);
if (m_internal.m_cookie != MMC_MULTI_SELECT_COOKIE)
return E_FAIL;
//return CreateMultiSelData(lpMedium);
ASSERT(m_pbMultiSelData != 0);
ASSERT(m_cbMultiSelData != 0);
lpMedium->tymed = TYMED_HGLOBAL;
lpMedium->hGlobal = ::GlobalAlloc(GMEM_SHARE|GMEM_MOVEABLE,
(m_cbMultiSelData + sizeof(DWORD)));
if (lpMedium->hGlobal == NULL)
return STG_E_MEDIUMFULL;
BYTE* pb = reinterpret_cast<BYTE*>(::GlobalLock(lpMedium->hGlobal));
*((DWORD*)pb) = m_cbMultiSelData / sizeof(GUID);
pb += sizeof(DWORD);
CopyMemory(pb, m_pbMultiSelData, m_cbMultiSelData);
::GlobalUnlock(lpMedium->hGlobal);
hr = S_OK;
}
#ifdef RECURSIVE_NODE_EXPANSION
else if (cf == m_cfNodeID)
{
// Create the node type object in GUID format
BYTE byData[256] = {0};
SNodeID* pData = reinterpret_cast<SNodeID*>(byData);
LPCTSTR pszText;
if (m_internal.m_cookie == NULL)
{
return (E_FAIL);
}
else if (m_internal.m_type == CCT_SCOPE)
{
CFolder* pFolder = reinterpret_cast<CFolder*>(m_internal.m_cookie);
ASSERT(pFolder != NULL);
if (pFolder == NULL)
return E_UNEXPECTED;
switch (pFolder->GetType())
{
// save the user node as a custom node ID
case USER:
pszText = _T("___Custom ID for User Data node___");
break;
// save the company node as a string
case COMPANY:
return (E_FAIL);
break;
// truncate anything below a virtual node
case VIRTUAL:
pszText = _T("");
break;
case EXT_USER:
case EXT_COMPANY:
case EXT_VIRTUAL:
default:
return (E_FAIL);
break;
}
}
else if (m_internal.m_type == CCT_RESULT)
{
return (E_FAIL);
}
_tcscpy ((LPTSTR) pData->id, pszText);
pData->cBytes = _tcslen ((LPTSTR) pData->id) * sizeof (TCHAR);
int cb = pData->cBytes + sizeof (pData->cBytes);
lpMedium->tymed = TYMED_HGLOBAL;
lpMedium->hGlobal = ::GlobalAlloc(GMEM_SHARE|GMEM_MOVEABLE, cb);
if (lpMedium->hGlobal == NULL)
return STG_E_MEDIUMFULL;
BYTE* pb = reinterpret_cast<BYTE*>(::GlobalLock(lpMedium->hGlobal));
CopyMemory(pb, pData, cb);
::GlobalUnlock(lpMedium->hGlobal);
hr = S_OK;
}
#endif /* RECURSIVE_NODE_EXPANSION */
return hr;
}
STDMETHODIMP CDataObject::GetDataHere(LPFORMATETC lpFormatetc, LPSTGMEDIUM lpMedium)
{
HRESULT hr = DV_E_CLIPFORMAT;
AFX_MANAGE_STATE(AfxGetStaticModuleState());
// Based on the CLIPFORMAT write data to the stream
const CLIPFORMAT cf = lpFormatetc->cfFormat;
if (cf == m_cfNodeType)
{
hr = CreateNodeTypeData(lpMedium);
}
else if (cf == m_cfCoClass)
{
hr = CreateCoClassID(lpMedium);
}
else if(cf == m_cfNodeTypeString)
{
hr = CreateNodeTypeStringData(lpMedium);
}
else if (cf == m_cfDisplayName)
{
hr = CreateDisplayName(lpMedium);
}
else if (cf == m_cfInternal)
{
hr = CreateInternal(lpMedium);
}
else if (cf == m_cfWorkstation)
{
hr = CreateWorkstationName(lpMedium);
}
return hr;
}
STDMETHODIMP CDataObject::EnumFormatEtc(DWORD dwDirection, LPENUMFORMATETC* ppEnumFormatEtc)
{
return E_NOTIMPL;
}
/////////////////////////////////////////////////////////////////////////////
// CDataObject creation members
HRESULT CDataObject::Create(const void* pBuffer, int len, LPSTGMEDIUM lpMedium)
{
HRESULT hr = DV_E_TYMED;
// Do some simple validation
if (pBuffer == NULL || lpMedium == NULL)
return E_POINTER;
// Make sure the type medium is HGLOBAL
if (lpMedium->tymed == TYMED_HGLOBAL)
{
// Create the stream on the hGlobal passed in
LPSTREAM lpStream;
hr = CreateStreamOnHGlobal(lpMedium->hGlobal, FALSE, &lpStream);
if (SUCCEEDED(hr))
{
// Write to the stream the number of bytes
unsigned long written;
hr = lpStream->Write(pBuffer, len, &written);
// Because we told CreateStreamOnHGlobal with 'FALSE',
// only the stream is released here.
// Note - the caller (i.e. snap-in, object) will free the HGLOBAL
// at the correct time. This is according to the IDataObject specification.
lpStream->Release();
}
}
return hr;
}
HRESULT CDataObject::CreateMultiSelData(LPSTGMEDIUM lpMedium)
{
ASSERT(m_internal.m_cookie == MMC_MULTI_SELECT_COOKIE);
ASSERT(m_pbMultiSelData != 0);
ASSERT(m_cbMultiSelData != 0);
return Create(reinterpret_cast<const void*>(m_pbMultiSelData),
m_cbMultiSelData, lpMedium);
}
HRESULT CDataObject::CreateNodeTypeData(LPSTGMEDIUM lpMedium)
{
// Create the node type object in GUID format
const GUID* pcObjectType = NULL;
if (m_internal.m_cookie == NULL)
{
pcObjectType = &cNodeTypeStatic;
}
else if (m_internal.m_type == CCT_SCOPE)
{
CFolder* pFolder = reinterpret_cast<CFolder*>(m_internal.m_cookie);
ASSERT(pFolder != NULL);
if (pFolder == NULL)
return E_UNEXPECTED;
switch (pFolder->GetType())
{
case COMPANY:
pcObjectType = &cNodeTypeCompany;
break;
case USER:
pcObjectType = &cNodeTypeUser;
break;
case EXT_COMPANY:
pcObjectType = &cNodeTypeExtCompany;
break;
case EXT_USER:
pcObjectType = &cNodeTypeExtUser;
break;
case VIRTUAL:
case EXT_VIRTUAL:
pcObjectType = &cNodeTypeExtUser;
break;
default:
pcObjectType = &cNodeTypeDynamic;
break;
}
}
else if (m_internal.m_type == CCT_RESULT)
{
// RESULT_DATA* pData = reinterpret_cast<RESULT_DATA*>(m_internal.m_cookie);
pcObjectType = &cObjectTypeResultItem;
}
return Create(reinterpret_cast<const void*>(pcObjectType), sizeof(GUID),
lpMedium);
}
HRESULT CDataObject::CreateNodeTypeStringData(LPSTGMEDIUM lpMedium)
{
// Create the node type object in GUID string format
const WCHAR* cszObjectType = NULL;
if (m_internal.m_cookie == NULL)
{
cszObjectType = cszNodeTypeStatic;
}
else if (m_internal.m_type == CCT_SCOPE)
{
CFolder* pFolder = reinterpret_cast<CFolder*>(m_internal.m_cookie);
ASSERT(pFolder != NULL);
if (pFolder == NULL)
return E_UNEXPECTED;
switch (pFolder->GetType())
{
case COMPANY:
cszObjectType = cszNodeTypeCompany;
break;
case USER:
cszObjectType = cszNodeTypeUser;
break;
case EXT_COMPANY:
cszObjectType = cszNodeTypeExtCompany;
break;
case EXT_USER:
cszObjectType = cszNodeTypeExtUser;
break;
default:
cszObjectType = cszNodeTypeDynamic;
break;
}
}
else if (m_internal.m_type == CCT_RESULT)
{
// RESULT_DATA* pData = reinterpret_cast<RESULT_DATA*>(m_internal.m_cookie);
cszObjectType = cszObjectTypeResultItem;
}
return Create(cszObjectType, ((wcslen(cszObjectType)+1) * sizeof(WCHAR)), lpMedium);
}
HRESULT CDataObject::CreateDisplayName(LPSTGMEDIUM lpMedium)
{
// This is the display named used in the scope pane and snap-in manager
// Load the name from resource
// Note - if this is not provided, the console will used the snap-in name
CString szDispName;
szDispName.LoadString(IDS_NODENAME);
USES_CONVERSION;
#ifdef UNICODE
return Create(szDispName, ((szDispName.GetLength()+1) * sizeof(WCHAR)), lpMedium);
#else
return Create(T2W(szDispName), ((szDispName.GetLength()+1) * sizeof(WCHAR)), lpMedium);
#endif
}
HRESULT CDataObject::CreateInternal(LPSTGMEDIUM lpMedium)
{
return Create(&m_internal, sizeof(INTERNAL), lpMedium);
}
HRESULT CDataObject::CreateWorkstationName(LPSTGMEDIUM lpMedium)
{
TCHAR pzName[MAX_COMPUTERNAME_LENGTH+1] = {0};
DWORD len = MAX_COMPUTERNAME_LENGTH+1;
if (GetComputerName(pzName, &len) == FALSE)
return E_FAIL;
// Add 1 for the NULL and calculate the bytes for the stream
//#ifdef UNICODE
USES_CONVERSION;
return Create(T2W(pzName), ((len+1)* sizeof(WCHAR)), lpMedium);
//#else
// return Create(pzName, ((len+1)* sizeof(WCHAR)), lpMedium);
//#endif
}
HRESULT CDataObject::CreateCoClassID(LPSTGMEDIUM lpMedium)
{
// Create the CoClass information
return Create(reinterpret_cast<const void*>(&m_internal.m_clsid), sizeof(CLSID), lpMedium);
} | 29.834515 | 96 | 0.584707 | [
"object"
] |
245fde16485aceef9ac365ebba10c1838102b454 | 1,276 | hpp | C++ | lab6/include/stockDBDoublyLL.hpp | samruddhi221/cpp_codes | 055e4902addef2e7280e938db5901a4927e7b2d2 | [
"MIT"
] | null | null | null | lab6/include/stockDBDoublyLL.hpp | samruddhi221/cpp_codes | 055e4902addef2e7280e938db5901a4927e7b2d2 | [
"MIT"
] | null | null | null | lab6/include/stockDBDoublyLL.hpp | samruddhi221/cpp_codes | 055e4902addef2e7280e938db5901a4927e7b2d2 | [
"MIT"
] | 1 | 2019-11-02T02:24:04.000Z | 2019-11-02T02:24:04.000Z | #ifndef STOCKDBDOUBLYLL_HPP
#define STOCKDBDOUBLYLL_HPP
#include "stockNodeDLL.hpp"
#define DEBUG_LINE std::cout << __LINE__ << std::endl;
class StockDBDoublyLL:public StockNodeDLL
{
public:
/**
* @brief members
*
*/
StockNodeDLL* m_head;
StockNodeDLL* m_tail;
int m_size;
enum class DIRECTION
{
FORWARD,
REVERSE
};
/**
* @brief Construct a new Stock D B Doubly L L object
*
*/
StockDBDoublyLL();
/**
* @brief Construct a new StockDB Doubly LL object
*
* @param node
*/
StockDBDoublyLL(StockNodeDLL* node);
/**
* @brief Destroy the Stock DB Doubly LL object
*
*/
~StockDBDoublyLL();
/**
* @brief append a node to a linked list
*
* @param node
*/
void appendNodeDLL(StockNodeDLL* node);
/**
* @brief insert a node in a doubly linked list
*
*/
void insertNodeDLL(StockNodeDLL* node, int position);
/**
* @brief delete a node from a doubly linkedlist
*
*/
void deleteNodeDLL(int position);
/**
* @brief display linked list in forward or reverse manner
*
* @param orientation
*/
void display(StockDBDoublyLL::DIRECTION orientation);
/**
* @brief find the middle node of a linkedlist
*
* @return StockNodeDLL*
*/
StockNodeDLL* findMiddle();
};
#endif | 16.151899 | 58 | 0.65047 | [
"object"
] |
2460fd073aceddd02fd5bcbb3fc3de0a0b30d4f6 | 1,739 | hpp | C++ | common/core/desktop/src/debug.hpp | srl295/keyman | 4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1 | [
"MIT"
] | 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | common/core/desktop/src/debug.hpp | srl295/keyman | 4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1 | [
"MIT"
] | 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | common/core/desktop/src/debug.hpp | srl295/keyman | 4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1 | [
"MIT"
] | 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | /*
* Keyman is copyright (C) SIL International. MIT License.
*
* Keyman Core - Debug class definition
*/
#pragma once
#include <cassert>
#include <vector>
#include <keyman/keyboardprocessor.h>
#include <keyman/keyboardprocessor_debug.h>
namespace km {
namespace kbp
{
class debug_items : public std::vector<km_kbp_state_debug_item>
{
private:
bool _is_enabled;
public:
template<typename... Args> debug_items(Args&&... args);
void push_begin(km_kbp_state_debug_key_info *key_info, uint32_t flags);
void push_end(uint16_t first_action, uint32_t flags);
void assert_push_entry();
bool is_enabled() const noexcept;
void set_enabled(bool value) noexcept;
};
template<typename... Args>
debug_items::debug_items(Args&&... args)
: std::vector<km_kbp_state_debug_item>(std::forward<Args>(args)...)
{
// Ensure the debug_items list is terminated in case the client calls
// km_kbp_state_debug_items before they call process_event.
_is_enabled = false;
push_end(0, 0);
}
inline
void debug_items::assert_push_entry() {
assert(empty() || (!empty() && back().type != KM_KBP_DEBUG_END));
}
inline
void debug_items::push_begin(km_kbp_state_debug_key_info *key_info, uint32_t flags) {
assert_push_entry();
emplace_back(km_kbp_state_debug_item{ KM_KBP_DEBUG_BEGIN, flags, {*key_info, } });
}
inline
void debug_items::push_end(uint16_t first_action, uint32_t flags) {
assert_push_entry();
emplace_back(km_kbp_state_debug_item{ KM_KBP_DEBUG_END, flags, { }, { u"", nullptr, nullptr, { }, first_action } });
}
inline
bool debug_items::is_enabled() const noexcept {
return _is_enabled;
}
inline
void debug_items::set_enabled(bool value) noexcept {
_is_enabled = value;
}
} // namespace kbp
} // namespace km
| 24.152778 | 118 | 0.744106 | [
"vector"
] |
2462437313d8c7be13072f719b47d4ba219bb64f | 52,322 | cpp | C++ | src/kits/storage/PathMonitor.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2017-06-17T22:03:56.000Z | 2019-01-25T10:51:55.000Z | src/kits/storage/PathMonitor.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/kits/storage/PathMonitor.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | /*
* Copyright 2007-2013, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Axel Dörfler, axeld@pinc-software.de
* Stephan Aßmus, superstippi@gmx.de
* Ingo Weinhold, ingo_weinhold@gmx.de
*/
#include <PathMonitor.h>
#include <pthread.h>
#include <stdio.h>
#include <Autolock.h>
#include <Directory.h>
#include <Entry.h>
#include <Handler.h>
#include <Locker.h>
#include <Looper.h>
#include <Path.h>
#include <String.h>
#include <AutoDeleter.h>
#include <NotOwningEntryRef.h>
#include <ObjectList.h>
#include <util/OpenHashTable.h>
#include <util/SinglyLinkedList.h>
#undef TRACE
//#define TRACE_PATH_MONITOR
#ifdef TRACE_PATH_MONITOR
# define TRACE(...) debug_printf("BPathMonitor: " __VA_ARGS__)
#else
# define TRACE(...) ;
#endif
// TODO: Support symlink components in the path.
// TODO: Support mounting/unmounting of volumes in path components and within
// the watched path tree.
#define WATCH_NODE_FLAG_MASK 0x00ff
namespace {
struct Directory;
struct Node;
struct WatcherHashDefinition;
typedef BOpenHashTable<WatcherHashDefinition> WatcherMap;
static pthread_once_t sInitOnce = PTHREAD_ONCE_INIT;
static WatcherMap* sWatchers = NULL;
static BLooper* sLooper = NULL;
static BPathMonitor::BWatchingInterface* sDefaultWatchingInterface = NULL;
static BPathMonitor::BWatchingInterface* sWatchingInterface = NULL;
// #pragma mark -
/*! Returns empty path, if either \a parent or \a subPath is empty or an
allocation fails.
*/
static BString
make_path(const BString& parent, const char* subPath)
{
BString path = parent;
int32 length = path.Length();
if (length == 0 || subPath[0] == '\0')
return BString();
if (parent.ByteAt(length - 1) != '/') {
path << '/';
if (path.Length() < ++length)
return BString();
}
path << subPath;
if (path.Length() <= length)
return BString();
return path;
}
// #pragma mark - Ancestor
class Ancestor {
public:
Ancestor(Ancestor* parent, const BString& path, size_t pathComponentOffset)
:
fParent(parent),
fChild(NULL),
fPath(path),
fEntryRef(-1, -1, fPath.String() + pathComponentOffset),
fNodeRef(),
fWatchingFlags(0),
fIsDirectory(false)
{
if (pathComponentOffset == 0) {
// must be "/"
fEntryRef.SetTo(-1, -1, ".");
}
if (fParent != NULL)
fParent->fChild = this;
}
Ancestor* Parent() const
{
return fParent;
}
Ancestor* Child() const
{
return fChild;
}
const BString& Path() const
{
return fPath;
}
const char* Name() const
{
return fEntryRef.name;
}
bool Exists() const
{
return fNodeRef.device >= 0;
}
const NotOwningEntryRef& EntryRef() const
{
return fEntryRef;
}
const node_ref& NodeRef() const
{
return fNodeRef;
}
bool IsDirectory() const
{
return fIsDirectory;
}
status_t StartWatching(uint32 pathFlags, BHandler* target)
{
// init entry ref
BEntry entry;
status_t error = entry.SetTo(fPath);
if (error != B_OK)
return error;
entry_ref entryRef;
error = entry.GetRef(&entryRef);
if (error != B_OK)
return error;
fEntryRef.device = entryRef.device;
fEntryRef.directory = entryRef.directory;
// init node ref
struct stat st;
error = entry.GetStat(&st);
if (error != B_OK)
return error == B_ENTRY_NOT_FOUND ? B_OK : error;
fNodeRef = node_ref(st.st_dev, st.st_ino);
fIsDirectory = S_ISDIR(st.st_mode);
// start watching
uint32 flags = fChild == NULL ? pathFlags : B_WATCH_DIRECTORY;
// In theory B_WATCH_NAME would suffice for all existing ancestors,
// plus B_WATCH_DIRECTORY for the parent of the first not existing
// ancestor. In practice this complicates the transitions when an
// ancestor is created/removed/moved.
if (flags != 0) {
error = sWatchingInterface->WatchNode(&fNodeRef, flags, target);
TRACE(" started to watch ancestor %p (\"%s\", %#" B_PRIx32
") -> %s\n", this, Name(), flags, strerror(error));
if (error != B_OK)
return error;
}
fWatchingFlags = flags;
return B_OK;
}
void StopWatching(BHandler* target)
{
// stop watching
if (fWatchingFlags != 0) {
sWatchingInterface->WatchNode(&fNodeRef, B_STOP_WATCHING, target);
fWatchingFlags = 0;
}
// uninitialize node and entry ref
fIsDirectory = false;
fNodeRef = node_ref();
fEntryRef.SetDirectoryNodeRef(node_ref());
}
Ancestor*& HashNext()
{
return fHashNext;
}
private:
Ancestor* fParent;
Ancestor* fChild;
Ancestor* fHashNext;
BString fPath;
NotOwningEntryRef fEntryRef;
node_ref fNodeRef;
uint32 fWatchingFlags;
bool fIsDirectory;
};
// #pragma mark - AncestorMap
struct AncestorHashDefinition {
typedef node_ref KeyType;
typedef Ancestor ValueType;
size_t HashKey(const node_ref& key) const
{
return size_t(key.device ^ key.node);
}
size_t Hash(Ancestor* value) const
{
return HashKey(value->NodeRef());
}
bool Compare(const node_ref& key, Ancestor* value) const
{
return key == value->NodeRef();
}
Ancestor*& GetLink(Ancestor* value) const
{
return value->HashNext();
}
};
typedef BOpenHashTable<AncestorHashDefinition> AncestorMap;
// #pragma mark - Entry
class Entry : public SinglyLinkedListLinkImpl<Entry> {
public:
Entry(Directory* parent, const BString& name, ::Node* node)
:
fParent(parent),
fName(name),
fNode(node)
{
}
Directory* Parent() const
{
return fParent;
}
const BString& Name() const
{
return fName;
}
::Node* Node() const
{
return fNode;
}
void SetNode(::Node* node)
{
fNode = node;
}
inline NotOwningEntryRef EntryRef() const;
Entry*& HashNext()
{
return fHashNext;
}
private:
Directory* fParent;
BString fName;
::Node* fNode;
Entry* fHashNext;
};
typedef SinglyLinkedList<Entry> EntryList;
// EntryMap
struct EntryHashDefinition {
typedef const char* KeyType;
typedef Entry ValueType;
size_t HashKey(const char* key) const
{
return BString::HashValue(key);
}
size_t Hash(Entry* value) const
{
return value->Name().HashValue();
}
bool Compare(const char* key, Entry* value) const
{
return value->Name() == key;
}
Entry*& GetLink(Entry* value) const
{
return value->HashNext();
}
};
typedef BOpenHashTable<EntryHashDefinition> EntryMap;
// #pragma mark - Node
class Node {
public:
Node(const node_ref& nodeRef)
:
fNodeRef(nodeRef)
{
}
virtual ~Node()
{
}
virtual bool IsDirectory() const
{
return false;
}
virtual Directory* ToDirectory()
{
return NULL;
}
const node_ref& NodeRef() const
{
return fNodeRef;
}
const EntryList& Entries() const
{
return fEntries;
}
bool HasEntries() const
{
return !fEntries.IsEmpty();
}
Entry* FirstNodeEntry() const
{
return fEntries.Head();
}
bool IsOnlyNodeEntry(Entry* entry) const
{
return entry == fEntries.Head() && fEntries.GetNext(entry) == NULL;
}
void AddNodeEntry(Entry* entry)
{
fEntries.Add(entry);
}
void RemoveNodeEntry(Entry* entry)
{
fEntries.Remove(entry);
}
Node*& HashNext()
{
return fHashNext;
}
private:
node_ref fNodeRef;
EntryList fEntries;
Node* fHashNext;
};
struct NodeHashDefinition {
typedef node_ref KeyType;
typedef Node ValueType;
size_t HashKey(const node_ref& key) const
{
return size_t(key.device ^ key.node);
}
size_t Hash(Node* value) const
{
return HashKey(value->NodeRef());
}
bool Compare(const node_ref& key, Node* value) const
{
return key == value->NodeRef();
}
Node*& GetLink(Node* value) const
{
return value->HashNext();
}
};
typedef BOpenHashTable<NodeHashDefinition> NodeMap;
// #pragma mark - Directory
class Directory : public Node {
public:
static Directory* Create(const node_ref& nodeRef)
{
Directory* directory = new(std::nothrow) Directory(nodeRef);
if (directory == NULL || directory->fEntries.Init() != B_OK) {
delete directory;
return NULL;
}
return directory;
}
virtual bool IsDirectory() const
{
return true;
}
virtual Directory* ToDirectory()
{
return this;
}
Entry* FindEntry(const char* name) const
{
return fEntries.Lookup(name);
}
Entry* CreateEntry(const BString& name, Node* node)
{
Entry* entry = new(std::nothrow) Entry(this, name, node);
if (entry == NULL || entry->Name().IsEmpty()) {
delete entry;
return NULL;
}
AddEntry(entry);
return entry;
}
void AddEntry(Entry* entry)
{
fEntries.Insert(entry);
}
void RemoveEntry(Entry* entry)
{
fEntries.Remove(entry);
}
EntryMap::Iterator GetEntryIterator() const
{
return fEntries.GetIterator();
}
Entry* RemoveAllEntries()
{
return fEntries.Clear(true);
}
private:
Directory(const node_ref& nodeRef)
:
Node(nodeRef)
{
}
private:
EntryMap fEntries;
};
// #pragma mark - Entry
inline NotOwningEntryRef
Entry::EntryRef() const
{
return NotOwningEntryRef(fParent->NodeRef(), fName);
}
// #pragma mark - PathHandler
class PathHandler : public BHandler {
public:
PathHandler(const char* path, uint32 flags,
const BMessenger& target, BLooper* looper);
virtual ~PathHandler();
status_t InitCheck() const;
void Quit();
const BString& OriginalPath() const
{ return fOriginalPath; }
uint32 Flags() const { return fFlags; }
virtual void MessageReceived(BMessage* message);
PathHandler*& HashNext() { return fHashNext; }
private:
status_t _CreateAncestors();
status_t _StartWatchingAncestors(Ancestor* ancestor,
bool notify);
void _StopWatchingAncestors(Ancestor* ancestor,
bool notify);
void _EntryCreated(BMessage* message);
void _EntryRemoved(BMessage* message);
void _EntryMoved(BMessage* message);
void _NodeChanged(BMessage* message);
bool _EntryCreated(const NotOwningEntryRef& entryRef,
const node_ref& nodeRef, bool isDirectory,
bool dryRun, bool notify, Entry** _entry);
bool _EntryRemoved(const NotOwningEntryRef& entryRef,
const node_ref& nodeRef, bool dryRun,
bool notify, Entry** _keepEntry);
bool _CheckDuplicateEntryNotification(int32 opcode,
const entry_ref& toEntryRef,
const node_ref& nodeRef,
const entry_ref* fromEntryRef = NULL);
void _UnsetDuplicateEntryNotification();
Ancestor* _GetAncestor(const node_ref& nodeRef) const;
status_t _AddNode(const node_ref& nodeRef,
bool isDirectory, bool notify,
Entry* entry = NULL, Node** _node = NULL);
void _DeleteNode(Node* node, bool notify);
Node* _GetNode(const node_ref& nodeRef) const;
status_t _AddEntryIfNeeded(Directory* directory,
const char* name, const node_ref& nodeRef,
bool isDirectory, bool notify,
Entry** _entry = NULL);
void _DeleteEntry(Entry* entry, bool notify);
void _DeleteEntryAlreadyRemovedFromParent(
Entry* entry, bool notify);
void _NotifyFilesCreatedOrRemoved(Entry* entry,
int32 opcode) const;
void _NotifyEntryCreatedOrRemoved(Entry* entry,
int32 opcode) const;
void _NotifyEntryCreatedOrRemoved(
const entry_ref& entryRef,
const node_ref& nodeRef, const char* path,
bool isDirectory, int32 opcode) const;
void _NotifyEntryMoved(const entry_ref& fromEntryRef,
const entry_ref& toEntryRef,
const node_ref& nodeRef,
const char* fromPath, const char* path,
bool isDirectory, bool wasAdded,
bool wasRemoved) const;
void _NotifyTarget(BMessage& message,
const char* path) const;
BString _NodePath(const Node* node) const;
BString _EntryPath(const Entry* entry) const;
bool _WatchRecursively() const;
bool _WatchFilesOnly() const;
bool _WatchDirectoriesOnly() const;
private:
BMessenger fTarget;
uint32 fFlags;
status_t fStatus;
BString fOriginalPath;
BString fPath;
Ancestor* fRoot;
Ancestor* fBaseAncestor;
Node* fBaseNode;
AncestorMap fAncestors;
NodeMap fNodes;
PathHandler* fHashNext;
int32 fDuplicateEntryNotificationOpcode;
node_ref fDuplicateEntryNotificationNodeRef;
entry_ref fDuplicateEntryNotificationToEntryRef;
entry_ref fDuplicateEntryNotificationFromEntryRef;
};
struct PathHandlerHashDefinition {
typedef const char* KeyType;
typedef PathHandler ValueType;
size_t HashKey(const char* key) const
{
return BString::HashValue(key);
}
size_t Hash(PathHandler* value) const
{
return value->OriginalPath().HashValue();
}
bool Compare(const char* key, PathHandler* value) const
{
return key == value->OriginalPath();
}
PathHandler*& GetLink(PathHandler* value) const
{
return value->HashNext();
}
};
typedef BOpenHashTable<PathHandlerHashDefinition> PathHandlerMap;
// #pragma mark - Watcher
struct Watcher : public PathHandlerMap {
static Watcher* Create(const BMessenger& target)
{
Watcher* watcher = new(std::nothrow) Watcher(target);
if (watcher == NULL || watcher->Init() != B_OK) {
delete watcher;
return NULL;
}
return watcher;
}
const BMessenger& Target() const
{
return fTarget;
}
Watcher*& HashNext()
{
return fHashNext;
}
private:
Watcher(const BMessenger& target)
:
fTarget(target)
{
}
private:
BMessenger fTarget;
Watcher* fHashNext;
};
struct WatcherHashDefinition {
typedef BMessenger KeyType;
typedef Watcher ValueType;
size_t HashKey(const BMessenger& key) const
{
return key.HashValue();
}
size_t Hash(Watcher* value) const
{
return HashKey(value->Target());
}
bool Compare(const BMessenger& key, Watcher* value) const
{
return key == value->Target();
}
Watcher*& GetLink(Watcher* value) const
{
return value->HashNext();
}
};
// #pragma mark - PathHandler
PathHandler::PathHandler(const char* path, uint32 flags,
const BMessenger& target, BLooper* looper)
:
BHandler(path),
fTarget(target),
fFlags(flags),
fStatus(B_OK),
fOriginalPath(path),
fPath(),
fRoot(NULL),
fBaseAncestor(NULL),
fBaseNode(NULL),
fAncestors(),
fNodes()
{
TRACE("%p->PathHandler::PathHandler(\"%s\", %#" B_PRIx32 ")\n", this, path,
flags);
_UnsetDuplicateEntryNotification();
fStatus = fAncestors.Init();
if (fStatus != B_OK)
return;
fStatus = fNodes.Init();
if (fStatus != B_OK)
return;
// normalize the flags
if ((fFlags & B_WATCH_RECURSIVELY) != 0) {
// We add B_WATCH_NAME and B_WATCH_DIRECTORY as needed, so clear them
// here.
fFlags &= ~uint32(B_WATCH_NAME | B_WATCH_DIRECTORY);
} else {
// The B_WATCH_*_ONLY flags are only valid for the recursive mode.
// B_WATCH_NAME is implied (we watch the parent directory).
fFlags &= ~uint32(B_WATCH_FILES_ONLY | B_WATCH_DIRECTORIES_ONLY
| B_WATCH_NAME);
}
// Normalize the path a bit. We can't use BPath, as it may really normalize
// the path, i.e. resolve symlinks and such, which may cause us to monitor
// the wrong path. We want some normalization, though:
// * relative -> absolute path
// * fold duplicate '/'s
// * omit "." components
// * fail when encountering ".." components
// make absolute
BString normalizedPath;
if (path[0] == '/') {
normalizedPath = "/";
path++;
} else
normalizedPath = BPath(".").Path();
if (normalizedPath.IsEmpty()) {
fStatus = B_NO_MEMORY;
return;
}
// parse path components
const char* pathEnd = path + strlen(path);
for (;;) {
// skip '/'s
while (path[0] == '/')
path++;
if (path == pathEnd)
break;
const char* componentEnd = strchr(path, '/');
if (componentEnd == NULL)
componentEnd = pathEnd;
size_t componentLength = componentEnd - path;
// handle ".' and ".."
if (path[0] == '.') {
if (componentLength == 1) {
path = componentEnd;
continue;
}
if (componentLength == 2 && path[1] == '.') {
fStatus = B_BAD_VALUE;
return;
}
}
int32 normalizedPathLength = normalizedPath.Length();
if (normalizedPath.ByteAt(normalizedPathLength - 1) != '/') {
normalizedPath << '/';
normalizedPathLength++;
}
normalizedPath.Append(path, componentEnd - path);
normalizedPathLength += int32(componentEnd - path);
if (normalizedPath.Length() != normalizedPathLength) {
fStatus = B_NO_MEMORY;
return;
}
path = componentEnd;
}
fPath = normalizedPath;
// Create the Ancestor objects -- they correspond to the path components and
// are used for watching changes that affect the entries on the path.
fStatus = _CreateAncestors();
if (fStatus != B_OK)
return;
// add ourselves to the looper
looper->AddHandler(this);
// start watching
fStatus = _StartWatchingAncestors(fRoot, false);
if (fStatus != B_OK)
return;
}
PathHandler::~PathHandler()
{
TRACE("%p->PathHandler::~PathHandler(\"%s\", %#" B_PRIx32 ")\n", this,
fPath.String(), fFlags);
if (fBaseNode != NULL)
_DeleteNode(fBaseNode, false);
while (fRoot != NULL) {
Ancestor* nextAncestor = fRoot->Child();
delete fRoot;
fRoot = nextAncestor;
}
}
status_t
PathHandler::InitCheck() const
{
return fStatus;
}
void
PathHandler::Quit()
{
TRACE("%p->PathHandler::Quit()\n", this);
sWatchingInterface->StopWatching(this);
sLooper->RemoveHandler(this);
delete this;
}
void
PathHandler::MessageReceived(BMessage* message)
{
switch (message->what) {
case B_NODE_MONITOR:
{
int32 opcode;
if (message->FindInt32("opcode", &opcode) != B_OK)
return;
switch (opcode) {
case B_ENTRY_CREATED:
_EntryCreated(message);
break;
case B_ENTRY_REMOVED:
_EntryRemoved(message);
break;
case B_ENTRY_MOVED:
_EntryMoved(message);
break;
default:
_UnsetDuplicateEntryNotification();
_NodeChanged(message);
break;
}
break;
}
default:
BHandler::MessageReceived(message);
break;
}
}
status_t
PathHandler::_CreateAncestors()
{
TRACE("%p->PathHandler::_CreateAncestors()\n", this);
// create the Ancestor objects
const char* path = fPath.String();
const char* pathEnd = path + fPath.Length();
const char* component = path;
Ancestor* ancestor = NULL;
while (component < pathEnd) {
const char* componentEnd = component == path
? component + 1 : strchr(component, '/');
if (componentEnd == NULL)
componentEnd = pathEnd;
BString ancestorPath(path, componentEnd - path);
if (ancestorPath.IsEmpty())
return B_NO_MEMORY;
ancestor = new(std::nothrow) Ancestor(ancestor, ancestorPath,
component - path);
TRACE(" created ancestor %p (\"%s\" / \"%s\")\n", ancestor,
ancestor->Path().String(), ancestor->Name());
if (ancestor == NULL)
return B_NO_MEMORY;
if (fRoot == NULL)
fRoot = ancestor;
component = componentEnd[0] == '/' ? componentEnd + 1 : componentEnd;
}
fBaseAncestor = ancestor;
return B_OK;
}
status_t
PathHandler::_StartWatchingAncestors(Ancestor* startAncestor, bool notify)
{
TRACE("%p->PathHandler::_StartWatchingAncestors(%p, %d)\n", this,
startAncestor, notify);
// The watch flags for the path (if it exists). Recursively implies
// directory, since we need to watch the entries.
uint32 watchFlags = (fFlags & WATCH_NODE_FLAG_MASK)
| (_WatchRecursively() ? B_WATCH_DIRECTORY : 0);
for (Ancestor* ancestor = startAncestor; ancestor != NULL;
ancestor = ancestor->Child()) {
status_t error = ancestor->StartWatching(watchFlags, this);
if (error != B_OK)
return error;
if (!ancestor->Exists()) {
TRACE(" -> ancestor doesn't exist\n");
break;
}
fAncestors.Insert(ancestor);
}
if (!fBaseAncestor->Exists())
return B_OK;
if (notify) {
_NotifyEntryCreatedOrRemoved(fBaseAncestor->EntryRef(),
fBaseAncestor->NodeRef(), fPath, fBaseAncestor->IsDirectory(),
B_ENTRY_CREATED);
}
if (!_WatchRecursively())
return B_OK;
status_t error = _AddNode(fBaseAncestor->NodeRef(),
fBaseAncestor->IsDirectory(), notify && _WatchFilesOnly(), NULL,
&fBaseNode);
if (error != B_OK)
return error;
return B_OK;
}
void
PathHandler::_StopWatchingAncestors(Ancestor* ancestor, bool notify)
{
// stop watching the tree below path
if (fBaseNode != NULL) {
_DeleteNode(fBaseNode, notify && _WatchFilesOnly());
fBaseNode = NULL;
}
if (notify && fBaseAncestor->Exists()
&& (fBaseAncestor->IsDirectory()
? !_WatchFilesOnly() : !_WatchDirectoriesOnly())) {
_NotifyEntryCreatedOrRemoved(fBaseAncestor->EntryRef(),
fBaseAncestor->NodeRef(), fPath, fBaseAncestor->IsDirectory(),
B_ENTRY_REMOVED);
}
// stop watching the ancestors and uninitialize their entries
for (; ancestor != NULL; ancestor = ancestor->Child()) {
if (ancestor->Exists())
fAncestors.Remove(ancestor);
ancestor->StopWatching(this);
}
}
void
PathHandler::_EntryCreated(BMessage* message)
{
// TODO: Unless we're watching files only, we might want to forward (some
// of) the messages that don't agree with our model, since our client
// maintains its model at a different time and the notification might be
// necessary to keep it up-to-date. E.g. consider the following case:
// 1. a directory is created
// 2. a file is created in the directory
// 3. the file is removed from the directory
// If we get the notification after 1. and before 2., we pass it on to the
// client, which may get it after 2. and before 3., thus seeing the file.
// If we then get the entry-created notification after 3., we don't see the
// file anymore and ignore the notification as well as the following
// entry-removed notification. That is the client will never know that the
// file has been removed. This can only happen in recursive mode. Otherwise
// (and with B_WATCH_DIRECTORY) we just pass on all notifications.
// A possible solution could be to just create a zombie entry and pass on
// the entry-created notification. We wouldn't be able to adhere to the
// B_WATCH_FILES_ONLY/B_WATCH_DIRECTORIES_ONLY flags, but that should be
// acceptable. Either the client hasn't seen the entry either -- then it
// doesn't matter -- or it likely has ignored a not matching entry anyway.
NotOwningEntryRef entryRef;
node_ref nodeRef;
if (message->FindInt32("device", &nodeRef.device) != B_OK
|| message->FindInt64("node", &nodeRef.node) != B_OK
|| message->FindInt64("directory", &entryRef.directory) != B_OK
|| message->FindString("name", (const char**)&entryRef.name) != B_OK) {
return;
}
entryRef.device = nodeRef.device;
if (_CheckDuplicateEntryNotification(B_ENTRY_CREATED, entryRef, nodeRef))
return;
TRACE("%p->PathHandler::_EntryCreated(): entry: %" B_PRIdDEV ":%" B_PRIdINO
":\"%s\", node: %" B_PRIdDEV ":%" B_PRIdINO "\n", this, entryRef.device,
entryRef.directory, entryRef.name, nodeRef.device, nodeRef.node);
BEntry entry;
struct stat st;
if (entry.SetTo(&entryRef) != B_OK || entry.GetStat(&st) != B_OK
|| nodeRef != node_ref(st.st_dev, st.st_ino)) {
return;
}
_EntryCreated(entryRef, nodeRef, S_ISDIR(st.st_mode), false, true, NULL);
}
void
PathHandler::_EntryRemoved(BMessage* message)
{
NotOwningEntryRef entryRef;
node_ref nodeRef;
if (message->FindInt32("device", &nodeRef.device) != B_OK
|| message->FindInt64("node", &nodeRef.node) != B_OK
|| message->FindInt64("directory", &entryRef.directory) != B_OK
|| message->FindString("name", (const char**)&entryRef.name) != B_OK) {
return;
}
entryRef.device = nodeRef.device;
if (_CheckDuplicateEntryNotification(B_ENTRY_REMOVED, entryRef, nodeRef))
return;
TRACE("%p->PathHandler::_EntryRemoved(): entry: %" B_PRIdDEV ":%" B_PRIdINO
":\"%s\", node: %" B_PRIdDEV ":%" B_PRIdINO "\n", this, entryRef.device,
entryRef.directory, entryRef.name, nodeRef.device, nodeRef.node);
_EntryRemoved(entryRef, nodeRef, false, true, NULL);
}
void
PathHandler::_EntryMoved(BMessage* message)
{
NotOwningEntryRef fromEntryRef;
NotOwningEntryRef toEntryRef;
node_ref nodeRef;
if (message->FindInt32("node device", &nodeRef.device) != B_OK
|| message->FindInt64("node", &nodeRef.node) != B_OK
|| message->FindInt32("device", &fromEntryRef.device) != B_OK
|| message->FindInt64("from directory", &fromEntryRef.directory) != B_OK
|| message->FindInt64("to directory", &toEntryRef.directory) != B_OK
|| message->FindString("from name", (const char**)&fromEntryRef.name)
!= B_OK
|| message->FindString("name", (const char**)&toEntryRef.name)
!= B_OK) {
return;
}
toEntryRef.device = fromEntryRef.device;
if (_CheckDuplicateEntryNotification(B_ENTRY_MOVED, toEntryRef, nodeRef,
&fromEntryRef)) {
return;
}
TRACE("%p->PathHandler::_EntryMoved(): entry: %" B_PRIdDEV ":%" B_PRIdINO
":\"%s\" -> %" B_PRIdDEV ":%" B_PRIdINO ":\"%s\", node: %" B_PRIdDEV
":%" B_PRIdINO "\n", this, fromEntryRef.device, fromEntryRef.directory,
fromEntryRef.name, toEntryRef.device, toEntryRef.directory,
toEntryRef.name, nodeRef.device, nodeRef.node);
BEntry entry;
struct stat st;
if (entry.SetTo(&toEntryRef) != B_OK || entry.GetStat(&st) != B_OK
|| nodeRef != node_ref(st.st_dev, st.st_ino)) {
_EntryRemoved(fromEntryRef, nodeRef, false, true, NULL);
return;
}
bool isDirectory = S_ISDIR(st.st_mode);
Ancestor* fromAncestor = _GetAncestor(fromEntryRef.DirectoryNodeRef());
Ancestor* toAncestor = _GetAncestor(toEntryRef.DirectoryNodeRef());
if (_WatchRecursively()) {
Node* fromDirectoryNode = _GetNode(fromEntryRef.DirectoryNodeRef());
Node* toDirectoryNode = _GetNode(toEntryRef.DirectoryNodeRef());
if (fromDirectoryNode != NULL || toDirectoryNode != NULL) {
// Check whether _EntryRemoved()/_EntryCreated() can handle the
// respective entry regularly (i.e. don't encounter an out-of-sync
// issue) or don't need to be called at all (entry outside the
// monitored tree).
if ((fromDirectoryNode == NULL
|| _EntryRemoved(fromEntryRef, nodeRef, true, false, NULL))
&& (toDirectoryNode == NULL
|| _EntryCreated(toEntryRef, nodeRef, isDirectory, true,
false, NULL))) {
// The entries can be handled regularly. We delegate the work to
// _EntryRemoved() and _EntryCreated() and only handle the
// notification ourselves.
// handle removed
Entry* removedEntry = NULL;
if (fromDirectoryNode != NULL) {
_EntryRemoved(fromEntryRef, nodeRef, false, false,
&removedEntry);
}
// handle created
Entry* createdEntry = NULL;
if (toDirectoryNode != NULL) {
_EntryCreated(toEntryRef, nodeRef, isDirectory, false,
false, &createdEntry);
}
// notify
if (_WatchFilesOnly() && isDirectory) {
// recursively iterate through the removed and created
// hierarchy and send notifications for the files
if (removedEntry != NULL) {
_NotifyFilesCreatedOrRemoved(removedEntry,
B_ENTRY_REMOVED);
}
if (createdEntry != NULL) {
_NotifyFilesCreatedOrRemoved(createdEntry,
B_ENTRY_CREATED);
}
} else {
BString fromPath;
if (fromDirectoryNode != NULL) {
fromPath = make_path(_NodePath(fromDirectoryNode),
fromEntryRef.name);
}
BString path;
if (toDirectoryNode != NULL) {
path = make_path(_NodePath(toDirectoryNode),
toEntryRef.name);
}
_NotifyEntryMoved(fromEntryRef, toEntryRef, nodeRef,
fromPath, path, isDirectory, fromDirectoryNode == NULL,
toDirectoryNode == NULL);
}
if (removedEntry != NULL)
_DeleteEntry(removedEntry, false);
} else {
// The entries can't be handled regularly. We delegate all the
// work to _EntryRemoved() and _EntryCreated(). This will
// generate separate entry-removed and entry-created
// notifications.
// handle removed
if (fromDirectoryNode != NULL)
_EntryRemoved(fromEntryRef, nodeRef, false, true, NULL);
// handle created
if (toDirectoryNode != NULL) {
_EntryCreated(toEntryRef, nodeRef, isDirectory, false, true,
NULL);
}
}
return;
}
if (fromAncestor == fBaseAncestor || toAncestor == fBaseAncestor) {
// That should never happen, as we should have found a matching
// directory node in this case.
#ifdef DEBUG
debugger("path ancestor exists, but doesn't have a directory");
// Could actually be an out-of-memory situation, if we simply failed
// to create the directory earlier.
#endif
_StopWatchingAncestors(fRoot, false);
_StartWatchingAncestors(fRoot, false);
return;
}
} else {
// Non-recursive mode: This notification is only of interest to us, if
// it is either a move into/within/out of the path and B_WATCH_DIRECTORY
// is set, or an ancestor might be affected.
if (fromAncestor == NULL && toAncestor == NULL)
return;
if (fromAncestor == fBaseAncestor || toAncestor == fBaseAncestor) {
if ((fFlags & B_WATCH_DIRECTORY) != 0) {
BString fromPath;
if (fromAncestor == fBaseAncestor)
fromPath = make_path(fPath, fromEntryRef.name);
BString path;
if (toAncestor == fBaseAncestor)
path = make_path(fPath, toEntryRef.name);
_NotifyEntryMoved(fromEntryRef, toEntryRef, nodeRef,
fromPath, path, isDirectory, fromAncestor == NULL,
toAncestor == NULL);
}
return;
}
}
if (fromAncestor == NULL && toAncestor == NULL)
return;
if (fromAncestor == NULL) {
_EntryCreated(toEntryRef, nodeRef, isDirectory, false, true, NULL);
return;
}
if (toAncestor == NULL) {
_EntryRemoved(fromEntryRef, nodeRef, false, true, NULL);
return;
}
// An entry was moved in a true ancestor directory or between true ancestor
// directories. Unless the moved entry was or becomes our base ancestor, we
// let _EntryRemoved() and _EntryCreated() handle it.
bool fromIsBase = fromAncestor == fBaseAncestor->Parent()
&& strcmp(fromEntryRef.name, fBaseAncestor->Name()) == 0;
bool toIsBase = toAncestor == fBaseAncestor->Parent()
&& strcmp(toEntryRef.name, fBaseAncestor->Name()) == 0;
if (fromIsBase || toIsBase) {
// This might be a duplicate notification. Check whether our model
// already reflects the change. Otherwise stop/start watching the base
// ancestor as required.
bool notifyFilesRecursively = _WatchFilesOnly() && isDirectory;
if (fromIsBase) {
if (!fBaseAncestor->Exists())
return;
_StopWatchingAncestors(fBaseAncestor, notifyFilesRecursively);
} else {
if (fBaseAncestor->Exists()) {
if (fBaseAncestor->NodeRef() == nodeRef
&& isDirectory == fBaseAncestor->IsDirectory()) {
return;
}
// We're out of sync with reality.
_StopWatchingAncestors(fBaseAncestor, true);
_StartWatchingAncestors(fBaseAncestor, true);
return;
}
_StartWatchingAncestors(fBaseAncestor, notifyFilesRecursively);
}
if (!notifyFilesRecursively) {
_NotifyEntryMoved(fromEntryRef, toEntryRef, nodeRef,
fromIsBase ? fPath.String() : NULL,
toIsBase ? fPath.String() : NULL,
isDirectory, toIsBase, fromIsBase);
}
return;
}
_EntryRemoved(fromEntryRef, nodeRef, false, true, NULL);
_EntryCreated(toEntryRef, nodeRef, isDirectory, false, true, NULL);
}
void
PathHandler::_NodeChanged(BMessage* message)
{
node_ref nodeRef;
if (message->FindInt32("device", &nodeRef.device) != B_OK
|| message->FindInt64("node", &nodeRef.node) != B_OK) {
return;
}
TRACE("%p->PathHandler::_NodeChanged(): node: %" B_PRIdDEV ":%" B_PRIdINO
", %s%s\n", this, nodeRef.device, nodeRef.node,
message->GetInt32("opcode", B_STAT_CHANGED) == B_ATTR_CHANGED
? "attribute: " : "stat",
message->GetInt32("opcode", B_STAT_CHANGED) == B_ATTR_CHANGED
? message->GetString("attr", "") : "");
bool isDirectory = false;
BString path;
if (Ancestor* ancestor = _GetAncestor(nodeRef)) {
if (ancestor != fBaseAncestor)
return;
isDirectory = ancestor->IsDirectory();
path = fPath;
} else if (Node* node = _GetNode(nodeRef)) {
isDirectory = node->IsDirectory();
path = _NodePath(node);
} else
return;
if (isDirectory ? _WatchFilesOnly() : _WatchDirectoriesOnly())
return;
_NotifyTarget(*message, path);
}
bool
PathHandler::_EntryCreated(const NotOwningEntryRef& entryRef,
const node_ref& nodeRef, bool isDirectory, bool dryRun, bool notify,
Entry** _entry)
{
if (_entry != NULL)
*_entry = NULL;
Ancestor* ancestor = _GetAncestor(nodeRef);
if (ancestor != NULL) {
if (isDirectory == ancestor->IsDirectory()
&& entryRef == ancestor->EntryRef()) {
// just a duplicate notification
TRACE(" -> we already know the ancestor\n");
return true;
}
struct stat ancestorStat;
if (BEntry(&ancestor->EntryRef()).GetStat(&ancestorStat) == B_OK
&& node_ref(ancestorStat.st_dev, ancestorStat.st_ino)
== ancestor->NodeRef()
&& S_ISDIR(ancestorStat.st_mode) == ancestor->IsDirectory()) {
// Our information for the ancestor is up-to-date, so ignore the
// notification.
TRACE(" -> we know a different ancestor, but our info is "
"up-to-date\n");
return true;
}
// We're out of sync with reality.
TRACE(" -> ancestor mismatch -> resyncing\n");
if (!dryRun) {
_StopWatchingAncestors(ancestor, true);
_StartWatchingAncestors(ancestor, true);
}
return false;
}
ancestor = _GetAncestor(entryRef.DirectoryNodeRef());
if (ancestor != NULL) {
if (ancestor != fBaseAncestor) {
// The directory is a true ancestor -- the notification is only of
// interest, if the entry matches the child ancestor.
Ancestor* childAncestor = ancestor->Child();
if (strcmp(entryRef.name, childAncestor->Name()) != 0) {
TRACE(" -> not an ancestor entry we're interested in "
"(\"%s\")\n", childAncestor->Name());
return true;
}
if (!dryRun) {
if (childAncestor->Exists()) {
TRACE(" ancestor entry mismatch -> resyncing\n");
// We're out of sync with reality -- the new entry refers to
// a different node.
_StopWatchingAncestors(childAncestor, true);
}
TRACE(" -> starting to watch newly appeared ancestor\n");
_StartWatchingAncestors(childAncestor, true);
}
return false;
}
// The directory is our path. If watching recursively, just fall
// through. Otherwise, we want to pass on the notification, if directory
// watching is enabled.
if (!_WatchRecursively()) {
if ((fFlags & B_WATCH_DIRECTORY) != 0) {
_NotifyEntryCreatedOrRemoved(entryRef, nodeRef,
make_path(fPath, entryRef.name), isDirectory,
B_ENTRY_CREATED);
}
return true;
}
}
if (!_WatchRecursively()) {
// That shouldn't happen, since we only watch the ancestors in this
// case.
return true;
}
Node* directoryNode = _GetNode(entryRef.DirectoryNodeRef());
if (directoryNode == NULL)
return true;
Directory* directory = directoryNode->ToDirectory();
if (directory == NULL) {
// We're out of sync with reality.
if (!dryRun) {
if (Entry* nodeEntry = directory->FirstNodeEntry()) {
// remove the entry that is in the way and re-add the proper
// entry
NotOwningEntryRef directoryEntryRef = nodeEntry->EntryRef();
BString directoryName = nodeEntry->Name();
_DeleteEntry(nodeEntry, true);
_EntryCreated(directoryEntryRef, entryRef.DirectoryNodeRef(),
true, false, notify, NULL);
} else {
// It's either the base node or something's severely fishy.
// Resync the whole path.
_StopWatchingAncestors(fBaseAncestor, true);
_StartWatchingAncestors(fBaseAncestor, true);
}
}
return false;
}
// Check, if there's a colliding entry.
if (Entry* nodeEntry = directory->FindEntry(entryRef.name)) {
Node* entryNode = nodeEntry->Node();
if (entryNode != NULL && entryNode->NodeRef() == nodeRef)
return true;
// We're out of sync with reality -- the new entry refers to a different
// node.
_DeleteEntry(nodeEntry, true);
}
if (dryRun)
return true;
_AddEntryIfNeeded(directory, entryRef.name, nodeRef, isDirectory, notify,
_entry);
return true;
}
bool
PathHandler::_EntryRemoved(const NotOwningEntryRef& entryRef,
const node_ref& nodeRef, bool dryRun, bool notify, Entry** _keepEntry)
{
if (_keepEntry != NULL)
*_keepEntry = NULL;
Ancestor* ancestor = _GetAncestor(nodeRef);
if (ancestor != NULL) {
// The node is an ancestor. If this is a true match, stop watching the
// ancestor.
if (!ancestor->Exists())
return true;
if (entryRef != ancestor->EntryRef()) {
// We might be out of sync with reality -- the new entry refers to a
// different node.
struct stat ancestorStat;
if (BEntry(&ancestor->EntryRef()).GetStat(&ancestorStat) != B_OK) {
if (!dryRun)
_StopWatchingAncestors(ancestor, true);
return false;
}
if (node_ref(ancestorStat.st_dev, ancestorStat.st_ino)
!= ancestor->NodeRef()
|| S_ISDIR(ancestorStat.st_mode) != ancestor->IsDirectory()) {
if (!dryRun) {
_StopWatchingAncestors(ancestor, true);
_StartWatchingAncestors(ancestor, true);
}
return false;
}
return true;
}
if (!dryRun)
_StopWatchingAncestors(ancestor, true);
return false;
}
ancestor = _GetAncestor(entryRef.DirectoryNodeRef());
if (ancestor != NULL) {
if (ancestor != fBaseAncestor) {
// The directory is a true ancestor -- the notification cannot be
// of interest, since the node didn't match a known ancestor.
return true;
}
// The directory is our path. If watching recursively, just fall
// through. Otherwise, we want to pass on the notification, if directory
// watching is enabled.
if (!_WatchRecursively()) {
if (notify && (fFlags & B_WATCH_DIRECTORY) != 0) {
_NotifyEntryCreatedOrRemoved(entryRef, nodeRef,
make_path(fPath, entryRef.name), false, B_ENTRY_REMOVED);
// We don't know whether this was a directory, but it
// doesn't matter in this case.
}
return true;
}
}
if (!_WatchRecursively()) {
// That shouldn't happen, since we only watch the ancestors in this
// case.
return true;
}
Node* directoryNode = _GetNode(entryRef.DirectoryNodeRef());
if (directoryNode == NULL) {
// We shouldn't get a notification, if we don't known the directory.
return true;
}
Directory* directory = directoryNode->ToDirectory();
if (directory == NULL) {
// We might be out of sync with reality or the notification is just
// late. The former case is extremely unlikely (we are watching the node
// and its parent directory after all) and rather hard to verify.
return true;
}
Entry* nodeEntry = directory->FindEntry(entryRef.name);
if (nodeEntry == NULL) {
// might be a non-directory node while we're in directories-only mode
return true;
}
if (!dryRun) {
if (_keepEntry != NULL)
*_keepEntry = nodeEntry;
else
_DeleteEntry(nodeEntry, notify);
}
return true;
}
bool
PathHandler::_CheckDuplicateEntryNotification(int32 opcode,
const entry_ref& toEntryRef, const node_ref& nodeRef,
const entry_ref* fromEntryRef)
{
if (opcode == fDuplicateEntryNotificationOpcode
&& nodeRef == fDuplicateEntryNotificationNodeRef
&& toEntryRef == fDuplicateEntryNotificationToEntryRef
&& (fromEntryRef == NULL
|| *fromEntryRef == fDuplicateEntryNotificationFromEntryRef)) {
return true;
}
fDuplicateEntryNotificationOpcode = opcode;
fDuplicateEntryNotificationNodeRef = nodeRef;
fDuplicateEntryNotificationToEntryRef = toEntryRef;
fDuplicateEntryNotificationFromEntryRef = fromEntryRef != NULL
? *fromEntryRef : entry_ref();
return false;
}
void
PathHandler::_UnsetDuplicateEntryNotification()
{
fDuplicateEntryNotificationOpcode = B_STAT_CHANGED;
fDuplicateEntryNotificationNodeRef = node_ref();
fDuplicateEntryNotificationFromEntryRef = entry_ref();
fDuplicateEntryNotificationToEntryRef = entry_ref();
}
Ancestor*
PathHandler::_GetAncestor(const node_ref& nodeRef) const
{
return fAncestors.Lookup(nodeRef);
}
status_t
PathHandler::_AddNode(const node_ref& nodeRef, bool isDirectory, bool notify,
Entry* entry, Node** _node)
{
TRACE("%p->PathHandler::_AddNode(%" B_PRIdDEV ":%" B_PRIdINO
", isDirectory: %d, notify: %d)\n", this, nodeRef.device, nodeRef.node,
isDirectory, notify);
// If hard links are supported, we may already know the node.
Node* node = _GetNode(nodeRef);
if (node != NULL) {
if (entry != NULL) {
entry->SetNode(node);
node->AddNodeEntry(entry);
}
if (_node != NULL)
*_node = node;
return B_OK;
}
// create the node
Directory* directoryNode = NULL;
if (isDirectory)
node = directoryNode = Directory::Create(nodeRef);
else
node = new(std::nothrow) Node(nodeRef);
if (node == NULL)
return B_NO_MEMORY;
ObjectDeleter<Node> nodeDeleter(node);
// start watching (don't do that for the base node, since we watch it
// already via fBaseAncestor)
if (nodeRef != fBaseAncestor->NodeRef()) {
uint32 flags = (fFlags & WATCH_NODE_FLAG_MASK) | B_WATCH_DIRECTORY;
status_t error = sWatchingInterface->WatchNode(&nodeRef, flags, this);
if (error != B_OK)
return error;
}
fNodes.Insert(nodeDeleter.Detach());
if (entry != NULL) {
entry->SetNode(node);
node->AddNodeEntry(entry);
}
if (_node != NULL)
*_node = node;
if (!isDirectory)
return B_OK;
// recursively add the directory's descendents
BDirectory directory;
if (directory.SetTo(&nodeRef) != B_OK) {
if (_node != NULL)
*_node = node;
return B_OK;
}
entry_ref entryRef;
while (directory.GetNextRef(&entryRef) == B_OK) {
struct stat st;
if (BEntry(&entryRef).GetStat(&st) != B_OK)
continue;
bool isDirectory = S_ISDIR(st.st_mode);
status_t error = _AddEntryIfNeeded(directoryNode, entryRef.name,
node_ref(st.st_dev, st.st_ino), isDirectory, notify);
if (error != B_OK) {
TRACE("%p->PathHandler::_AddNode(%" B_PRIdDEV ":%" B_PRIdINO
", isDirectory: %d, notify: %d): failed to add directory "
"entry: \"%s\"\n", this, nodeRef.device, nodeRef.node,
isDirectory, notify, entryRef.name);
continue;
}
}
return B_OK;
}
void
PathHandler::_DeleteNode(Node* node, bool notify)
{
if (Directory* directory = node->ToDirectory()) {
Entry* entry = directory->RemoveAllEntries();
while (entry != NULL) {
Entry* nextEntry = entry->HashNext();
_DeleteEntryAlreadyRemovedFromParent(entry, notify);
entry = nextEntry;
}
}
if (node->NodeRef() != fBaseAncestor->NodeRef())
sWatchingInterface->WatchNode(&node->NodeRef(), B_STOP_WATCHING, this);
fNodes.Remove(node);
delete node;
}
Node*
PathHandler::_GetNode(const node_ref& nodeRef) const
{
return fNodes.Lookup(nodeRef);
}
status_t
PathHandler::_AddEntryIfNeeded(Directory* directory, const char* name,
const node_ref& nodeRef, bool isDirectory, bool notify,
Entry** _entry)
{
TRACE("%p->PathHandler::_AddEntryIfNeeded(%" B_PRIdDEV ":%" B_PRIdINO
":\"%s\", %" B_PRIdDEV ":%" B_PRIdINO
", isDirectory: %d, notify: %d)\n", this, directory->NodeRef().device,
directory->NodeRef().node, name, nodeRef.device, nodeRef.node,
isDirectory, notify);
if (!isDirectory && _WatchDirectoriesOnly()) {
if (_entry != NULL)
*_entry = NULL;
return B_OK;
}
Entry* entry = directory->CreateEntry(name, NULL);
if (entry == NULL)
return B_NO_MEMORY;
status_t error = _AddNode(nodeRef, isDirectory, notify && _WatchFilesOnly(),
entry);
if (error != B_OK) {
directory->RemoveEntry(entry);
delete entry;
return error;
}
if (notify)
_NotifyEntryCreatedOrRemoved(entry, B_ENTRY_CREATED);
if (_entry != NULL)
*_entry = entry;
return B_OK;
}
void
PathHandler::_DeleteEntry(Entry* entry, bool notify)
{
entry->Parent()->RemoveEntry(entry);
_DeleteEntryAlreadyRemovedFromParent(entry, notify);
}
void
PathHandler::_DeleteEntryAlreadyRemovedFromParent(Entry* entry, bool notify)
{
if (notify)
_NotifyEntryCreatedOrRemoved(entry, B_ENTRY_REMOVED);
Node* node = entry->Node();
if (node->IsOnlyNodeEntry(entry))
_DeleteNode(node, notify && _WatchFilesOnly());
delete entry;
}
void
PathHandler::_NotifyFilesCreatedOrRemoved(Entry* entry, int32 opcode) const
{
Directory* directory = entry->Node()->ToDirectory();
if (directory == NULL) {
_NotifyEntryCreatedOrRemoved(entry, opcode);
return;
}
for (EntryMap::Iterator it = directory->GetEntryIterator(); it.HasNext();)
_NotifyFilesCreatedOrRemoved(it.Next(), opcode);
}
void
PathHandler::_NotifyEntryCreatedOrRemoved(Entry* entry, int32 opcode) const
{
Node* node = entry->Node();
_NotifyEntryCreatedOrRemoved(
NotOwningEntryRef(entry->Parent()->NodeRef(), entry->Name()),
node->NodeRef(), _EntryPath(entry), node->IsDirectory(), opcode);
}
void
PathHandler::_NotifyEntryCreatedOrRemoved(const entry_ref& entryRef,
const node_ref& nodeRef, const char* path, bool isDirectory, int32 opcode)
const
{
if (isDirectory ? _WatchFilesOnly() : _WatchDirectoriesOnly())
return;
TRACE("%p->PathHandler::_NotifyEntryCreatedOrRemoved(): entry %s: %"
B_PRIdDEV ":%" B_PRIdINO ":\"%s\", node: %" B_PRIdDEV ":%" B_PRIdINO
"\n", this, opcode == B_ENTRY_CREATED ? "created" : "removed",
entryRef.device, entryRef.directory, entryRef.name, nodeRef.device,
nodeRef.node);
BMessage message(B_PATH_MONITOR);
message.AddInt32("opcode", opcode);
message.AddInt32("device", entryRef.device);
message.AddInt64("directory", entryRef.directory);
message.AddInt32("node device", nodeRef.device);
// This field is not in a usual node monitoring message, since the node
// the created/removed entry refers to always belongs to the same FS as
// the directory, as another FS cannot yet/no longer be mounted there.
// In our case, however, this can very well be the case, e.g. when the
// the notification is triggered in response to a directory tree having
// been moved into/out of our path.
message.AddInt64("node", nodeRef.node);
message.AddString("name", entryRef.name);
_NotifyTarget(message, path);
}
void
PathHandler::_NotifyEntryMoved(const entry_ref& fromEntryRef,
const entry_ref& toEntryRef, const node_ref& nodeRef, const char* fromPath,
const char* path, bool isDirectory, bool wasAdded, bool wasRemoved) const
{
if ((isDirectory && _WatchFilesOnly())
|| (!isDirectory && _WatchDirectoriesOnly())) {
return;
}
TRACE("%p->PathHandler::_NotifyEntryMoved(): entry: %" B_PRIdDEV ":%"
B_PRIdINO ":\"%s\" -> %" B_PRIdDEV ":%" B_PRIdINO ":\"%s\", node: %"
B_PRIdDEV ":%" B_PRIdINO "\n", this, fromEntryRef.device,
fromEntryRef.directory, fromEntryRef.name, toEntryRef.device,
toEntryRef.directory, toEntryRef.name, nodeRef.device, nodeRef.node);
BMessage message(B_PATH_MONITOR);
message.AddInt32("opcode", B_ENTRY_MOVED);
message.AddInt32("device", fromEntryRef.device);
message.AddInt64("from directory", fromEntryRef.directory);
message.AddInt64("to directory", toEntryRef.directory);
message.AddInt32("node device", nodeRef.device);
message.AddInt64("node", nodeRef.node);
message.AddString("from name", fromEntryRef.name);
message.AddString("name", toEntryRef.name);
if (wasAdded)
message.AddBool("added", true);
if (wasRemoved)
message.AddBool("removed", true);
if (fromPath != NULL && fromPath[0] != '\0')
message.AddString("from path", fromPath);
_NotifyTarget(message, path);
}
void
PathHandler::_NotifyTarget(BMessage& message, const char* path) const
{
message.what = B_PATH_MONITOR;
if (path != NULL && path[0] != '\0')
message.AddString("path", path);
message.AddString("watched_path", fPath.String());
fTarget.SendMessage(&message);
}
BString
PathHandler::_NodePath(const Node* node) const
{
if (Entry* entry = node->FirstNodeEntry())
return _EntryPath(entry);
return node == fBaseNode ? fPath : BString();
}
BString
PathHandler::_EntryPath(const Entry* entry) const
{
return make_path(_NodePath(entry->Parent()), entry->Name());
}
bool
PathHandler::_WatchRecursively() const
{
return (fFlags & B_WATCH_RECURSIVELY) != 0;
}
bool
PathHandler::_WatchFilesOnly() const
{
return (fFlags & B_WATCH_FILES_ONLY) != 0;
}
bool
PathHandler::_WatchDirectoriesOnly() const
{
return (fFlags & B_WATCH_DIRECTORIES_ONLY) != 0;
}
} // namespace
// #pragma mark - BPathMonitor
namespace BPrivate {
BPathMonitor::BPathMonitor()
{
}
BPathMonitor::~BPathMonitor()
{
}
/*static*/ status_t
BPathMonitor::StartWatching(const char* path, uint32 flags,
const BMessenger& target)
{
TRACE("BPathMonitor::StartWatching(%s, %" B_PRIx32 ")\n", path, flags);
if (path == NULL || path[0] == '\0')
return B_BAD_VALUE;
// B_WATCH_FILES_ONLY and B_WATCH_DIRECTORIES_ONLY are mutual exclusive
if ((flags & B_WATCH_FILES_ONLY) != 0
&& (flags & B_WATCH_DIRECTORIES_ONLY) != 0) {
return B_BAD_VALUE;
}
status_t status = _InitIfNeeded();
if (status != B_OK)
return status;
BAutolock _(sLooper);
Watcher* watcher = sWatchers->Lookup(target);
bool newWatcher = false;
if (watcher != NULL) {
// If there's already a handler for the path, we'll replace it, but
// add its flags.
if (PathHandler* handler = watcher->Lookup(path)) {
// keep old flags save for conflicting mutually exclusive ones
uint32 oldFlags = handler->Flags();
const uint32 kMutuallyExclusiveFlags
= B_WATCH_FILES_ONLY | B_WATCH_DIRECTORIES_ONLY;
if ((flags & kMutuallyExclusiveFlags) != 0)
oldFlags &= ~(uint32)kMutuallyExclusiveFlags;
flags |= oldFlags;
watcher->Remove(handler);
handler->Quit();
}
} else {
watcher = Watcher::Create(target);
if (watcher == NULL)
return B_NO_MEMORY;
sWatchers->Insert(watcher);
newWatcher = true;
}
PathHandler* handler = new (std::nothrow) PathHandler(path, flags, target,
sLooper);
status = handler != NULL ? handler->InitCheck() : B_NO_MEMORY;
if (status != B_OK) {
if (handler != NULL)
handler->Quit();
if (newWatcher) {
sWatchers->Remove(watcher);
delete watcher;
}
return status;
}
watcher->Insert(handler);
return B_OK;
}
/*static*/ status_t
BPathMonitor::StopWatching(const char* path, const BMessenger& target)
{
if (sLooper == NULL)
return B_BAD_VALUE;
TRACE("BPathMonitor::StopWatching(%s)\n", path);
BAutolock _(sLooper);
Watcher* watcher = sWatchers->Lookup(target);
if (watcher == NULL)
return B_BAD_VALUE;
PathHandler* handler = watcher->Lookup(path);
if (handler == NULL)
return B_BAD_VALUE;
watcher->Remove(handler);
handler->Quit();
if (watcher->IsEmpty()) {
sWatchers->Remove(watcher);
delete watcher;
}
return B_OK;
}
/*static*/ status_t
BPathMonitor::StopWatching(const BMessenger& target)
{
if (sLooper == NULL)
return B_BAD_VALUE;
BAutolock _(sLooper);
Watcher* watcher = sWatchers->Lookup(target);
if (watcher == NULL)
return B_BAD_VALUE;
// delete handlers
PathHandler* handler = watcher->Clear(true);
while (handler != NULL) {
PathHandler* nextHandler = handler->HashNext();
handler->Quit();
handler = nextHandler;
}
sWatchers->Remove(watcher);
delete watcher;
return B_OK;
}
/*static*/ void
BPathMonitor::SetWatchingInterface(BWatchingInterface* watchingInterface)
{
sWatchingInterface = watchingInterface != NULL
? watchingInterface : sDefaultWatchingInterface;
}
/*static*/ status_t
BPathMonitor::_InitIfNeeded()
{
pthread_once(&sInitOnce, &BPathMonitor::_Init);
return sLooper != NULL ? B_OK : B_NO_MEMORY;
}
/*static*/ void
BPathMonitor::_Init()
{
sDefaultWatchingInterface = new(std::nothrow) BWatchingInterface;
if (sDefaultWatchingInterface == NULL)
return;
sWatchers = new(std::nothrow) WatcherMap;
if (sWatchers == NULL || sWatchers->Init() != B_OK)
return;
if (sWatchingInterface == NULL)
SetWatchingInterface(sDefaultWatchingInterface);
BLooper* looper = new (std::nothrow) BLooper("PathMonitor looper");
TRACE("Start PathMonitor looper\n");
if (looper == NULL)
return;
thread_id thread = looper->Run();
if (thread < 0) {
delete looper;
return;
}
sLooper = looper;
}
// #pragma mark - BWatchingInterface
BPathMonitor::BWatchingInterface::BWatchingInterface()
{
}
BPathMonitor::BWatchingInterface::~BWatchingInterface()
{
}
status_t
BPathMonitor::BWatchingInterface::WatchNode(const node_ref* node, uint32 flags,
const BMessenger& target)
{
return watch_node(node, flags, target);
}
status_t
BPathMonitor::BWatchingInterface::WatchNode(const node_ref* node, uint32 flags,
const BHandler* handler, const BLooper* looper)
{
return watch_node(node, flags, handler, looper);
}
status_t
BPathMonitor::BWatchingInterface::StopWatching(const BMessenger& target)
{
return stop_watching(target);
}
status_t
BPathMonitor::BWatchingInterface::StopWatching(const BHandler* handler,
const BLooper* looper)
{
return stop_watching(handler, looper);
}
} // namespace BPrivate
| 23.913163 | 79 | 0.694297 | [
"model"
] |
246d8bd29382f1624ca0817766bb6b951589fb6d | 5,799 | cpp | C++ | curl/src/main/jni/native/curl_transaction_metrics.cpp | qiniu/qiniu-android-curl-plugin | b3a296d5ae6195b0e873fc01b01d453dae3f1bdd | [
"MIT"
] | 1 | 2021-11-03T10:30:20.000Z | 2021-11-03T10:30:20.000Z | curl/src/main/jni/native/curl_transaction_metrics.cpp | YangSen-qn/qiniu-android-curl-plugin | 272a853aee65875db1dee01db837d9012a87e997 | [
"MIT"
] | null | null | null | curl/src/main/jni/native/curl_transaction_metrics.cpp | YangSen-qn/qiniu-android-curl-plugin | 272a853aee65875db1dee01db837d9012a87e997 | [
"MIT"
] | 1 | 2021-11-03T02:59:46.000Z | 2021-11-03T02:59:46.000Z | //
// Created by yangsen on 2020/9/18.
//
#include "curl_transaction_metrics.h"
#include <jni.h>
#include "curl_context.h"
jobject createJavaMetrics(CurlContext *curlContext) {
if (curlContext == nullptr) {
return nullptr;
}
JNIEnv *env = curlContext->env;
if (env == nullptr) {
return nullptr;
}
jclass metrics_class = env->FindClass("com/qiniu/client/curl/CurlTransactionMetrics");
if (metrics_class == nullptr) {
return nullptr;
}
jmethodID init_method = env->GetMethodID(metrics_class,
"<init>",
"()V");
if (init_method == nullptr) {
env->DeleteLocalRef(metrics_class);
return nullptr;
}
jobject object = env->NewObject(metrics_class, init_method);
env->DeleteLocalRef(metrics_class);
return object;
}
void setJavaMetricsStringField(CurlContext *curlContext, const char *fieldName, char *fieldValue) {
if (curlContext == nullptr || fieldValue == nullptr) {
return;
}
JNIEnv *env = curlContext->env;
jobject metrics = curlContext->metrics;
if (env == nullptr || metrics == nullptr) {
return;
}
jclass metrics_class = env->FindClass("com/qiniu/client/curl/CurlTransactionMetrics");
if (metrics_class == nullptr) {
return;
}
jmethodID set_method = env->GetMethodID(metrics_class, fieldName, "(Ljava/lang/String;)V");
if (set_method == nullptr) {
env->DeleteLocalRef(metrics_class);
return;
}
env->CallVoidMethod(metrics, set_method, env->NewStringUTF(fieldValue));
env->DeleteLocalRef(metrics_class);
}
void
setJavaMetricsLongField(CurlContext *curlContext, const char *fieldName, long long fieldValue) {
if (curlContext == nullptr) {
return;
}
JNIEnv *env = curlContext->env;
jobject metrics = curlContext->metrics;
if (env == nullptr || metrics == nullptr) {
return;
}
jclass metrics_class = env->FindClass("com/qiniu/client/curl/CurlTransactionMetrics");
if (metrics_class == nullptr) {
return;
}
jmethodID set_method = env->GetMethodID(metrics_class, fieldName, "(J)V");
if (set_method == nullptr) {
env->DeleteLocalRef(metrics_class);
return;
}
env->CallVoidMethod(metrics, set_method, fieldValue);
env->DeleteLocalRef(metrics_class);
}
void setJavaMetricsVoidField(CurlContext *curlContext, const char *fieldName) {
if (curlContext == nullptr) {
return;
}
JNIEnv *env = curlContext->env;
jobject metrics = curlContext->metrics;
if (env == nullptr || metrics == nullptr) {
return;
}
jclass metrics_class = env->FindClass("com/qiniu/client/curl/CurlTransactionMetrics");
if (metrics_class == nullptr) {
return;
}
jmethodID set_method = env->GetMethodID(metrics_class, fieldName, "()V");
if (set_method == nullptr) {
env->DeleteLocalRef(metrics_class);
return;
}
env->CallVoidMethod(metrics, set_method);
env->DeleteLocalRef(metrics_class);
}
void setJavaMetricsCountOfRequestHeaderBytesSent(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setCountOfRequestHeaderBytesSent", fieldValue);
}
void setJavaMetricsCountOfRequestBodyBytesSent(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setCountOfRequestBodyBytesSent", fieldValue);
}
void
setJavaMetricsCountOfResponseHeaderBytesReceived(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setCountOfResponseHeaderBytesReceived", fieldValue);
}
void
setJavaMetricsCountOfResponseBodyBytesReceived(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setCountOfResponseBodyBytesReceived", fieldValue);
}
void setJavaMetricsLocalAddress(CurlContext *curlContext, char *fieldValue) {
setJavaMetricsStringField(curlContext, "setLocalAddress", fieldValue);
}
void setJavaMetricsLocalPort(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setLocalPort", fieldValue);
}
void setJavaMetricsRemoteAddress(CurlContext *curlContext, char *fieldValue) {
setJavaMetricsStringField(curlContext, "setRemoteAddress", fieldValue);
}
void setJavaMetricsRemotePort(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setRemotePort", fieldValue);
}
void setJavaMetricsStartTimestamp(CurlContext *curlContext) {
setJavaMetricsVoidField(curlContext, "setStartTimestamp");
}
void setJavaMetricsNameLookupTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setNameLookupTime", fieldValue);
}
void setJavaMetricsConnectTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setConnectTime", fieldValue);
}
void setJavaMetricsAppConnectTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setAppConnectTime", fieldValue);
}
void setJavaMetricsPreTransferTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setPreTransferTime", fieldValue);
}
void setJavaMetricsStartTransferTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setStartTransferTime", fieldValue);
}
void setJavaMetricsTotalTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setTotalTime", fieldValue);
}
void setJavaMetricsRedirectTime(CurlContext *curlContext, long long fieldValue) {
setJavaMetricsLongField(curlContext, "setRedirectTime", fieldValue);
} | 30.845745 | 99 | 0.721331 | [
"object"
] |
2470c2a7d6a3e5d76decc1343470532ef4584fc3 | 11,822 | cpp | C++ | examples/parallel_for/tachyon/src/api.cpp | dishasrivastavapuresoftware/oneTBB | 34dd71e7238d278a807a0380311f39102a916223 | [
"Apache-2.0"
] | 1,736 | 2020-03-17T20:23:25.000Z | 2022-03-31T16:01:44.000Z | examples/parallel_for/tachyon/src/api.cpp | dishasrivastavapuresoftware/oneTBB | 34dd71e7238d278a807a0380311f39102a916223 | [
"Apache-2.0"
] | 500 | 2020-09-15T09:45:10.000Z | 2022-03-30T04:28:38.000Z | examples/parallel_for/tachyon/src/api.cpp | dishasrivastavapuresoftware/oneTBB | 34dd71e7238d278a807a0380311f39102a916223 | [
"Apache-2.0"
] | 376 | 2020-03-19T06:15:59.000Z | 2022-03-25T06:26:31.000Z | /*
Copyright (c) 2005-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
The original source for this example is
Copyright (c) 1994-2008 John E. Stone
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*/
/*
* api.cpp - This file contains all of the API calls that are defined for
* external driver code to use.
*/
#include "machine.hpp"
#include "types.hpp"
#include "macros.hpp"
#include "box.hpp"
#include "cylinder.hpp"
#include "plane.hpp"
#include "quadric.hpp"
#include "ring.hpp"
#include "sphere.hpp"
#include "triangle.hpp"
#include "vol.hpp"
#include "extvol.hpp"
#include "texture.hpp"
#include "light.hpp"
#include "render.hpp"
#include "camera.hpp"
#include "vector.hpp"
#include "intersect.hpp"
#include "shade.hpp"
#include "util.hpp"
#include "imap.hpp"
#include "global.hpp"
#include "tachyon_video.hpp"
typedef void *SceneHandle;
#include "api.hpp"
vector rt_vector(apiflt x, apiflt y, apiflt z) {
vector v;
v.x = x;
v.y = y;
v.z = z;
return v;
}
color rt_color(apiflt r, apiflt g, apiflt b) {
color c;
c.r = r;
c.g = g;
c.b = b;
return c;
}
void rt_initialize() {
rpcmsg msg;
reset_object();
reset_lights();
InitTextures();
if (!parinitted) {
parinitted = 1;
msg.type = 1; /* setup a ping message */
}
}
void rt_renderscene(SceneHandle voidscene) {
scenedef *scene = (scenedef *)voidscene;
renderscene(*scene);
}
void rt_camerasetup(SceneHandle voidscene,
apiflt zoom,
apiflt aspectratio,
int antialiasing,
int raydepth,
vector camcent,
vector viewvec,
vector upvec) {
scenedef *scene = (scenedef *)voidscene;
vector newupvec;
vector newviewvec;
vector newrightvec;
VCross((vector *)&upvec, &viewvec, &newrightvec);
VNorm(&newrightvec);
VCross((vector *)&viewvec, &newrightvec, &newupvec);
VNorm(&newupvec);
newviewvec = viewvec;
VNorm(&newviewvec);
scene->camzoom = zoom;
scene->aspectratio = aspectratio;
scene->antialiasing = antialiasing;
scene->raydepth = raydepth;
scene->camcent = camcent;
scene->camviewvec = newviewvec;
scene->camrightvec = newrightvec;
scene->camupvec = newupvec;
}
void rt_outputfile(SceneHandle voidscene, const char *outname) {
scenedef *scene = (scenedef *)voidscene;
strcpy((char *)&scene->outfilename, outname);
}
void rt_resolution(SceneHandle voidscene, int hres, int vres) {
scenedef *scene = (scenedef *)voidscene;
scene->hres = hres;
scene->vres = vres;
}
void rt_verbose(SceneHandle voidscene, int v) {
scenedef *scene = (scenedef *)voidscene;
scene->verbosemode = v;
}
void rt_rawimage(SceneHandle voidscene, unsigned char *rawimage) {
scenedef *scene = (scenedef *)voidscene;
scene->rawimage = rawimage;
}
void rt_background(SceneHandle voidscene, color col) {
scenedef *scene = (scenedef *)voidscene;
scene->background.r = col.r;
scene->background.g = col.g;
scene->background.b = col.b;
}
void rt_boundmode(SceneHandle voidscene, int mode) {
scenedef *scene = (scenedef *)voidscene;
scene->boundmode = mode;
}
void rt_boundthresh(SceneHandle voidscene, int threshold) {
scenedef *scene = (scenedef *)voidscene;
if (threshold > 1) {
scene->boundthresh = threshold;
}
else {
rtmesg("Ignoring out-of-range automatic bounding threshold.\n");
rtmesg("Automatic bounding threshold reset to default.\n");
scene->boundthresh = MAXOCTNODES;
}
}
void rt_displaymode(SceneHandle voidscene, int mode) {
scenedef *scene = (scenedef *)voidscene;
scene->displaymode = mode;
}
void rt_scenesetup(SceneHandle voidscene, char *outname, int hres, int vres, int verbose) {
rt_outputfile(voidscene, outname);
rt_resolution(voidscene, hres, vres);
rt_verbose(voidscene, verbose);
}
SceneHandle rt_newscene(void) {
scenedef *scene;
SceneHandle voidscene;
scene = (scenedef *)malloc(sizeof(scenedef));
memset(scene, 0, sizeof(scenedef)); /* clear all valuas to 0 */
voidscene = (SceneHandle)scene;
rt_outputfile(voidscene, "/dev/null"); /* default output file (.tga) */
rt_resolution(voidscene, 512, 512); /* 512x512 resolution */
rt_verbose(voidscene, 0); /* verbose messages off */
rt_rawimage(voidscene, nullptr); /* raw image output off */
rt_boundmode(voidscene, RT_BOUNDING_ENABLED); /* spatial subdivision on */
rt_boundthresh(voidscene, MAXOCTNODES); /* default threshold */
rt_displaymode(voidscene, RT_DISPLAY_ENABLED); /* video output on */
rt_camerasetup(voidscene,
1.0,
1.0,
0,
6,
rt_vector(0.0, 0.0, 0.0),
rt_vector(0.0, 0.0, 1.0),
rt_vector(0.0, 1.0, 0.0));
return scene;
}
void rt_deletescene(SceneHandle scene) {
if (scene != nullptr)
free(scene);
}
void apitextotex(apitexture *apitex, texture *tex) {
switch (apitex->texturefunc) {
case 0: tex->texfunc = (color(*)(void *, void *, void *))(standard_texture); break;
case 1: tex->texfunc = (color(*)(void *, void *, void *))(checker_texture); break;
case 2: tex->texfunc = (color(*)(void *, void *, void *))(grit_texture); break;
case 3: tex->texfunc = (color(*)(void *, void *, void *))(marble_texture); break;
case 4: tex->texfunc = (color(*)(void *, void *, void *))(wood_texture); break;
case 5: tex->texfunc = (color(*)(void *, void *, void *))(gnoise_texture); break;
case 6: tex->texfunc = (color(*)(void *, void *, void *))(cyl_checker_texture); break;
case 7:
tex->texfunc = (color(*)(void *, void *, void *))(image_sphere_texture);
tex->img = AllocateImage((char *)apitex->imap);
break;
case 8:
tex->texfunc = (color(*)(void *, void *, void *))(image_cyl_texture);
tex->img = AllocateImage((char *)apitex->imap);
break;
case 9:
tex->texfunc = (color(*)(void *, void *, void *))(image_plane_texture);
tex->img = AllocateImage((char *)apitex->imap);
break;
default: tex->texfunc = (color(*)(void *, void *, void *))(standard_texture); break;
}
tex->ctr = apitex->ctr;
tex->rot = apitex->rot;
tex->scale = apitex->scale;
tex->uaxs = apitex->uaxs;
tex->vaxs = apitex->vaxs;
tex->ambient = apitex->ambient;
tex->diffuse = apitex->diffuse;
tex->specular = apitex->specular;
tex->opacity = apitex->opacity;
tex->col = apitex->col;
tex->islight = 0;
tex->shadowcast = 1;
tex->phong = 0.0;
tex->phongexp = 0.0;
tex->phongtype = 0;
}
void *rt_texture(apitexture *apitex) {
texture *tex;
tex = (texture *)rt_getmem(sizeof(texture));
apitextotex(apitex, tex);
return (tex);
}
void rt_tex_color(void *voidtex, color col) {
texture *tex = (texture *)voidtex;
tex->col = col;
}
void rt_tex_phong(void *voidtex, apiflt phong, apiflt phongexp, int type) {
texture *tex = (texture *)voidtex;
tex->phong = phong;
tex->phongexp = phongexp;
tex->phongtype = type;
}
void rt_light(void *tex, vector ctr, apiflt rad) {
point_light *li;
li = newlight(tex, (vector)ctr, rad);
li->tex->islight = 1;
li->tex->shadowcast = 1;
li->tex->diffuse = 0.0;
li->tex->specular = 0.0;
li->tex->opacity = 1.0;
add_light(li);
add_object((object *)li);
}
void rt_scalarvol(void *tex,
vector min,
vector max,
int xs,
int ys,
int zs,
char *fname,
void *invol) {
add_object((object *)newscalarvol(
tex, (vector)min, (vector)max, xs, ys, zs, fname, (scalarvol *)invol));
}
void rt_extvol(void *tex, vector min, vector max, int samples, flt (*evaluator)(flt, flt, flt)) {
add_object((object *)newextvol(tex, (vector)min, (vector)max, samples, evaluator));
}
void rt_box(void *tex, vector min, vector max) {
add_object((object *)newbox(tex, (vector)min, (vector)max));
}
void rt_cylinder(void *tex, vector ctr, vector axis, apiflt rad) {
add_object(newcylinder(tex, (vector)ctr, (vector)axis, rad));
}
void rt_fcylinder(void *tex, vector ctr, vector axis, apiflt rad) {
add_object(newfcylinder(tex, (vector)ctr, (vector)axis, rad));
}
void rt_plane(void *tex, vector ctr, vector norm) {
add_object(newplane(tex, (vector)ctr, (vector)norm));
}
void rt_ring(void *tex, vector ctr, vector norm, apiflt a, apiflt b) {
add_object(newring(tex, (vector)ctr, (vector)norm, a, b));
}
void rt_sphere(void *tex, vector ctr, apiflt rad) {
add_object(newsphere(tex, (vector)ctr, rad));
}
void rt_tri(void *tex, vector v0, vector v1, vector v2) {
object *trn;
trn = newtri(tex, (vector)v0, (vector)v1, (vector)v2);
if (trn != nullptr) {
add_object(trn);
}
}
void rt_stri(void *tex, vector v0, vector v1, vector v2, vector n0, vector n1, vector n2) {
object *trn;
trn = newstri(tex, (vector)v0, (vector)v1, (vector)v2, (vector)n0, (vector)n1, (vector)n2);
if (trn != nullptr) {
add_object(trn);
}
}
void rt_quadsphere(void *tex, vector ctr, apiflt rad) {
quadric *q;
flt factor;
q = (quadric *)newquadric();
factor = 1.0 / (rad * rad);
q->tex = (texture *)tex;
q->ctr = ctr;
q->mat.a = factor;
q->mat.b = 0.0;
q->mat.c = 0.0;
q->mat.d = 0.0;
q->mat.e = factor;
q->mat.f = 0.0;
q->mat.g = 0.0;
q->mat.h = factor;
q->mat.i = 0.0;
q->mat.j = -1.0;
add_object((object *)q);
}
| 28.76399 | 97 | 0.630604 | [
"render",
"object",
"vector"
] |
2471bbfb17c7f4c22b3836da0ab3036c3eed315c | 2,223 | hpp | C++ | src/Consumer/LB_Basic.hpp | kit-algo/fpt-editing | 74620a1b4eca14920a05d8c9e74bdbfc9a4808a5 | [
"MIT"
] | 1 | 2021-02-18T14:09:04.000Z | 2021-02-18T14:09:04.000Z | src/Consumer/LB_Basic.hpp | kit-algo/fpt-editing | 74620a1b4eca14920a05d8c9e74bdbfc9a4808a5 | [
"MIT"
] | null | null | null | src/Consumer/LB_Basic.hpp | kit-algo/fpt-editing | 74620a1b4eca14920a05d8c9e74bdbfc9a4808a5 | [
"MIT"
] | null | null | null | #ifndef CONSUMER_LOWER_BOUND_BASIC_HPP
#define CONSUMER_LOWER_BOUND_BASIC_HPP
#include <vector>
#include "../config.hpp"
#include "../Options.hpp"
#include "../Finder/Finder.hpp"
#include "../Finder/SubgraphStats.hpp"
#include "../LowerBound/Lower_Bound.hpp"
#include "Base_No_Updates.hpp"
namespace Consumer
{
template<typename Finder_impl, typename Graph, typename Graph_Edits, typename Mode, typename Restriction, typename Conversion, size_t length>
class Basic : Options::Tag::Lower_Bound, public Base_No_Updates<Finder_impl, Graph, Graph_Edits, Mode, Restriction, Conversion, length>
{
public:
static constexpr char const *name = "Basic";
using Lower_Bound_Storage_type = ::Lower_Bound::Lower_Bound<Mode, Restriction, Conversion, Graph, Graph_Edits, length>;
using subgraph_t = typename Lower_Bound_Storage_type::subgraph_t;
using State = typename Base_No_Updates<Finder_impl, Graph, Graph_Edits, Mode, Restriction, Conversion, length>::State;
using Subgraph_Stats_type = ::Finder::Subgraph_Stats<Finder_impl, Graph, Graph_Edits, Mode, Restriction, Conversion, length>;
private:
Graph_Edits used;
Finder_impl finder;
public:
Basic(VertexID graph_size) : used(graph_size), finder(graph_size) {}
size_t result(State&, const Subgraph_Stats_type&, size_t k, Graph const &graph, Graph_Edits const &edited, Options::Tag::Lower_Bound)
{
used.clear();
size_t found = 0;
#ifndef NDEBUG
Lower_Bound_Storage_type lower_bound;
#endif
finder.find(graph, [&](const subgraph_t& path)
{
bool skip = Finder::for_all_edges_unordered<Mode, Restriction, Conversion>(graph, edited, path.begin(), path.end(), [&](auto uit, auto vit) {
return used.has_edge(*uit, *vit);
});
if (skip)
{
return false;
}
#ifndef NDEBUG
lower_bound.add(path);
#endif
Finder::for_all_edges_unordered<Mode, Restriction, Conversion>(graph, edited, path.begin(), path.end(), [&](auto uit, auto vit) {
used.set_edge(*uit, *vit);
return false;
});
++found;
return found > k;
}, used);
#ifndef NDEBUG
if (found <= k) {
lower_bound.assert_maximal(graph, edited, finder);
}
#endif
return found;
}
};
}
#endif
| 27.7875 | 145 | 0.711651 | [
"vector"
] |
248f616f9579cb03568303cea91e2428d428d372 | 1,297 | cpp | C++ | aws-cpp-sdk-rekognition/source/model/FaceDetection.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-rekognition/source/model/FaceDetection.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-rekognition/source/model/FaceDetection.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/rekognition/model/FaceDetection.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Rekognition
{
namespace Model
{
FaceDetection::FaceDetection() :
m_timestamp(0),
m_timestampHasBeenSet(false),
m_faceHasBeenSet(false)
{
}
FaceDetection::FaceDetection(JsonView jsonValue) :
m_timestamp(0),
m_timestampHasBeenSet(false),
m_faceHasBeenSet(false)
{
*this = jsonValue;
}
FaceDetection& FaceDetection::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Timestamp"))
{
m_timestamp = jsonValue.GetInt64("Timestamp");
m_timestampHasBeenSet = true;
}
if(jsonValue.ValueExists("Face"))
{
m_face = jsonValue.GetObject("Face");
m_faceHasBeenSet = true;
}
return *this;
}
JsonValue FaceDetection::Jsonize() const
{
JsonValue payload;
if(m_timestampHasBeenSet)
{
payload.WithInt64("Timestamp", m_timestamp);
}
if(m_faceHasBeenSet)
{
payload.WithObject("Face", m_face.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace Rekognition
} // namespace Aws
| 16.844156 | 69 | 0.706245 | [
"model"
] |
24981c0e41145aea0937972a443dbfed3ec735b3 | 6,316 | cpp | C++ | modules/cuda_plugin/src/ops/lstm_sequence.cpp | YUNEEC/openvino_contrib | 6a79637583fadd22e01d31b912d94d7a27cc78ba | [
"Apache-2.0"
] | null | null | null | modules/cuda_plugin/src/ops/lstm_sequence.cpp | YUNEEC/openvino_contrib | 6a79637583fadd22e01d31b912d94d7a27cc78ba | [
"Apache-2.0"
] | null | null | null | modules/cuda_plugin/src/ops/lstm_sequence.cpp | YUNEEC/openvino_contrib | 6a79637583fadd22e01d31b912d94d7a27cc78ba | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "lstm_sequence.hpp"
#include <cuda_operation_registry.hpp>
#include <gsl/gsl_assert>
#include <utility>
#include <vector>
#include "lstm_sequence_components.hpp"
namespace CUDAPlugin {
LSTMSequenceOp::LSTMSequenceOp(const CreationContext& context,
const NodeOp& node,
IndexCollection&& inputIds,
IndexCollection&& outputIds)
: LSTMSequenceOpBase(context, LSTMSequenceParams{node}, config(), node, std::move(inputIds), std::move(outputIds)) {
using LSTMSequenceArgIndices = CUDAPlugin::RNN::Details::LSTMSequenceArgIndices;
const int64_t batch_size = params_.batch_size_;
const int64_t num_directions = params_.numDirections();
const int64_t hidden_size = params_.hidden_size_;
const int64_t input_size = params_.input_size_;
const int64_t max_seq_length = params_.max_seq_length_;
const auto& x_shape = node.get_input_shape(LSTMSequenceArgIndices::x);
Expects(x_shape.size() == 3);
Expects(x_shape[0] == batch_size);
Expects(x_shape[1] == max_seq_length);
Expects(x_shape[2] == input_size);
const auto& hx_shape = node.get_input_shape(LSTMSequenceArgIndices::hidden_input);
Expects(hx_shape.size() == 3);
Expects(hx_shape[0] == batch_size);
Expects(hx_shape[1] == num_directions);
Expects(hx_shape[2] == hidden_size);
const auto& cx_shape = node.get_input_shape(LSTMSequenceArgIndices::cell_input);
Expects(cx_shape.size() == 3);
Expects(cx_shape[0] == batch_size);
Expects(cx_shape[1] == num_directions);
Expects(cx_shape[2] == hidden_size);
const auto& y_shape = node.get_output_shape(LSTMSequenceArgIndices::y);
Expects(y_shape.size() == 4);
Expects(y_shape[0] == batch_size);
Expects(y_shape[1] == num_directions);
Expects(y_shape[2] == max_seq_length);
Expects(y_shape[3] == hidden_size);
const auto& hy_shape = node.get_output_shape(LSTMSequenceArgIndices::hidden_output);
Expects(hy_shape.size() == 3);
Expects(hy_shape[0] == batch_size);
Expects(hy_shape[1] == num_directions);
Expects(hy_shape[2] == hidden_size);
const auto& cy_shape = node.get_output_shape(LSTMSequenceArgIndices::cell_output);
Expects(cy_shape.size() == 3);
Expects(cy_shape[0] == batch_size);
Expects(cy_shape[1] == num_directions);
Expects(cy_shape[2] == hidden_size);
setupLayoutAdapters();
calcAdapterWorkbuffers();
}
LSTMSequenceOpBase::Config LSTMSequenceOp::config() {
LSTMSequenceOpBase::Config config{};
config.rnn_data_layout = CUDNN_RNN_DATA_LAYOUT_BATCH_MAJOR_UNPACKED;
return config;
}
void LSTMSequenceOp::setupLayoutAdapters() {
using InputAdapter = RNN::Details::TransposeInputTensorAdapter;
using OutputAdapter = RNN::Details::TransposeOutputTensorAdapter;
const int64_t batch_size = params_.batch_size_;
const int64_t num_directions = params_.numDirections();
const int64_t hidden_size = params_.hidden_size_;
const int64_t max_seq_length = params_.max_seq_length_;
// Determine whether it's necessary to transpose input state tensors to make OpenVINO state inputs binary compatible
// with cuDNN API.
const std::vector<int64_t> state_shape_openvino = {batch_size, num_directions, hidden_size};
const std::vector<int64_t> state_shape_cudnn = {num_directions, batch_size, hidden_size};
const bool transposeStateInputs = (batch_size > 1) && (num_directions > 1);
if (transposeStateInputs) {
hx_adapter = std::make_unique<InputAdapter>(params_.element_type_cuda_,
params_.element_size_,
state_shape_openvino,
state_shape_cudnn,
std::vector<int>{1, 0, 2});
cx_adapter = std::make_unique<InputAdapter>(params_.element_type_cuda_,
params_.element_size_,
state_shape_openvino,
state_shape_cudnn,
std::vector<int>{1, 0, 2});
}
// Determine whether it's necessary to transpose output state tensors to make cuDNN API outputs binary compatible
// with OpenVINO.
const bool transposeStateOutputs = (batch_size > 1) && (num_directions > 1);
if (transposeStateOutputs) {
hy_adapter = std::make_unique<OutputAdapter>(params_.element_type_cuda_,
params_.element_size_,
state_shape_cudnn,
state_shape_openvino,
std::vector<int>{1, 0, 2});
cy_adapter = std::make_unique<OutputAdapter>(params_.element_type_cuda_,
params_.element_size_,
state_shape_cudnn,
state_shape_openvino,
std::vector<int>{1, 0, 2});
}
// Determine whether it's necessary to transpose output Y tensor to make cuDNN API output binary compatible with
// OpenVINO.
const std::vector<int64_t> y_shape_openvino = {batch_size, num_directions, max_seq_length, hidden_size};
const std::vector<int64_t> y_shape_cudnn = {batch_size, max_seq_length, num_directions, hidden_size};
const bool transposeY = (num_directions > 1) && (max_seq_length > 1);
if (transposeY) {
y_adapter = std::make_unique<OutputAdapter>(params_.element_type_cuda_,
params_.element_size_,
y_shape_cudnn,
y_shape_openvino,
std::vector<int>{0, 2, 1, 3});
}
}
OPERATION_REGISTER(LSTMSequenceOp, LSTMSequence);
} // namespace CUDAPlugin
| 46.785185 | 120 | 0.606396 | [
"vector"
] |
2498301e05fa9b9f9958a0fe1db8dec570aac249 | 768 | cpp | C++ | src/UiElement.cpp | Doctor-Ned/OpenGLPAG | 3cebddc2f7700920ec2b7c8f8983993651a64d9b | [
"MIT"
] | null | null | null | src/UiElement.cpp | Doctor-Ned/OpenGLPAG | 3cebddc2f7700920ec2b7c8f8983993651a64d9b | [
"MIT"
] | null | null | null | src/UiElement.cpp | Doctor-Ned/OpenGLPAG | 3cebddc2f7700920ec2b7c8f8983993651a64d9b | [
"MIT"
] | null | null | null | #include "UiElement.h"
UiElement::UiElement(Shader* shader, const char* texture, glm::vec2 position, glm::vec2 size, bool center) {
if (texture != nullptr) {
this->texture = createTexture(texture);
}
this->shader = shader;
this->position = position;
this->size = size;
this->center = center;
if (center) {
actualPosition = glm::vec2(position.x - size.x / 2.0f, position.y - size.y / 2.0f);
}
else {
actualPosition = position;
}
}
void UiElement::render() {
shader->use();
shader->setProjection(projection);
}
glm::vec2 UiElement::getPosition() {
return actualPosition;
}
glm::vec2 UiElement::getCenter() {
return glm::vec2(actualPosition.x + size.x / 2.0f, actualPosition.y + size.y / 2.0f);
}
glm::vec2 UiElement::getSize() {
return size;
}
| 21.942857 | 108 | 0.677083 | [
"render"
] |
249aabdda0f255207233bfd91adcf58c5b579f4c | 10,502 | cpp | C++ | build-bot/main.cpp | hbirchtree/coffeecutie-build-daemon | f29ce65896822d4f1358fee5b20c25e54ec1864f | [
"MIT"
] | null | null | null | build-bot/main.cpp | hbirchtree/coffeecutie-build-daemon | f29ce65896822d4f1358fee5b20c25e54ec1864f | [
"MIT"
] | 2 | 2016-06-06T19:31:16.000Z | 2017-01-30T12:46:30.000Z | build-bot/main.cpp | hbirchtree/coffeecutie-build-daemon | f29ce65896822d4f1358fee5b20c25e54ec1864f | [
"MIT"
] | null | null | null | #include "fun_helpers.h"
#include <coffee/core/CApplication>
#include <coffee/core/CDebug>
#include <coffee/core/CArgParser>
cstring git_program = "git";
cstring cmake_program = "cmake";
DataSet create_item(cstring file)
{
/* Clear all structures */
DataSet repo = {};
BuildEnvironment& repo_data = repo.repo;
repo.temp = {};
repo.temp.last_commit = {};
/* Default, sane values */
repo_data.r_cfg.branch = "master";
repo_data.r_cfg.upstream = "origin";
repo_data.b_cfg.interval = 3600;
repo_data.b_cfg.repodir = Env::CurrentDir();
repo_data.b_cfg.build = Env::CurrentDir();
CString build_sys = "cmake";
JSON::Document doc;
/* Open source file */
{
CResources::Resource resc(file);
CResources::FileMap(resc);
/* If file not found, no source to add */
if(!resc.data)
return {};
/* Copy data string */
{
CString data_string;
data_string.insert(0,(cstring)resc.data,resc.size);
CResources::FileUnmap(resc);
/* Open JSON document from file, it contains all the information */
doc = JSON::Read(data_string.c_str());
}
if(!doc.IsObject())
return {};
}
/* Extract root object and get the data */
{
JSON::Value doc_ = doc.GetObject();
/* Various flags */
if(doc_.HasMember("cleans")&&doc_["cleans"].GetBool())
repo_data.flags |= CleanAlways;
if(doc_.HasMember("nofail")&&doc_["nofail"].GetBool())
repo_data.flags |= IgnoreFailure;
/* Server information */
repo_data.server.addr = JSGetString(doc_,"server:address");
if(doc_.HasMember("server:port")&&doc_["server:port"].IsUint())
repo_data.server.port = doc_["server:port"].GetUint();
/* Repository information */
repo_data.r_cfg.repository = JSGetString(doc_,"repository");
repo_data.r_cfg.upstream = JSGetString(doc_,"upstream");
repo_data.r_cfg.branch = JSGetString(doc_,"branch");
/* Filesystem locations */
repo_data.b_cfg.repodir = JSGetString(doc_,"repo-dir");
repo_data.b_cfg.build = JSGetString(doc_,"build-dir");
/* Build information */
build_sys = JSGetString(doc_,"build-type");
repo_data.b_cfg.system = JSGetString(doc_,"target");
/* Update rate */
if(doc_.HasMember("interval"))
repo_data.b_cfg.interval = doc_["interval"].GetUint64();
}
/* Create a list of commands based on build system preference */
Vector<Proc_Cmd>& cmd_queue = repo_data.b_cfg.queue;
if(build_sys == "cmake")
{
cstring upstream = repo_data.r_cfg.upstream.c_str();
cstring branch = repo_data.r_cfg.branch.c_str();
cstring build_dir = repo_data.b_cfg.build.c_str();
cstring repo_dir = repo_data.b_cfg.repodir.c_str();
cmd_queue.push_back({git_program,{"-C",repo_dir,"pull",upstream,branch},{}});
if((repo_data.flags&CleanAlways))
cmd_queue.push_back({cmake_program,{"--build",build_dir,"--target","clean"},{}});
cmd_queue.push_back({cmake_program,{"--build",build_dir,"--target","install"},{}});
}else{
cWarning("Unrecognized build system: {0}",build_sys);
}
/* Create stream and MIME-type preferences */
repo.temp.expect_type = "application/atom+xml; charset=utf-8";
REST::Request& request = repo.temp.request;
{
HTTP::InitializeRequest(request);
request.transp = REST::HTTPS;
request.values["Accept"] = "application/atom+xml";
request.resource = cStringFormat("/{0}/commits/{1}.atom",
repo_data.r_cfg.repository,
repo_data.r_cfg.branch);
}
/* Print preferences back to user */
cBasicPrint("\nConfigured target:\n"
"repository = {0}\n"
"branch = {5}\n"
"upstream = {6}\n"
"repository-dir = {1}\n"
"build-dir = {2}\n"
"interval = {3}\n"
"build-system = {4}\n"
"build-flags = {7}\n",
repo_data.r_cfg.repository,
repo_data.b_cfg.repodir,
repo_data.b_cfg.build,
repo_data.b_cfg.interval,
build_sys,
repo_data.r_cfg.branch,
repo_data.r_cfg.upstream,
repo_data.flags);
return repo;
}
FailureCase update_item(BuildEnvironment const& data, Repository_tmp* workarea)
{
/* If it is not our time, don't do anything */
if(Time::CurrentTimestamp() < workarea->wakeup)
return Nothing;
/* Set global variables for server and system configuration */
if(!data.b_cfg.system.empty())
crosscompiling = data.b_cfg.system.c_str();
else
crosscompiling = nullptr;
buildrep_server = data.server.addr.c_str();
buildrep_server_port = data.server.port;
/* References for faster typing */
uint64 const& interval = data.b_cfg.interval;
REST::Request const& request = workarea->request;
CString const& expect_type = workarea->expect_type;
CString const& repo = data.r_cfg.repository;
Vector<Proc_Cmd> const command_queue = data.b_cfg.queue;
cBasicPrint("WORKING ON: {0}",repo);
/* Make a request for the latest commits */
auto response = REST::RestRequest("github.com",request);
/* If not successful, fail and die */
if(response.code != 200 && !(data.flags&IgnoreFailure))
return FeedFetchFailed;
/* Only proceed if MIME-type is correct */
if(REST::GetContentType(response) == expect_type)
{
/* Extract Atom feed and find latest commit (first in list, hopefully) */
XML::Document* doc = XML::XMLRead(
BytesConst{(byte_t*)response.payload.c_str(),response.payload.size()});
XML::Element* feed = doc->FirstChildElement("feed");
/* If failed to get first feed, die */
if(!feed)
{
if(!(data.flags&IgnoreFailure))
return XMLParseFailed;
}else{
/* Get information on latest commit in simple format */
GitCommit cmt = ParseEntry(feed->FirstChildElement("entry"));
/* If this new commit is later than our current, go ahead and build */
if(workarea->last_commit < cmt)
{
workarea->last_commit = cmt;
cBasicPrint("Updated repository: {0}, commit={1}, ts={2}",
repo,cmt.hash,cmt.ts);
/* Execute command queue, die if error */
uint16 signal = 0;
CString log;
uint64 timer = Time::CurrentMicroTimestamp();
for (Proc_Cmd const& cmd : command_queue)
{
cBasicPrintNoNL("Running: {0}",cmd.program);
for(CString const& a : cmd.argv)
cBasicPrintNoNL(" {0}",a);
cBasicPrintNoNL("\n");
/* Execute command, capturing log and signal */
int sig = Proc::ExecuteLogged(cmd, &log);
if (sig != 0)
{
/* On failure, either submit with error or return */
signal = 1;
cBasicPrint("Failed with signal {0}:\n{1}", sig, log);
if(!(data.flags&IgnoreFailure))
return ProcessFailed;
break;
}
}
/* Send build report */
ReportBuildStatus(signal,cmt.hash,log,Time::CurrentMicroTimestamp()-timer);
}else{
cWarning("Mismatch commit, latest is commit={0}, ts={1}",
workarea->last_commit.hash,workarea->last_commit.ts);
}
}
delete doc;
}else{
cWarning("Content mismatch: \"{0}\", expected \"{1}\"",
REST::GetContentType(response),
expect_type);
return XMLParseFailed;
}
/* Find out when to wake up next time */
workarea->wakeup = Time::CurrentTimestamp()+interval;
cBasicPrint("Sleeping again, waking up at {0}",
Time::LocalTimeString(workarea->wakeup));
cBasicPrint("");
return Nothing;
}
int32 coffee_main(int32 argc, cstring_w* argv)
{
Vector<DataSet> datasets;
{
ArgumentCollection args;
/* Allow customizing path to Git and CMake, for Windows */
args.registerArgument(ArgumentCollection::Argument,"help");
args.registerArgument(ArgumentCollection::Argument,"gitbin");
args.registerArgument(ArgumentCollection::Argument,"cmakebin");
args.parseArguments(argc,argv);
for(std::pair<CString,cstring> const& arg : args.getArgumentOptions())
{
if(arg.first == "help" && arg.second)
{
cBasicPrint("{0} [options] {configs (.json)}\n"
"Options available:\n"
" --help Show this message and exit\n"
" --gitbin [bin] Specify Git binary\n"
" --cmakebin [bin] Specify CMake binary\n",
Env::ExecutableName());
return 0;
}
else if(arg.first == "gitbin" && arg.second)
git_program = arg.second;
else if(arg.first == "cmakebin" && arg.second)
cmake_program = arg.second;
}
/* All positional arguments are interpreted as file paths */
for(cstring it : args.getPositionalArguments())
{
datasets.push_back(create_item(it));
}
}
/* Will not enter loop if no work items are found */
if(datasets.size() == 0)
return 0;
cDebug("Got {0} datasets\n",datasets.size());
/* Start the REST service */
REST::InitService();
cDebug("Launched BuildBot");
/* Initiate blast processing, watch processor burn */
while(true)
{
for(DataSet& e : datasets)
{
int sig = update_item(e.repo, &e.temp);
if (sig != Nothing)
return sig;
}
Threads::sleepMillis(250);
}
}
COFFEE_APPLICATION_MAIN(coffee_main);
| 33.660256 | 93 | 0.557513 | [
"object",
"vector"
] |
249d0768425e28a7ce6064d008e3f62f20c27619 | 7,254 | hpp | C++ | include/VertexWeights.hpp | tillhainbach/FastEMD | d21dbb77a5dc96c82aab3da914ad5cd990c317c9 | [
"BSD-3-Clause"
] | 4 | 2020-02-12T20:23:02.000Z | 2021-12-04T02:38:36.000Z | include/VertexWeights.hpp | tillhainbach/FastEMD | d21dbb77a5dc96c82aab3da914ad5cd990c317c9 | [
"BSD-3-Clause"
] | 3 | 2020-03-24T08:54:29.000Z | 2020-04-02T13:41:03.000Z | include/VertexWeights.hpp | tillhainbach/FastEMD | d21dbb77a5dc96c82aab3da914ad5cd990c317c9 | [
"BSD-3-Clause"
] | null | null | null | //
// VertexWeights.hpp
// FastEMD
//
// Created by Till Hainbach on 23.03.20.
// Copyright © 2020 Till Hainbach. All rights reserved.
//
#ifndef VertexWeights_h
#define VertexWeights_h
#include "VertexBaseContainer.hpp"
#include "Counter.hpp"
namespace FastEMD
{
using namespace types;
//MARK: Vertex Weights Class
template<typename NUM_T, typename INTERFACE_T, NODE_T SIZE = 0>
class VertexWeights : public VertexBaseContainer<NUM_T, INTERFACE_T, SIZE, 1>
{
public:
//MARK: Initializer
VertexWeights(NODE_T numberOfNodes)
: VertexBaseContainer<NUM_T, INTERFACE_T, SIZE, 1>(numberOfNodes,
"Vertex Weights",
{"weight"}) {};
VertexWeights(std::vector<NUM_T> _data)
: VertexBaseContainer<NUM_T, INTERFACE_T, SIZE, 1>(_data,
"Vertex Weights",
{"weight"}) {};
//MARK: Setters
template<typename _T>
NUM_T fillWeights(const _T& P, const _T& Q,
Counter<NUM_T, INTERFACE_T, SIZE/2>& nonZeroSourceNodes,
Counter<NUM_T, INTERFACE_T, SIZE/2>& nonZeroSinkNodes);
template<typename _T>
void preFlowWeights(const _T& P, const _T& Q);
void swapWeights();
//MARK: Getters
void calcPreFlowCost(
Counter<NUM_T, INTERFACE_T, SIZE/2> const& sinkNodes,
Counter<NUM_T, INTERFACE_T, SIZE/2>& uniqueJs,
NUM_T maxC, NODE_T costSize);
auto sum() const {NUM_T sum = 0; for (auto e: *this) sum += e; return sum;}
NUM_T preFlowCost = 0;
template<typename _T, typename _I, NODE_T _S>
friend std::ostream& operator<<(std::ostream& os,
const VertexWeights<_T, _I, _S>& container);
};
//MARK: Implementations
template<typename NUM_T, typename INTERFACE_T, NODE_T SIZE>
template<typename _T>
NUM_T VertexWeights<NUM_T, INTERFACE_T, SIZE>::fillWeights(
_T const & P, _T const & Q,
Counter<NUM_T, INTERFACE_T, SIZE/2> & nonZeroSourceNodes,
Counter<NUM_T, INTERFACE_T, SIZE/2> & nonZeroSinkNodes)
{
NODE_T nonZeroSourceCounter = 0, nonZeroSinkCounter = 0;
NUM_T sum_P = 0, sum_Q = 0;
NODE_T const N = static_cast<NODE_T>(P.size());
for (NODE_T i = 0; i < N; ++i)
{
NUM_T tempSum = P[i] - Q[i];
switch (static_cast<unsigned char>(tempSum > 0)) // P[i] > Q[i]
{
case 0:
switch (static_cast<unsigned char>(tempSum < 0))
{
case 0: // P[i] == Q[i]
//TODO: implement flow if (FLOW_TYPE != NO_FLOW) ((*F)[i][i]) = Q[i];
(*this)[i] = (*this)[i + N] = 0;
break;
case 1: // P[i] < Q[i]
//TODO: implement flow if (FLOW_TYPE != NO_FLOW) ((*F)[i][i]) = P[i];
sum_Q -= tempSum;
(*this)[i] = 0;
(*this)[i + N] = tempSum;
nonZeroSinkNodes[nonZeroSinkCounter++] = i;
break;
} // inner switch
break;
case 1: // P[i] > Q[i]
//TODO: implement flow if (FLOW_TYPE != NO_FLOW) ((*F)[i][i]) = Q[i];
sum_P += tempSum;
(*this)[i] = tempSum;
(*this)[i + N] = 0;
nonZeroSourceNodes[nonZeroSourceCounter++] = i;
break;
} // outer switch
}
nonZeroSourceNodes.resize(nonZeroSourceCounter);
nonZeroSinkNodes.resize(nonZeroSinkCounter);
//TODO: untangle this function into several smaller functions...
#if PRINT && DEBUG
std::cout << *this << std::endl;
std::cout << nonZeroSourceNodes << std::endl;
std::cout << nonZeroSinkNodes << std::endl;
#endif
//MARK: Ensuring that the supplier - P, has more mass.
NUM_T abs_diff_sum_P_sum_Q = std::abs(sum_P - sum_Q);
if (sum_Q > sum_P)
{
this->swapWeights();
std::swap(nonZeroSourceNodes, nonZeroSinkNodes);
#if PRINT && DEBUG
std::cout << "needToSwapFlow" << std::endl;
std::cout << nonZeroSourceNodes << std::endl;
std::cout << nonZeroSinkNodes << std::endl;
#endif
}
/* remark*) I put here a deficit of the extra mass, as mass that flows
to the threshold node can be absorbed from all sources with cost zero
(this is in reverse order from the paper, where incoming edges to the
threshold node had the cost of the threshold and outgoing edges had
the cost of zero) This also makes sum of b zero. */
*(this->thresholdNode()) = -abs_diff_sum_P_sum_Q;
return abs_diff_sum_P_sum_Q;
}
template<typename NUM_T, typename INTERFACE_T, NODE_T SIZE>
void VertexWeights<NUM_T, INTERFACE_T, SIZE>::swapWeights()
{
NODE_T N = (this->_numberOfNodes - 2) / 2;
std::swap_ranges(this->begin(), this->begin() + N, this->begin() + N);
std::transform(this->begin(), this->end(), this->begin(),
std::bind(std::multiplies<NUM_T>(),
std::placeholders::_1, -1));
}
template<typename NUM_T, typename INTERFACE_T, NODE_T SIZE>
void VertexWeights<NUM_T, INTERFACE_T, SIZE>::calcPreFlowCost(
Counter<NUM_T, INTERFACE_T, SIZE/2> const & sinkNodes,
Counter<NUM_T, INTERFACE_T, SIZE/2>& sinkNodeGetsFlowOnlyFromThreshold,
NUM_T maxC, NODE_T costSize)
{
// calculate pre_flow_cost & add weight to this->_thresholdNodeIndex
// reorder b array so that all weights are in range [0, sourcesCounter + sinksCounter + 2];
auto N = (this->size() - 2)/2;
int shrinkCounter = costSize - sinkNodes.size() - 2;
// for each sink node check whether it gets flow only from threshold node
// if true add its weight to Threshold Node else move it weight to new position
for(auto j : sinkNodes)
{
auto weight = (*this)[j + N];
if (sinkNodeGetsFlowOnlyFromThreshold[j] && weight != 0)
{
preFlowCost -= (weight * maxC);
*this->thresholdNode() += weight;
}
else // (sinkNodeGetsFlowOnlyFromThreshold[j] != 0)
{
sinkNodeGetsFlowOnlyFromThreshold[j] = shrinkCounter;
(*this)[shrinkCounter++] = weight;
}
}
// move this->_thresholdNodeIndex weight;
(*this)[shrinkCounter] = *this->thresholdNode();
// resize weights to new SIZE
this->resize(costSize);
// add zero-weight Artificial node
*this->artificialNode() = 0; //Artificialnode;
}
template<typename NUM_T, typename INTERFACE_T, NODE_T SIZE>
std::ostream& operator<<(std::ostream& os,
const VertexWeights<NUM_T, INTERFACE_T, SIZE>& container)
{
// Print the container name.
os << container._containerName << ": ";
// Print one line describing the containing data.
// Now, print the actual data.
for(auto element : container)
{
os << element << " ";
}
return os;
}
} // namespace FastEMD
#endif /* VertexWeights_h */
| 34.875 | 95 | 0.57389 | [
"vector",
"transform"
] |
249d59f59c4e67cb34a5a942252cdc5b3da6661e | 10,909 | hpp | C++ | Physics/Vec3D.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | Physics/Vec3D.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | Physics/Vec3D.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file Vec3D.hpp
Vec3D class header file
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\author Maciej Nicewicz \n
UCLA \n
nicewicz@physics.ucla.edu \n
\author Vladimir Vassiliev \n
UCLA \n
vvv@astro.ucla.edu \n
\date 11/09/2004
\version 1.2
\note
*/
#ifndef PHYSICS_VEC3D_H
#define PHYSICS_VEC3D_H
#ifndef __VS_NO_IOSTREAM
#include <iostream>
#endif
#include <cmath>
#include <RandomNumbers.hpp>
/*! \class Vec3D
\brief 3 dimensional vector class
This class defines 3D vectors, set of operations
in vector field, scalar and vector products,
as well as rotation, parity transformation, negation,
and normalization.
*/
namespace Physics
{
class Vec3D
{
public:
inline Vec3D(); //!<default constructor
inline Vec3D(const Vec3D& v); //!<copy constructor
inline Vec3D( double _x, double _y, double _z ); //!<overloaded constructor
inline void Polar(double& r, double& theta, double& phi) const;
inline double Norm() const; //!<calculates norm
inline double Norm2() const; //!<calculates scalar product with itself
void Rotate(const Vec3D& axis); //!<rotates vector around axis
inline void P(); //!<parity transformation
inline void Reflect(const Vec3D& norm); //!reflect in normal
void ScatterDirection(double dispersion, RandomNumbers& rng);
inline Vec3D& Reset(const Vec3D& v = Vec3D());
inline Vec3D& Reset(double _x, double _y, double _z);
inline Vec3D& operator = ( const Vec3D& v ); //!<assignment
inline Vec3D& operator += ( const Vec3D& v ); //!<assignment: addition
inline Vec3D& operator -= ( const Vec3D& v ); //!<assignment: subtraction
inline Vec3D& operator ^= ( const Vec3D& v ); //!<vector product
inline Vec3D& operator *= ( double d ); //!<assignment: multiply by scaler
inline Vec3D& operator /= ( double d ); //!<assignment: divide by scaler
Vec3D& operator &= (const Vec3D& r); //!<assignment: composition of rotations
inline Vec3D operator + (const Vec3D& v) const; //!<addition
inline Vec3D operator - (const Vec3D& v) const; //!<subtraction
inline double operator * (const Vec3D& v) const; //!<scalar product
inline Vec3D operator ^ (const Vec3D& v) const; //!<vector product
inline Vec3D operator & (const Vec3D& v) const; //!<addition of rotations
#ifndef __VS_NO_IOSTREAM
void Dump(std::ostream& stream = std::cout) const; //!<prints coordinates
void DumpShort(std::ostream& stream = std::cout) const; //!<prints coordinates
#endif
inline Vec3D DeRotate(const Vec3D& r) const;
public:
double x, y, z; //!<components
private:
static const double SMALLEST_ROTATION_ANGLE = 1e-9;
};
inline Vec3D operator - ( const Vec3D& v ); //!<negation
inline Vec3D operator * ( double d, const Vec3D& v ); //!<left scalar mult.
inline Vec3D operator * ( const Vec3D& v, double d ); //!<right scalar mult.
inline Vec3D operator / ( const Vec3D& v, double d ); //!<right scalar division
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Default class constructor
inline Vec3D::Vec3D(): x(), y(), z()
{
// nothing to see here
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Copy constructor
// \param o: Vector to copy
inline Vec3D::Vec3D(const Vec3D& o): x(o.x), y(o.y), z(o.z)
{
// nothing to see here
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Overloaded class constructor
/// \param _x: x
/// \param _y: y
/// \param _z: z
inline Vec3D::Vec3D( double _x, double _y, double _z ): x(_x), y(_y), z(_z)
{
// nothing to see here
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Method for vector norm
/// \param _r: r
/// \param _theta: theta
/// \param _phi: phi
inline void Vec3D::Polar(double& r, double& theta, double& phi) const
{
r=Norm();
theta = atan(sqrt(x*x+y*y)/z);
phi = atan2(y,x);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Method for vector norm
inline double Vec3D::Norm() const
{
return sqrt(x*x + y*y + z*z);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Method for vector norm in square
inline double Vec3D::Norm2() const
{
return x*x + y*y + z*z;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Method for parity transformation of vector
inline void Vec3D::P()
{
*this=-(*this);
return;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Method for reflection of vector in mirror
inline void Vec3D::Reflect(const Vec3D& norm) //!reflect in normal
{
double n2 = norm.Norm2();
if(n2 == 0)return;
*this -= norm * (2.0*((*this)*norm)/n2);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Reset the vector (assignment)
/// \param v: vector
inline Vec3D& Vec3D::Reset(const Vec3D& v)
{
return *this = v;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Reset the vector components
/// \param _x: x
/// \param _y: y
/// \param _z: z
inline Vec3D& Vec3D::Reset(double _x, double _y, double _z)
{
x = _x;
y = _y;
z = _z;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Assignment operator =
inline Vec3D& Vec3D::operator = ( const Vec3D& v )
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Assignment operator +=
inline Vec3D& Vec3D::operator += ( const Vec3D& v )
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Assignment operator -=
inline Vec3D& Vec3D::operator -= ( const Vec3D& v )
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Assignment operator ^= vector multiplication
/// \param v: vector
/*! \note
Normally ^ operator is a bitwise exclusive OR, which
has precedence lower than * / and even lower than + -.
Thus it is executed last if no brackets are used.
Exmp: r=7.5*a+l*b-c*m+2*b^c=(7.5*a+l*b-c*m+2*b)^c
See examples file exmp_Vec3D.cpp for additional
comment(s)
*/
inline Vec3D& Vec3D::operator ^= ( const Vec3D& v )
{
Vec3D temp(y*v.z - z*v.y,
z*v.x - x*v.z,
x*v.y - y*v.x);
*this=temp;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Assignment operator *= scalar multiplication
/// \param d: scalar
inline Vec3D& Vec3D::operator *= ( double d )
{
x *= d;
y *= d;
z *= d;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Assignment operator /= scalar division
/// \param d: scalar
inline Vec3D& Vec3D::operator /= ( double d )
{
x /= d;
y /= d;
z /= d;
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator +
inline Vec3D Vec3D::operator + ( const Vec3D& v ) const
{
Vec3D temp(*this);
return temp += v;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator -
inline Vec3D Vec3D::operator - ( const Vec3D& v ) const
{
Vec3D temp(*this);
return temp -= v;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator *
inline double Vec3D::operator * ( const Vec3D& v ) const
{
return x*v.x + y*v.y + z*v.z;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator ^ of vector product
/*! \note
Normally ^ operator is a bitwise exclusive OR, which
has precedence lower than * / and even lower than + -.
Thus it is executed last if no brackets are used.
Exmp: r=7.5*a+l*b-c*m+2*b^c=(7.5*a+l*b-c*m+2*b)^c
See examples file exmp_Vec3D.cpp for additional
comment(s)
*/
inline Vec3D Vec3D::operator ^ ( const Vec3D& v ) const
{
Vec3D temp(*this);
return temp ^= v;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator & of rotation composition
/*! \note
Composition is opposite to the sense of matrix
multiplication. If r=r1&r2 then rotation r1 happens
first, followed by r2
Normally & operator is a bitwise exclusive AND, which
has precedence lower than * / and even lower than + -.
Thus it is executed last if no brackets are used.
Exmp: r=7.5*a+l*b-c*m+2*b^c=(7.5*a+l*b-c*m+2*b)^c
See examples file exmp_Vec3D.cpp for additional
comment(s)
*/
inline Vec3D Vec3D::operator & ( const Vec3D& v ) const
{
Vec3D temp(*this);
return temp &= v;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// DeRotate a vector to a system which is parallel to another
/// vector
inline Vec3D Vec3D::DeRotate(const Vec3D& r) const
{
Vec3D temp(*this);
double norm;
double theta;
double phi;
r.Polar(norm,theta,phi);
temp.Rotate(Vec3D(0,0,-phi));
temp.Rotate(Vec3D(0,-theta,0));
return temp;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator * for left scalar multiplication
inline Vec3D operator * ( double d, const Vec3D& v )
{
Vec3D temp(d*v.x, d*v.y, d*v.z );
return temp;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator * for right scalar multiplication
inline Vec3D operator * ( const Vec3D& v, double d )
{
Vec3D temp( v.x*d, v.y*d, v.z*d );
return temp;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Operator * for right scalar division
inline Vec3D operator / ( const Vec3D& v, double d )
{
Vec3D temp( v.x/d, v.y/d, v.z/d );
return temp;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Negation
inline Vec3D operator - ( const Vec3D& v )
{
Vec3D temp( -v.x, -v.y, -v.z );
return temp;
}
} // namespace Physics
#ifndef __VS_NO_IOSTREAM
namespace std
{
inline ostream& operator << (ostream& stream, const Physics::Vec3D& v);
inline istream& operator >> (istream& stream, Physics::Vec3D& v);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Stream insertion
inline ostream& operator << (ostream& stream, const Physics::Vec3D& v)
{
v.DumpShort(stream);
return stream;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// Stream extraction
inline istream& operator >> (istream& stream, Physics::Vec3D& v)
{
char c;
stream >> c >> v.x >> v.y >> v.z >> c;
return stream;
}
}
#endif
#endif // PHYSICS_VEC3D_H
| 27.617722 | 86 | 0.506554 | [
"vector",
"3d"
] |
24a3637df9dc761516b82b88c4139cb143072de8 | 22,765 | cpp | C++ | framework/Benchmarks.cpp | scottviteri/verified-betrfs | 7af56c8acd943880cb19ba16d146c6a206101d9b | [
"BSD-2-Clause"
] | 15 | 2021-05-11T09:19:12.000Z | 2022-03-14T10:39:05.000Z | framework/Benchmarks.cpp | scottviteri/verified-betrfs | 7af56c8acd943880cb19ba16d146c6a206101d9b | [
"BSD-2-Clause"
] | 3 | 2021-06-07T21:45:13.000Z | 2021-11-29T23:19:59.000Z | framework/Benchmarks.cpp | scottviteri/verified-betrfs | 7af56c8acd943880cb19ba16d146c6a206101d9b | [
"BSD-2-Clause"
] | 7 | 2021-05-11T17:08:04.000Z | 2022-02-23T07:19:36.000Z | // Copyright 2018-2021 VMware, Inc., Microsoft Inc., Carnegie Mellon University, ETH Zurich, and University of Washington
// SPDX-License-Identifier: BSD-2-Clause
#include "Benchmarks.h"
#include <chrono>
#include <iostream>
#include <random>
#include <algorithm>
#include <cstdio>
#include <cassert>
#include "Application.h"
using namespace std;
void benchmark_start(string const& name);
void benchmark_end(string const& name);
constexpr int KEY_SIZE = 20;
constexpr int VALUE_SIZE = 400;
class Benchmark {
public:
virtual ~Benchmark() {}
virtual string name() = 0;
virtual int opCount() = 0;
virtual void prepare(Application& app) = 0;
virtual void go(Application& app) = 0;
void run(string filename, bool skipPrepare = false) {
if (!skipPrepare) {
Mkfs(filename);
}
Application app(filename);
if (!skipPrepare) {
prepare(app);
}
auto t1 = chrono::high_resolution_clock::now();
cerr << "Benchmark " << name() << " starting." << endl;
go(app);
auto t2 = chrono::high_resolution_clock::now();
long long ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
cout << "Benchmark " << name() << ": "
<< (((double) opCount()) / (((double) ms) / 1000)) << " ops/s, "
<< ms << " ms, "
<< opCount() << " ops"
<< endl;
}
vector<ByteString> RandomSeqs(int n, int seed, int len) {
std::default_random_engine gen;
gen.seed(seed);
std::uniform_int_distribution<int> distribution(0, 255);
vector<ByteString> l(n);
for (int i = 0; i < n; i++) {
l[i] = ByteString(len);
for (int j = 0; j < len; j++) {
l[i].seq.ptr()[j] = (uint8) distribution(gen);
}
}
return l;
}
vector<ByteString> RandomKeys(int n, int seed) {
return RandomSeqs(n, seed, KEY_SIZE);
}
vector<ByteString> RandomValues(int n, int seed) {
return RandomSeqs(n, seed, VALUE_SIZE);
}
vector<ByteString> RandomSortedKeys(int n, int seed) {
vector<ByteString> data = RandomKeys(n, seed);
std::sort(data.begin(), data.end());
return data;
}
pair<vector<ByteString>, vector<ByteString>> RandomQueryKeysAndValues(
int n, int seed,
vector<ByteString> const& insertedKeys,
vector<ByteString> const& insertedValues)
{
std::default_random_engine gen;
gen.seed(seed);
std::uniform_int_distribution<int> rand_bool(0, 1);
std::uniform_int_distribution<int> rand_byte(0, 255);
std::uniform_int_distribution<int> rand_idx(0, insertedKeys.size() - 1);
ByteString emptyBytes(0);
vector<ByteString> queryKeys(n);
vector<ByteString> queryValues(n);
for (int i = 0; i < n; i++) {
if (rand_bool(gen) == 0) {
// Min length 20 so probability of collision is miniscule
ByteString bytes(20);
for (size_t j = 0; j < bytes.size(); j++) {
bytes.seq.ptr()[j] = rand_byte(gen);
}
queryKeys[i] = bytes;
queryValues[i] = emptyBytes;
} else {
int idx = rand_idx(gen);
queryKeys[i] = insertedKeys[idx];
queryValues[i] = insertedValues[idx];
}
}
return make_pair(move(queryKeys), move(queryValues));
}
[[ noreturn ]]
void fail(string err)
{
cout << "fatal error: " << err << endl;
exit(1);
}
string to_hex(ByteString const& b) {
vector<char> ch(b.size() * 2);
for (size_t i = 0; i < b.size(); i++) {
uint8 by = b.seq.select(i);
int x = by >> 4;
int y = by & 0xf;
ch[2*i] = (x < 10 ? x + '0' : x + 'a' - 10);
ch[2*i + 1] = (y < 10 ? y + '0' : y + 'a' - 10);
}
return string(&ch[0], ch.size());
}
};
class SimpleTest : public Benchmark {
public:
virtual string name() override { return "SimpleTest"; }
virtual int opCount() override { return 100000; }
SimpleTest() {
}
virtual void prepare(Application& app) override {
app.Insert("a", "1");
app.Insert("b", "2");
app.Insert("c", "3");
app.Insert("d", "4");
app.Sync(true);
app.crash();
}
virtual void go(Application& app) override {
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("b"), ByteString("2"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("b"), ByteString("2"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("b"), ByteString("2"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("b"), ByteString("2"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("a"), ByteString("1"));
app.QueryAndExpect(ByteString("b"), ByteString("2"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.Insert("a", "x");
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("b"), ByteString("2"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.Insert("b", "y");
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("b"), ByteString("y"));
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("b"), ByteString("y"));
app.QueryAndExpect(ByteString("c"), ByteString("3"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.Insert("c", "z");
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.QueryAndExpect(ByteString("c"), ByteString("z"));
app.QueryAndExpect(ByteString("b"), ByteString("y"));
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("b"), ByteString("y"));
app.QueryAndExpect(ByteString("c"), ByteString("z"));
app.QueryAndExpect(ByteString("d"), ByteString("4"));
app.Insert("d", "w");
app.QueryAndExpect(ByteString("d"), ByteString("w"));
app.QueryAndExpect(ByteString("c"), ByteString("z"));
app.QueryAndExpect(ByteString("b"), ByteString("y"));
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("a"), ByteString("x"));
app.QueryAndExpect(ByteString("b"), ByteString("y"));
app.QueryAndExpect(ByteString("c"), ByteString("z"));
app.QueryAndExpect(ByteString("d"), ByteString("w"));
ByteString t[4];
t[0] = ByteString("x");
t[1] = ByteString("y");
t[2] = ByteString("z");
t[3] = ByteString("w");
for (int i = 0; i < 100000; i++) {
int k = rand() % 4;
ByteString key;
if (k == 0) key = ByteString("a");
if (k == 1) key = ByteString("b");
if (k == 2) key = ByteString("c");
if (k == 3) key = ByteString("d");
if (rand() % 2) {
app.QueryAndExpect(key, t[k]);
} else {
int v = rand() % 2;
ByteString val;
if (k == 0) val = v ? ByteString("1") : ByteString("11");
if (k == 1) val = v ? ByteString("2") : ByteString("22");
if (k == 2) val = v ? ByteString("3") : ByteString("33");
if (k == 3) val = v ? ByteString("4") : ByteString("44");
app.Insert(key, val);
t[k] = val;
}
}
}
};
class BenchmarkRandomInserts : public Benchmark {
public:
int count = 500000;
virtual string name() override { return "RandomInserts"; }
virtual int opCount() override { return count; }
vector<ByteString> keys;
vector<ByteString> values;
BenchmarkRandomInserts() {
int seed1 = 1234;
int seed2 = 527;
keys = RandomKeys(count, seed1);
values = RandomValues(count, seed2);
}
virtual void prepare(Application& app) override {
}
virtual void go(Application& app) override {
for (size_t i = 0; i < keys.size(); i++) {
app.Insert(keys[i], values[i]);
}
app.Sync(false);
}
};
class BenchmarkLongRandomInserts : public Benchmark {
public:
int count = 5000000;
virtual string name() override { return "LongRandomInserts"; }
virtual int opCount() override { return count; }
uint32_t rngState = 198432;
uint32_t NextPseudoRandom() {
rngState = (uint32_t) (((uint64_t) rngState * 279470273) % 0xfffffffb);
return rngState;
}
BenchmarkLongRandomInserts() {
}
virtual void prepare(Application& app) override {
}
virtual void go(Application& app) override {
static_assert (KEY_SIZE % 4 == 0, "");
static_assert (VALUE_SIZE % 4 == 0, "");
for (int i = 0; i < count; i++) {
ByteString key(KEY_SIZE);
for (int j = 0; j < KEY_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (key.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
ByteString value(VALUE_SIZE);
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
app.Insert(key, value);
if (i % 50000 == 0) app.Sync(false);
}
app.Sync(true);
}
};
class BenchmarkBigTreeQueries : public Benchmark {
public:
int insertCount = 5000000;
int queryCount = 2000;
virtual string name() override { return "BigTreeQueries"; }
virtual int opCount() override { return queryCount; }
uint32_t rngState;
void resetRng() {
rngState = 198432;
}
vector<ByteString> queryKeys;
vector<ByteString> queryValues;
uint32_t NextPseudoRandom() {
rngState = (uint32_t) (((uint64_t) rngState * 279470273) % 0xfffffffb);
return rngState;
}
BenchmarkBigTreeQueries() {
resetRng();
for (int i = 0; i < queryCount; i++) {
ByteString key(KEY_SIZE);
ByteString value(VALUE_SIZE);
for (int k = 0; k < insertCount / queryCount; k++) {
for (int j = 0; j < KEY_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (key.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
}
queryKeys.push_back(key);
queryValues.push_back(value);
}
}
virtual void prepare(Application& app) override {
static_assert (KEY_SIZE % 4 == 0, "");
static_assert (VALUE_SIZE % 4 == 0, "");
resetRng();
for (int i = 0; i < insertCount; i++) {
ByteString key(KEY_SIZE);
for (int j = 0; j < KEY_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (key.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
ByteString value(VALUE_SIZE);
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
app.Insert(key, value);
}
app.Sync(true);
app.crash();
}
virtual void go(Application& app) override {
for (int i = 0; i < queryCount; i++) {
app.QueryAndExpect(queryKeys[i], queryValues[i]);
}
}
};
class BenchmarkRandomQueries : public Benchmark {
public:
int count = 500000;
virtual string name() override { return "RandomQueries"; }
virtual int opCount() override { return count; }
vector<ByteString> keys;
vector<ByteString> values;
vector<ByteString> query_keys;
vector<ByteString> query_values;
BenchmarkRandomQueries() {
int seed1 = 1234;
int seed2 = 527;
int seed3 = 19232;
keys = RandomKeys(count, seed1);
values = RandomValues(count, seed2);
auto p = RandomQueryKeysAndValues(count, seed3, keys, values);
query_keys = move(p.first);
query_values = move(p.second);
}
virtual void prepare(Application& app) override {
for (size_t i = 0; i < keys.size(); i++) {
app.Insert(keys[i], values[i]);
}
app.Sync(true);
app.crash();
}
virtual void go(Application& app) override {
for (size_t i = 0; i < query_keys.size(); i++) {
app.QueryAndExpect(query_keys[i], query_values[i]);
}
}
};
class BenchmarkMixedInsertQuery : public Benchmark {
public:
int start = 1000000;
int count = 5000000;
int KEY_SIZE = 24;
int VALUE_SIZE = 512;
virtual string name() override { return "MixedInsertQuery"; }
virtual int opCount() override { return count; }
uint32_t rngState = 198432;
uint32_t NextPseudoRandom() {
rngState = (uint32_t) (((uint64_t) rngState * 279470273) % 0xfffffffb);
return rngState;
}
vector<ByteString> keys;
BenchmarkMixedInsertQuery() {
for (int i = 0; i < start + count/2; i++) {
ByteString key(KEY_SIZE);
for (int j = 0; j < KEY_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (key.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
keys.push_back(key);
}
}
virtual void prepare(Application& app) override {
for (int i = 0; i < start; i++) {
ByteString value(VALUE_SIZE);
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
app.Insert(keys[i], value);
}
app.Sync(true);
}
virtual void go(Application& app) override {
assert (KEY_SIZE % 4 == 0);
assert (VALUE_SIZE % 4 == 0);
rngState = 43211;
for (int i = 0; i < count; i++) {
if (i % 10000 == 0) cout << i << endl;
if (i % 2) {
int v = NextPseudoRandom() % keys.size();
app.Query(keys[v]);
} else {
int key_idx = start + i / 2;
ByteString value(VALUE_SIZE);
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
app.Insert(keys[key_idx], value);
}
}
}
};
class BenchmarkMixedUpdateQuery : public Benchmark {
public:
int start = 1000000;
int count = 5000000;
// match ycsb-a
int KEY_SIZE = 24;
int VALUE_SIZE = 512;
virtual string name() override { return "MixedUpdateQuery"; }
virtual int opCount() override { return count; }
uint32_t rngState = 198432;
uint32_t NextPseudoRandom() {
rngState = (uint32_t) (((uint64_t) rngState * 279470273) % 0xfffffffb);
return rngState;
}
vector<ByteString> keys;
BenchmarkMixedUpdateQuery() {
for (int i = 0; i < start; i++) {
ByteString key(KEY_SIZE);
for (int j = 0; j < KEY_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (key.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
keys.push_back(key);
}
}
virtual void prepare(Application& app) override {
for (int i = 0; i < start; i++) {
ByteString value(VALUE_SIZE);
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
app.Insert(keys[i], value);
}
app.Sync(true);
}
virtual void go(Application& app) override {
assert (KEY_SIZE % 4 == 0);
assert (VALUE_SIZE % 4 == 0);
rngState = 43211;
for (int i = 0; i < count; i++) {
if (i % 10000 == 0) cout << i << endl;
if (i % 2) {
int v = NextPseudoRandom() % keys.size();
app.Query(keys[v]);
} else {
int key_idx = NextPseudoRandom() % keys.size();
ByteString value(VALUE_SIZE);
for (int j = 0; j < VALUE_SIZE; j += 4) {
uint32_t* ptr = (uint32_t*) (value.seq.ptr() + j);
*ptr = NextPseudoRandom();
}
app.Insert(keys[key_idx], value);
}
}
}
};
int get_first_idx_ge(vector<pair<ByteString, ByteString>> const& v, ByteString key)
{
int lo = 0;
int hi = v.size() + 1;
while (hi > lo + 1) {
int mid = (lo + hi) / 2;
if (v[mid-1].first < key) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
}
class BenchmarkRandomSuccQueries : public Benchmark {
public:
int insertCount = 50000;
int queryCount = 1000;
size_t targetCount = 100;
virtual string name() override { return "RandomSuccQueries"; }
virtual int opCount() override { return queryCount; }
vector<pair<ByteString, ByteString>> keys_values;
vector<ByteString> queries;
vector<vector<pair<ByteString, ByteString>>> query_results;
BenchmarkRandomSuccQueries() {
int seed1 = 1234;
int seed2 = 527;
int seed3 = 9001;
vector<ByteString> keys = RandomKeys(insertCount, seed1);
vector<ByteString> values = RandomValues(insertCount, seed2);
sort(keys.begin(), keys.end());
for (int i = 0; i < insertCount; i++) {
keys_values.push_back(make_pair(keys[i], values[i]));
}
queries = RandomKeys(queryCount, seed3);
for (size_t i = 0; i < queries.size(); i++) {
int idx = get_first_idx_ge(keys_values, queries[i]);
vector<pair<ByteString, ByteString>> query_result;
while (query_result.size() < targetCount && idx < (int)keys_values.size()) {
query_result.push_back(keys_values[idx]);
idx++;
}
query_results.push_back(move(query_result));
}
}
virtual void prepare(Application& app) override {
for (size_t i = 0; i < keys_values.size(); i++) {
//cout << "Inserting " << to_hex(keys_values[i].first) << " -> " << to_hex(keys_values[i].second) << endl;
app.Insert(keys_values[i].first, keys_values[i].second);
}
app.Sync(true);
app.crash();
}
virtual void go(Application& app) override {
for (size_t i = 0; i < queries.size(); i++) {
auto result = app.Succ(queries[i], true /* inclusive */, targetCount);
if (result != query_results[i]) {
cout << "query " << to_hex(queries[i]) << endl;
cout << "result: " << endl;
for (auto p : result) {
cout << " " << to_hex(p.first) << " : " << to_hex(p.second) << endl;
}
cout << "expected result: " << endl;
for (auto p : query_results[i]) {
cout << " " << to_hex(p.first) << " : " << to_hex(p.second) << endl;
}
fail("Incorrect succ result");
}
}
app.Sync(true);
}
};
class BenchmarkReplay : public Benchmark {
public:
int count = 20000;
virtual string name() override { return "Replay"; }
virtual int opCount() override { return 1; }
vector<ByteString> keys;
vector<ByteString> values;
vector<ByteString> query_keys;
vector<ByteString> query_values;
BenchmarkReplay() {
int seed1 = 1234;
int seed2 = 527;
int seed3 = 19232;
keys = RandomKeys(count, seed1);
values = RandomValues(count, seed2);
auto p = RandomQueryKeysAndValues(count, seed3, keys, values);
query_keys = move(p.first);
query_values = move(p.second);
}
virtual void prepare(Application& app) override {
for (size_t i = 0; i < keys.size(); i++) {
app.Insert(keys[i], values[i]);
}
app.Sync(false);
app.crash();
}
virtual void go(Application& app) override {
app.QueryAndExpect(query_keys[0], query_values[0]);
}
};
void RunAllBenchmarks(string filename) {
{ BenchmarkRandomInserts q; q.run(filename); }
{ BenchmarkRandomQueries q; q.run(filename); }
{ BenchmarkRandomSuccQueries q; q.run(filename); }
}
shared_ptr<Benchmark> benchmark_by_name(string const& name) {
if (name == "random-queries") { return shared_ptr<Benchmark>(new BenchmarkRandomQueries()); }
if (name == "random-inserts") { return shared_ptr<Benchmark>(new BenchmarkRandomInserts()); }
if (name == "long-random-inserts") { return shared_ptr<Benchmark>(new BenchmarkLongRandomInserts()); }
if (name == "big-tree-queries") { return shared_ptr<Benchmark>(new BenchmarkBigTreeQueries()); }
if (name == "random-succs") { return shared_ptr<Benchmark>(new BenchmarkRandomSuccQueries()); }
if (name == "mixed-insert-query") { return shared_ptr<Benchmark>(new BenchmarkMixedInsertQuery()); }
if (name == "mixed-update-query") { return shared_ptr<Benchmark>(new BenchmarkMixedUpdateQuery()); }
if (name == "replay") { return shared_ptr<Benchmark>(new BenchmarkReplay()); }
if (name == "simple-test") { return shared_ptr<Benchmark>(new SimpleTest()); }
cerr << "No benchmark found by name " << name << endl;
exit(1);
}
class StopwatchEntry {
public:
long long ns;
bool in_progress;
int count;
std::chrono::time_point<std::chrono::high_resolution_clock> last;
StopwatchEntry() {
ns = 0;
in_progress = false;
count = 0;
}
void start() {
assert(!in_progress);
in_progress = true;
last = chrono::high_resolution_clock::now();
}
void end() {
assert(in_progress);
in_progress = false;
auto t2 = chrono::high_resolution_clock::now();
ns += std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - last).count();
count++;
}
void append(long long ns) {
this->ns += ns;
count++;
}
};
map<string, StopwatchEntry> sw;
string nameToString(DafnySequence<char> dafnyName) {
return string(dafnyName.ptr(), dafnyName.size());
}
void benchmark_start(string const& name) {
auto it = sw.find(name);
if (it == sw.end()) {
sw.insert(make_pair(name, StopwatchEntry()));
}
sw[name].start();
}
void benchmark_end(string const& name) {
sw[name].end();
}
void benchmark_append(string const& name, long long ns) {
auto it = sw.find(name);
if (it == sw.end()) {
sw.insert(make_pair(name, StopwatchEntry()));
}
sw[name].append(ns);
}
void benchmark_dump() {
for (auto& p : sw) {
string name = p.first;
int count = p.second.count;
long long ms = p.second.ns / 1000000;
cout << name << " " << ms << " ms, " << count << " ticks" << endl;
}
}
void benchmark_clear() {
sw.clear();
}
namespace NativeBenchmarking_Compile {
void start(DafnySequence<char> dafnyName) {
benchmark_start(nameToString(dafnyName));
}
void end(DafnySequence<char> dafnyName) {
benchmark_end(nameToString(dafnyName));
}
}
void RunBenchmark(string filename, string const& name, bool skipPrepare) {
benchmark_by_name(name)->run(filename, skipPrepare);
benchmark_dump();
}
| 28.209418 | 121 | 0.606853 | [
"vector"
] |
24af879b4eb9f6154e9cc03bac7c72b5b0b68ed2 | 2,166 | cpp | C++ | Competitive Programing Problem Solutions/Virtual Judge/Shahariar Vai_Graph/10336 - Rank the Languages.cpp | BIJOY-SUST/ACM---ICPC | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 1 | 2022-02-27T12:07:59.000Z | 2022-02-27T12:07:59.000Z | Competitive Programing Problem Solutions/Virtual Judge/Shahariar Vai_Graph/10336 - Rank the Languages.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | Competitive Programing Problem Solutions/Virtual Judge/Shahariar Vai_Graph/10336 - Rank the Languages.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | /*______________________________________________
! BIJOY !
! CSE-25th Batch !
!Shahjalal University of Science and Technology!
!______________________________________________!
*/
#include<bits/stdc++.h>
//#define PI 3.14159265358979323846264338328
//#define PI acos(-1)
#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c
#define mx 10001
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};
//const int fx[]={-2,-2,-1,-1,+1,+1,+2,+2};
//const int fy[]={-1,+1,-2,+2,-2,+2,-1,+1};
using namespace std;
const int fx[]={+1,-1,+0,+0};
const int fy[]={+0,+0,+1,-1};
int r,c;
char arr[mx][mx];
bool visited[mx][mx];
void DFS(int u,int v,char ch){
visited[u][v]=true;
for(int i=0;i<4;i++){
int tx=u+fx[i];
int ty=v+fy[i];
if(valid(tx,ty)&&!visited[tx][ty]){
if(arr[tx][ty]==ch) DFS(tx,ty,ch);
}
}
}
bool compare(const pair<char,int>&a,const pair<char,int>&b){
//return a.second<b.second;
return a.second==b.second? a.first<b.first:a.second>b.second;
}
int main(){
int t;
scanf("%d",&t);
for(int tc=1;tc<=t;tc++){
scanf("%d %d",&r,&c);
for(int j=0;j<r;j++){
scanf("%s",&arr[j]);
}
map<char,int>letter;
memset(visited,false,sizeof(visited));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
char ch=arr[i][j];
if(!visited[i][j]){
DFS(i,j,ch);
letter[ch]++;
}
}
}
vector<pair<char,int> >v(letter.begin(),letter.end());
sort(v.begin(),v.end(),compare);
printf("World #%d\n",tc);
for(__typeof(v.begin()) it=v.begin();it!=v.end();it++){
printf("%c: %d\n",it->first,it->second);
//printf("%c: %d\n",(*it).first,(*it).second);
}
letter.clear();
v.clear();
}
return 0;
}
| 31.391304 | 66 | 0.459834 | [
"vector"
] |
24b753d55c483aebd0aa0b034fa3854ce75510af | 1,768 | hpp | C++ | AAM/include/openada.hpp | adadesions/trainingJackson | ac17bbd7155b6f04c28662ff1007ee28b73aacfc | [
"BSD-3-Clause"
] | null | null | null | AAM/include/openada.hpp | adadesions/trainingJackson | ac17bbd7155b6f04c28662ff1007ee28b73aacfc | [
"BSD-3-Clause"
] | null | null | null | AAM/include/openada.hpp | adadesions/trainingJackson | ac17bbd7155b6f04c28662ff1007ee28b73aacfc | [
"BSD-3-Clause"
] | null | null | null | #ifndef OPENADA_HPP
#define OPENADA_HPP
#include <iostream>
#include <dlib/matrix.h>
#include <opencv2/opencv.hpp>
namespace opa {
void test() {
std::cout << "Yo\n";
}
std::vector<cv::Vec6f> getDelaunayVec6f( std::string filename ) {
cv::FileStorage fs(filename, cv::FileStorage::READ);
std::vector<cv::Vec6f> vertices;
if( !fs.isOpened() ){
std::cout << "File not found at getDelaunay: " << filename << std::endl;
return vertices;
}
cv::FileNode delaunay = fs["delaunay"];
for( auto p:delaunay ){
cv::Vec6f v;
p["points"] >> v;
vertices.push_back(v);
}
fs.release();
return vertices;
}
cv::Mat getTexture( std::string filename ) {
cv::Mat image;
cv::FileStorage fs(filename, cv::FileStorage::READ);
if( !fs.isOpened() ){
std::cout << "File not found at getTexture: " << filename << std::endl;
return image;
}
cv::FileNode fn = fs["image"];
fs["image"] >> image;
return image;
}
std::vector<cv::Point2f> getTrianglePiece( int index, std::vector<cv::Vec6f> vertices ) {
cv::Vec6f v = vertices[index];
int cgx = (v[0] + v[2] + v[4])/3;
int cgy = (v[1] + v[3] + v[5])/3;
// cgx = 0;
// cgy = 0;
std::vector<cv::Point2f> p;
cv::Point2f cg = cv::Point2f( cgx, cgy );
p.push_back( cv::Point2f( v[0], v[1] ) );
p.push_back( cv::Point2f( v[2], v[3] ) );
p.push_back( cv::Point2f( v[4], v[5] ) );
p[0] = p[0] - cg;
p[1] = p[1] - cg;
p[2] = p[2] - cg;
return p;
}
}
#endif | 27.625 | 93 | 0.489253 | [
"vector"
] |
24ba4488814cb959f144ce1b798a0d602d518e28 | 1,212 | cpp | C++ | src/main.cpp | computer-geek64/huffskew | a55fab0d8ad99a46731eb7bf16e8a52ff725c060 | [
"MIT"
] | null | null | null | src/main.cpp | computer-geek64/huffskew | a55fab0d8ad99a46731eb7bf16e8a52ff725c060 | [
"MIT"
] | null | null | null | src/main.cpp | computer-geek64/huffskew | a55fab0d8ad99a46731eb7bf16e8a52ff725c060 | [
"MIT"
] | null | null | null | // main.cpp
// Ashish D'Souza
#include <cstddef>
#include <string>
#include <iostream>
#include "compress.hpp"
#include "uncompress.hpp"
#include "main.hpp"
using namespace std;
int main(int argc, char **argv) {
if(argc < 5) {
showHelp();
return 1;
}
vector<string> args;
for(unsigned int i = 0; i < argc; i++) {
string arg(*(argv + i));
if(arg == "-h") {
showHelp();
return 0;
}
args.push_back(arg);
}
string action(args[1]);
string inputFilename(args[2]);
string outputFilename(args[4]);
if(action == "-c") {
compress(inputFilename, outputFilename);
}
else if(action == "-u") {
uncompress(inputFilename, outputFilename);
}
else {
showHelp();
return 1;
}
return 0;
}
void showHelp() {
cout << "Usage: huffskew [action] [filename] -o [filename]" << "\n";
cout << "\n";
cout << "Option\t\tDescription" << "\n";
cout << "-h\t\tShow this help screen" << "\n";
cout << "-c [filename]\tCompress action" << "\n";
cout << "-u [filename]\tUncompress action" << "\n";
cout << "-o [filename]\tOutput filename" << endl;
} | 21.263158 | 72 | 0.535479 | [
"vector"
] |
24bbfc487a0a7d4095a72135b43d559eeefcf4a6 | 3,899 | hh | C++ | include/fflow/alg_lists.hh | peraro/finiteflow | 820ba5b13756e861d1e6a07403d7e70c1e849e0d | [
"MIT"
] | 25 | 2019-05-21T02:56:08.000Z | 2022-01-29T23:59:44.000Z | include/fflow/alg_lists.hh | peraro/finiteflow | 820ba5b13756e861d1e6a07403d7e70c1e849e0d | [
"MIT"
] | 2 | 2019-05-21T14:41:56.000Z | 2020-09-21T13:53:20.000Z | include/fflow/alg_lists.hh | peraro/finiteflow | 820ba5b13756e861d1e6a07403d7e70c1e849e0d | [
"MIT"
] | 3 | 2020-01-08T09:36:48.000Z | 2022-03-19T09:09:15.000Z | // Basic algorithm for manipulating lists of arguments. These do not
// need any AnlgorithmData, so we can just pass a nullptr for that
#ifndef FFLOW_ALG_LISTS_HH
#define FFLOW_ALG_LISTS_HH
#include <fflow/algorithm.hh>
namespace fflow {
class Chain : public Algorithm {
public:
void init(const unsigned npars[], unsigned npars_size);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
};
class Take : public Algorithm {
public:
struct InputEl {
unsigned list;
unsigned el;
};
Ret init(const unsigned npars[], unsigned npars_size,
std::vector<InputEl> && elems);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
private:
std::vector<InputEl> elems_;
};
class Slice : public Algorithm {
public:
Ret init(unsigned npars, unsigned start, unsigned end);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
private:
unsigned start_=0, end_=0;
};
class MatrixMul : public Algorithm {
public:
void init(unsigned nrows1, unsigned ncols1, unsigned ncols2);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
private:
unsigned nr1_, nc1_, nc2_;
};
class Add : public Algorithm {
public:
void init(unsigned nlists, unsigned list_len);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
};
class Mul : public Algorithm {
public:
void init(unsigned nlists, unsigned list_len);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
};
class NonZeroes : public Algorithm {
public:
void init(unsigned input_len);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
virtual Ret learn(Context * ctxt, AlgInput * xin, Mod mod,
AlgorithmData * data) override;
virtual UInt min_learn_times() override { return 2; }
const unsigned * non_zeroes() const
{
return nonzero_.get();
}
public:
std::unique_ptr<unsigned[]> nonzero_;
};
class TakeAndAdd : public Algorithm {
public:
struct InputEl {
unsigned list;
unsigned el;
};
Ret init(const unsigned npars[], unsigned npars_size,
std::vector<std::vector<InputEl>> && elems);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
private:
std::vector<std::vector<InputEl>> elems_;
};
class SparseMatrixMul : public Algorithm {
public:
// Call this after setting 'size' and 'cols' for 'row1' and 'row2'
Ret init(unsigned nrows1, unsigned ncols1, unsigned ncols2);
virtual Ret evaluate(Context * ctxt,
AlgInput xin[], Mod mod, AlgorithmData * data,
UInt xout[]) const override;
struct RowInfo {
private:
std::size_t start = 0;
public:
std::size_t size = 0;
std::unique_ptr<unsigned[]> cols;
private:
friend class SparseMatrixMul;
};
std::vector<RowInfo> row1, row2;
private:
unsigned nr1_, nc1_, nc2_;
};
} // namespace fflow
#endif // FFLOW_ALG_LISTS_HH
| 23.487952 | 71 | 0.588612 | [
"vector"
] |
24bee6cac5b5860dd88a695301944b16a81faa8d | 3,552 | hpp | C++ | Include/API/lib3mf_object.hpp | geaz/lib3mf | fd07e571a869f5c495a3beea014d341d67c9d405 | [
"BSD-2-Clause"
] | 171 | 2015-04-30T21:54:02.000Z | 2022-03-13T13:33:59.000Z | Include/API/lib3mf_object.hpp | geaz/lib3mf | fd07e571a869f5c495a3beea014d341d67c9d405 | [
"BSD-2-Clause"
] | 190 | 2015-07-21T22:15:54.000Z | 2022-03-30T15:48:37.000Z | Include/API/lib3mf_object.hpp | geaz/lib3mf | fd07e571a869f5c495a3beea014d341d67c9d405 | [
"BSD-2-Clause"
] | 80 | 2015-04-30T22:15:54.000Z | 2022-03-09T12:38:49.000Z | /*++
Copyright (C) 2019 3MF Consortium (Original Author)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Abstract: This is the class declaration of CObject
*/
#ifndef __LIB3MF_OBJECT
#define __LIB3MF_OBJECT
#include "lib3mf_interfaces.hpp"
// Parent classes
#include "lib3mf_resource.hpp"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4250)
#endif
// Include custom headers here.
#include "Model/Classes/NMR_ModelResource.h"
namespace Lib3MF {
namespace Impl {
/*************************************************************************************************************************
Class declaration of CObject
**************************************************************************************************************************/
class CObject : public virtual IObject, public virtual CResource {
private:
/**
* Put private members here.
*/
protected:
NMR::CModelObject* object();
public:
/**
* Put additional public members here. They will not be visible in the external API.
*/
CObject(NMR::PModelResource pResource);
CObject() = delete;
static IObject* fnCreateObjectFromModelResource(NMR::PModelResource pResource, bool bFailIfUnkownClass);
/**
* Public member functions to implement.
*/
eLib3MFObjectType GetType ();
void SetType (const eLib3MFObjectType eObjectType);
std::string GetName ();
void SetName (const std::string & sName);
std::string GetPartNumber ();
void SetPartNumber (const std::string & sPartNumber);
virtual bool IsMeshObject ();
virtual bool IsComponentsObject ();
virtual IMeshObject * AsMeshObject();
virtual IComponentsObject * AsComponentsObject();
bool IsValid ();
void SetAttachmentAsThumbnail(IAttachment* pAttachment);
IAttachment * GetThumbnailAttachment();
void ClearThumbnailAttachment();
IMetaDataGroup * GetMetaDataGroup ();
std::string GetUUID(bool & bHasUUID);
void SetUUID(const std::string & sUUID);
void SetSlicesMeshResolution(const eLib3MFSlicesMeshResolution eMeshResolution);
eLib3MFSlicesMeshResolution GetSlicesMeshResolution();
bool HasSlices(const bool bRecursive);
void ClearSliceStack();
ISliceStack * GetSliceStack();
void AssignSliceStack(ISliceStack* pSliceStackInstance);
Lib3MF::sBox GetOutbox();
};
}
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // __LIB3MF_OBJECT
| 26.117647 | 123 | 0.726351 | [
"object",
"model"
] |
24c0dcbaa15da14532f7d85e267cb96b7ffa297a | 16,288 | cpp | C++ | gtests/src/integration/simulacron/simulacron_cluster.cpp | AlexisWilke/cpp-driver | 9ca662826d46a528ef02b4cbd4cff6cb25ca1fe6 | [
"Apache-2.0"
] | null | null | null | gtests/src/integration/simulacron/simulacron_cluster.cpp | AlexisWilke/cpp-driver | 9ca662826d46a528ef02b4cbd4cff6cb25ca1fe6 | [
"Apache-2.0"
] | null | null | null | gtests/src/integration/simulacron/simulacron_cluster.cpp | AlexisWilke/cpp-driver | 9ca662826d46a528ef02b4cbd4cff6cb25ca1fe6 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) DataStax, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "simulacron_cluster.hpp"
#include "options.hpp"
#include "test_utils.hpp"
#include "tlog.hpp"
#include "scoped_lock.hpp"
#include "tsocket.hpp"
#include "values/uuid.hpp"
#include "objects/uuid_gen.hpp"
#include <algorithm>
#include <sstream>
#define SIMULACRON_LISTEN_ADDRESS "127.0.0.1"
#define SIMULACRON_ADMIN_PORT 8187
#define SIMULACRON_LOG_LEVEL "DEBUG"
#define HTTP_EOL "\r\n"
#define OUTPUT_BUFFER_SIZE 10240ul
#define SIMULACRON_NAP 100
#define SIMULACRON_CONNECTION_RETRIES 600 // Up to 60 seconds for retry based on SIMULACRON_NAP
#define SIMULACRON_PROCESS_RETRIS 100 // Up to 10 seconds for retry based on SIMULACRON_NAP
#define MAX_TOKEN static_cast<uint64_t>(INT64_MAX) - 1
#define DATA_CENTER_PREFIX "dc"
// Initialize the mutex, running status, thread, and default data center nodes
uv_mutex_t test::SimulacronCluster::mutex_;
bool test::SimulacronCluster::is_ready_ = false;
bool test::SimulacronCluster::is_running_ = false;
uv_thread_t test::SimulacronCluster::thread_;
const unsigned int DEFAULT_NODE[] = { 1 };
const std::vector<unsigned int> test::SimulacronCluster::DEFAULT_DATA_CENTER_NODES(
DEFAULT_NODE, DEFAULT_NODE + sizeof(DEFAULT_NODE) / sizeof(DEFAULT_NODE[0]));
test::SimulacronCluster::SimulacronCluster()
: dse_version_("")
, cassandra_version_("")
, current_cluster_id_(-1)
{
// Initialize the mutex
uv_mutex_init(&mutex_);
// Determine if Simulacron file exists
if (!test::Utils::file_exists(SIMULACRON_SERVER_JAR)) {
std::stringstream message;
message << "Unable to find Simulacron JAR file ["
<< SIMULACRON_SERVER_JAR << "]";
throw Exception(message.str());
}
// Determine the release version (for priming nodes)
CCM::CassVersion cassandra_version = Options::server_version();
if (Options::is_dse()) {
CCM::DseVersion dse_version(cassandra_version);
cassandra_version = dse_version.get_cass_version();
if (cassandra_version == "0.0.0") {
throw Exception("Unable to determine Cassandra version from DSE version");
}
dse_version_ = test::Utils::replace_all(dse_version.to_string(), "-",
".");
}
cassandra_version_ = test::Utils::replace_all(cassandra_version.to_string(),
"-", ".");
// Create Simulacron process (threaded) and wait for completely availability
uv_thread_create(&thread_, handle_thread_create, NULL);
uint64_t elapsed = 0ul;
uint64_t start_time = uv_hrtime();
while (!is_ready_ && elapsed < 30000) { // Wait for a maximum of 30s
Utils::msleep(SIMULACRON_NAP);
TEST_LOG("Waiting for Simulacron Availability: Elapsed wait " << elapsed << "ms");
elapsed = (uv_hrtime() - start_time) / 1000000UL;
}
TEST_LOG("Simulacron Status: " << (is_ready_ ? "Available" : "Not available"));
test::Utils::wait_for_port(SIMULACRON_LISTEN_ADDRESS, SIMULACRON_ADMIN_PORT);
}
test::SimulacronCluster::~SimulacronCluster() {
remove_cluster();
}
std::string test::SimulacronCluster::cluster_contact_points(bool is_all /*= true*/) {
// Iterate over each node and collect the list of active contact points
std::vector<Cluster::DataCenter::Node> cluster_nodes = nodes();
size_t index = 1;
std::stringstream contact_points;
for (std::vector<Cluster::DataCenter::Node>::iterator it =
cluster_nodes.begin(); it != cluster_nodes.end(); ++it) {
if (is_all || is_node_up(index++)) {
if (!contact_points.str().empty()) {
contact_points << ",";
}
contact_points << it->ip_address;
}
}
return contact_points.str();
}
void test::SimulacronCluster::create_cluster(const std::vector<unsigned int>& data_center_nodes /*= DEFAULT_DATA_CENTER_NODES*/,
bool with_vnodes /*= false */) {
std::stringstream paramters;
std::stringstream cluster_name;
cluster_name << DEFAULT_CLUSTER_PREFIX << "_";
// Add the data centers, Cassandra version, and token/vnodes parameters
paramters << "data_centers="
<< test::Utils::implode<unsigned int>(data_center_nodes, ',')
<< "&cassandra_version=" << cassandra_version_;
// Update the cluster configuration (set num_tokens)
if (with_vnodes) {
// Maximum number of tokens is 1536
paramters << "&num_tokens=1536";
} else {
paramters << "&num_tokens=1";
}
// Add the DSE version (if applicable)
if (Options::is_dse()) {
paramters << "&dse_version=" << dse_version_;
cluster_name << dse_version_;
} else {
cluster_name << cassandra_version_;
}
// Add the cluster name
cluster_name << "_"
<< test::Utils::implode<unsigned int>(data_center_nodes, '-');
if (with_vnodes) {
cluster_name << "-vnodes";
}
paramters << "&name=" << cluster_name.str();
// Create the cluster and get the cluster ID
std::string endpoint = "cluster?" + paramters.str();
std::string response = send_post(endpoint);
rapidjson::Document document;
document.Parse(response.c_str());
current_cluster_id_ = Cluster(&document).id;
}
void test::SimulacronCluster::create_cluster(unsigned int data_center_one_nodes,
unsigned int data_center_two_nodes /*= 0*/,
bool with_vnodes /*=false */) {
std::vector<unsigned int> data_center_nodes;
if (data_center_one_nodes > 0) {
data_center_nodes.push_back(data_center_one_nodes);
}
if (data_center_two_nodes > 0) {
data_center_nodes.push_back(data_center_two_nodes);
}
create_cluster(data_center_nodes, with_vnodes);
}
void test::SimulacronCluster::remove_cluster() {
send_delete("cluster");
}
std::string test::SimulacronCluster::get_ip_address(unsigned int node) {
std::vector<Cluster::DataCenter::Node> current_nodes = nodes();
if (node > 0 && node <= current_nodes.size()) {
return current_nodes[node - 1].ip_address;
}
return "";
}
bool test::SimulacronCluster::is_node_down(unsigned int node) {
// Attempt to connect to the binary port on the node
unsigned int number_of_retries = 0;
while (number_of_retries++ < SIMULACRON_CONNECTION_RETRIES) {
if (!is_node_available(node)) {
return true;
} else {
TEST_LOG("Connected to Node " << node
<< " in Cluster: Rechecking node down status ["
<< number_of_retries << "]");
test::Utils::msleep(SIMULACRON_NAP);
}
}
// Connection can still be established on node
return false;
}
bool test::SimulacronCluster::is_node_up(unsigned int node) {
// Attempt to connect to the binary port on the node
unsigned int number_of_retries = 0;
while (number_of_retries++ < SIMULACRON_CONNECTION_RETRIES) {
if (is_node_available(node)) {
return true;
} else {
TEST_LOG("Unable to Connect to Node " << node
<< " in Cluster: Rechecking node up status ["
<< number_of_retries << "]");
test::Utils::msleep(SIMULACRON_NAP);
}
}
// Connection cannot be established on node
return false;
}
test::SimulacronCluster::Cluster test::SimulacronCluster::cluster() {
// Generate the JSON document response
std::stringstream endpoint;
endpoint << "cluster/" << current_cluster_id_;
std::string response = send_get(endpoint.str());
rapidjson::Document document;
document.Parse(response.c_str());
// Create and return the cluster
return Cluster(&document);
}
std::vector<test::SimulacronCluster::Cluster::DataCenter> test::SimulacronCluster::data_centers() {
// Get the cluster object and retrieve the data centers
Cluster current_cluster = cluster();
return current_cluster.data_centers;
}
std::vector<test::SimulacronCluster::Cluster::DataCenter::Node>
test::SimulacronCluster::nodes() {
// Get the cluster object and retrieve the nodes from the data center(s)
Cluster current_cluster = cluster();
std::vector<Cluster::DataCenter::Node> nodes;
std::vector<Cluster::DataCenter> data_centers = current_cluster.data_centers;
for (std::vector<Cluster::DataCenter>::iterator it =
data_centers.begin(); it != data_centers.end(); ++it) {
std::vector<Cluster::DataCenter::Node> dc_nodes = it->nodes;
nodes.insert(nodes.end(), dc_nodes.begin(), dc_nodes.end());
}
return nodes;
}
unsigned int test::SimulacronCluster::active_connections(unsigned int node) {
std::vector<Cluster::DataCenter::Node> current_nodes = nodes();
if (node > 0 && node <= current_nodes.size()) {
return current_nodes[node - 1].active_connections;
}
return 0;
}
unsigned int test::SimulacronCluster::active_connections() {
return cluster().active_connections;
}
void test::SimulacronCluster::prime_query(prime::Request& request,
unsigned int node /*= 0*/) {
std::stringstream endpoint;
endpoint << "prime/" << current_cluster_id_ << generate_node_endpoint(node);
send_post(endpoint.str(), request.json());
}
void test::SimulacronCluster::remove_primed_queries(unsigned int node /*= 0*/) {
std::stringstream endpoint;
endpoint << "prime/" << current_cluster_id_ << generate_node_endpoint(node);
send_delete(endpoint.str());
}
void test::SimulacronCluster::handle_exit(uv_process_t* process,
int64_t error_code,
int term_signal) {
cass::ScopedMutex lock(&mutex_);
TEST_LOG("Process " << process->pid << " Terminated: " << error_code);
uv_close(reinterpret_cast<uv_handle_t*>(process), NULL);
}
void test::SimulacronCluster::handle_allocation(uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buffer) {
cass::ScopedMutex lock(&mutex_);
buffer->base = new char[OUTPUT_BUFFER_SIZE];
buffer->len = OUTPUT_BUFFER_SIZE;
}
void test::SimulacronCluster::handle_thread_create(void* arg) {
// Initialize the loop and process arguments
uv_loop_t loop;
if(uv_loop_init(&loop) != 0) {
throw Exception("Unable to Create Simulacron Process: libuv loop " \
"initialization failed");
};
uv_process_options_t options;
memset(&options, 0, sizeof(uv_process_options_t));
// Create the options for reading information from the spawn pipes
uv_pipe_t standard_output;
uv_pipe_t error_output;
uv_pipe_init(&loop, &standard_output, 0);
uv_pipe_init(&loop, &error_output, 0);
uv_stdio_container_t stdio[3];
options.stdio_count = 3;
options.stdio = stdio;
options.stdio[0].flags = UV_IGNORE;
options.stdio[1].flags = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
options.stdio[1].data.stream = (uv_stream_t*) &standard_output;
options.stdio[2].flags = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
options.stdio[2].data.stream = (uv_stream_t*) &error_output;
// Generate the spawn command for use with uv_spawn
const char* spawn_command[7];
spawn_command[0] = "java";
spawn_command[1] = "-jar";
spawn_command[2] = SIMULACRON_SERVER_JAR;
spawn_command[3] = "--loglevel";
spawn_command[4] = SIMULACRON_LOG_LEVEL;
spawn_command[5] = "--verbose";
spawn_command[6] = NULL;
// Create the options for the process
options.args = const_cast<char**>(spawn_command);
options.exit_cb = handle_exit;
options.file = spawn_command[0];
// Start the process
uv_process_t process;
int error_code = uv_spawn(&loop, &process, &options);
if (error_code == 0) {
TEST_LOG("Launched " << spawn_command[0] << " with ID "
<< process.pid);
// Start the output thread loops
uv_read_start(reinterpret_cast<uv_stream_t*>(&standard_output),
handle_allocation, handle_read);
uv_read_start(reinterpret_cast<uv_stream_t*>(&error_output),
handle_allocation, handle_read);
// Start the process loop
is_running_ = true;
uv_run(&loop, UV_RUN_DEFAULT);
uv_loop_close(&loop);
is_running_ = false;
} else {
TEST_LOG_ERROR(uv_strerror(error_code));
}
}
void test::SimulacronCluster::handle_read(uv_stream_t* stream,
ssize_t buffer_length, const uv_buf_t* buffer) {
cass::ScopedMutex lock(&mutex_);
if (buffer_length > 0) {
// Process the buffer and log it
std::string message(buffer->base, buffer_length);
TEST_LOG(Utils::trim(message));
// Check to see if Simulacron is ready to accept connections
if (Utils::contains(message, "Started HTTP server interface")) {
is_ready_ = true;
}
} else if (buffer_length < 0) {
uv_close(reinterpret_cast<uv_handle_t*>(stream), NULL);
}
// Clean up the memory allocated
delete[] buffer->base;
}
void test::SimulacronCluster::send_delete(const std::string& endpoint) {
Response response = send_request(Request::HTTP_METHOD_DELETE, endpoint);
if (response.status_code != 202) {
std::stringstream message;
message << "DELETE Operation " << endpoint
<< " did not Complete Successfully: " << response.status_code;
throw Exception(message.str());
}
}
const std::string test::SimulacronCluster::send_get(
const std::string& endpoint) {
Response response = send_request(Request::HTTP_METHOD_GET, endpoint);
if (response.status_code != 200) {
std::stringstream message;
message << "GET Operation " << endpoint
<< " did not Complete Successfully: " << response.status_code;
throw Exception(message.str());
}
return response.message;
}
const std::string test::SimulacronCluster::send_post(
const std::string& endpoint, const std::string& content /*= ""*/) {
Response response = send_request(Request::HTTP_METHOD_POST, endpoint,
content);
if (response.status_code != 201) {
std::stringstream message;
message << "POST Operation " << endpoint
<< " did not Complete Successfully: " << response.status_code;
throw Exception(message.str());
}
return response.message;
}
Response test::SimulacronCluster::send_request(Request::Method method,
const std::string& endpoint,
const std::string& content /*= ""*/) {
// Create and send the request to the REST server
Request request;
request.method = method;
request.address = SIMULACRON_LISTEN_ADDRESS;
request.port = SIMULACRON_ADMIN_PORT;
request.endpoint = endpoint;
if (method == Request::HTTP_METHOD_POST && !content.empty()) {
request.content = content;
}
return RestClient::send_request(request);
}
bool test::SimulacronCluster::is_node_available(unsigned int node) {
// Determine if the node is valid
std::vector<Cluster::DataCenter::Node> cluster_nodes = nodes();
if (node > cluster_nodes.size()) {
std::stringstream message;
message << "Unable to Check Availability of Node: Node " << node
<< " is not a valid node";
throw test::Exception(message.str());
}
// Determine if the node is available
Cluster::DataCenter::Node cluster_node = cluster_nodes[node - 1];
std::string ip_address = cluster_node.ip_address;
unsigned short port = cluster_node.port;
return is_node_available(ip_address, port);
}
bool test::SimulacronCluster::is_node_available(const std::string& ip_address,
unsigned short port) {
Socket socket;
try {
socket.establish_connection(ip_address, port);
return true;
} catch (...) {
; // No-op
}
// Unable to establish connection to node
return false;
}
const std::string test::SimulacronCluster::generate_node_endpoint(unsigned int node) {
std::stringstream endpoint;
if (node > 0) {
std::vector<Cluster::DataCenter::Node> current_nodes = nodes();
if (node > current_nodes.size()) {
std::stringstream message;
message << "Insufficient Nodes in Cluster: Cluster contains "
<< current_nodes.size() << "; " << node << " is invalid";
throw Exception(message.str());
}
endpoint << "/" << current_nodes[node - 1].data_center_id << "/"
<< current_nodes[node - 1].id;
}
return endpoint.str();
}
| 34.729211 | 128 | 0.69984 | [
"object",
"vector"
] |
24c3ff80badd1237f0f891c43831f296ed726180 | 8,969 | cpp | C++ | core/jni/android_view_InputQueue.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 164 | 2015-01-05T16:49:11.000Z | 2022-03-29T20:40:27.000Z | core/jni/android_view_InputQueue.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 127 | 2015-01-12T12:02:32.000Z | 2021-11-28T08:46:25.000Z | core/jni/android_view_InputQueue.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 1,141 | 2015-01-01T22:54:40.000Z | 2022-02-09T22:08:26.000Z | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "InputQueue"
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <android/input.h>
#include <android_runtime/AndroidRuntime.h>
#include <android_runtime/android_view_InputQueue.h>
#include <input/Input.h>
#include <utils/Looper.h>
#include <utils/TypeHelpers.h>
#include <nativehelper/ScopedLocalRef.h>
#include <nativehelper/JNIHelp.h>
#include "android_os_MessageQueue.h"
#include "android_view_KeyEvent.h"
#include "android_view_MotionEvent.h"
#include "core_jni_helpers.h"
namespace android {
static struct {
jmethodID finishInputEvent;
} gInputQueueClassInfo;
enum {
MSG_FINISH_INPUT = 1,
};
InputQueue::InputQueue(jobject inputQueueObj, const sp<Looper>& looper,
int dispatchReadFd, int dispatchWriteFd) :
mDispatchReadFd(dispatchReadFd), mDispatchWriteFd(dispatchWriteFd),
mDispatchLooper(looper), mHandler(new WeakMessageHandler(this)) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
mInputQueueWeakGlobal = env->NewGlobalRef(inputQueueObj);
}
InputQueue::~InputQueue() {
mDispatchLooper->removeMessages(mHandler);
JNIEnv* env = AndroidRuntime::getJNIEnv();
env->DeleteGlobalRef(mInputQueueWeakGlobal);
close(mDispatchReadFd);
close(mDispatchWriteFd);
}
void InputQueue::attachLooper(Looper* looper, int ident,
ALooper_callbackFunc callback, void* data) {
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mAppLoopers.size(); i++) {
if (looper == mAppLoopers[i]) {
return;
}
}
mAppLoopers.push(looper);
looper->addFd(mDispatchReadFd, ident, ALOOPER_EVENT_INPUT, callback, data);
}
void InputQueue::detachLooper() {
Mutex::Autolock _l(mLock);
detachLooperLocked();
}
void InputQueue::detachLooperLocked() {
for (size_t i = 0; i < mAppLoopers.size(); i++) {
mAppLoopers[i]->removeFd(mDispatchReadFd);
}
mAppLoopers.clear();
}
bool InputQueue::hasEvents() {
Mutex::Autolock _l(mLock);
return mPendingEvents.size() > 0;
}
status_t InputQueue::getEvent(InputEvent** outEvent) {
Mutex::Autolock _l(mLock);
*outEvent = NULL;
if (!mPendingEvents.isEmpty()) {
*outEvent = mPendingEvents[0];
mPendingEvents.removeAt(0);
}
if (mPendingEvents.isEmpty()) {
char byteread[16];
ssize_t nRead;
do {
nRead = TEMP_FAILURE_RETRY(read(mDispatchReadFd, &byteread, sizeof(byteread)));
if (nRead < 0 && errno != EAGAIN) {
ALOGW("Failed to read from native dispatch pipe: %s", strerror(errno));
}
} while (nRead > 0);
}
return *outEvent != NULL ? OK : WOULD_BLOCK;
}
bool InputQueue::preDispatchEvent(InputEvent* e) {
if (e->getType() == AINPUT_EVENT_TYPE_KEY) {
KeyEvent* keyEvent = static_cast<KeyEvent*>(e);
if (keyEvent->getFlags() & AKEY_EVENT_FLAG_PREDISPATCH) {
finishEvent(e, false);
return true;
}
}
return false;
}
void InputQueue::finishEvent(InputEvent* event, bool handled) {
Mutex::Autolock _l(mLock);
mFinishedEvents.push(key_value_pair_t<InputEvent*, bool>(event, handled));
if (mFinishedEvents.size() == 1) {
mDispatchLooper->sendMessage(this, Message(MSG_FINISH_INPUT));
}
}
void InputQueue::handleMessage(const Message& message) {
switch(message.what) {
case MSG_FINISH_INPUT:
JNIEnv* env = AndroidRuntime::getJNIEnv();
ScopedLocalRef<jobject> inputQueueObj(env, jniGetReferent(env, mInputQueueWeakGlobal));
if (!inputQueueObj.get()) {
ALOGW("InputQueue was finalized without being disposed");
return;
}
while (true) {
InputEvent* event;
bool handled;
{
Mutex::Autolock _l(mLock);
if (mFinishedEvents.isEmpty()) {
break;
}
event = mFinishedEvents[0].getKey();
handled = mFinishedEvents[0].getValue();
mFinishedEvents.removeAt(0);
}
env->CallVoidMethod(inputQueueObj.get(), gInputQueueClassInfo.finishInputEvent,
reinterpret_cast<jlong>(event), handled);
recycleInputEvent(event);
}
break;
}
}
void InputQueue::recycleInputEvent(InputEvent* event) {
mPooledInputEventFactory.recycle(event);
}
KeyEvent* InputQueue::createKeyEvent() {
return mPooledInputEventFactory.createKeyEvent();
}
MotionEvent* InputQueue::createMotionEvent() {
return mPooledInputEventFactory.createMotionEvent();
}
void InputQueue::enqueueEvent(InputEvent* event) {
Mutex::Autolock _l(mLock);
mPendingEvents.push(event);
if (mPendingEvents.size() == 1) {
char dummy = 0;
int res = TEMP_FAILURE_RETRY(write(mDispatchWriteFd, &dummy, sizeof(dummy)));
if (res < 0 && errno != EAGAIN) {
ALOGW("Failed writing to dispatch fd: %s", strerror(errno));
}
}
}
InputQueue* InputQueue::createQueue(jobject inputQueueObj, const sp<Looper>& looper) {
int pipeFds[2];
if (pipe(pipeFds)) {
ALOGW("Could not create native input dispatching pipe: %s", strerror(errno));
return NULL;
}
fcntl(pipeFds[0], F_SETFL, O_NONBLOCK);
fcntl(pipeFds[1], F_SETFL, O_NONBLOCK);
return new InputQueue(inputQueueObj, looper, pipeFds[0], pipeFds[1]);
}
static jlong nativeInit(JNIEnv* env, jobject clazz, jobject queueWeak, jobject jMsgQueue) {
sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, jMsgQueue);
if (messageQueue == NULL) {
jniThrowRuntimeException(env, "MessageQueue is not initialized.");
return 0;
}
sp<InputQueue> queue = InputQueue::createQueue(queueWeak, messageQueue->getLooper());
if (!queue.get()) {
jniThrowRuntimeException(env, "InputQueue failed to initialize");
return 0;
}
queue->incStrong(&gInputQueueClassInfo);
return reinterpret_cast<jlong>(queue.get());
}
static void nativeDispose(JNIEnv* env, jobject clazz, jlong ptr) {
sp<InputQueue> queue = reinterpret_cast<InputQueue*>(ptr);
queue->detachLooper();
queue->decStrong(&gInputQueueClassInfo);
}
static jlong nativeSendKeyEvent(JNIEnv* env, jobject clazz, jlong ptr, jobject eventObj,
jboolean predispatch) {
InputQueue* queue = reinterpret_cast<InputQueue*>(ptr);
KeyEvent* event = queue->createKeyEvent();
status_t status = android_view_KeyEvent_toNative(env, eventObj, event);
if (status) {
queue->recycleInputEvent(event);
jniThrowRuntimeException(env, "Could not read contents of KeyEvent object.");
return -1;
}
if (predispatch) {
event->setFlags(event->getFlags() | AKEY_EVENT_FLAG_PREDISPATCH);
}
queue->enqueueEvent(event);
return reinterpret_cast<jlong>(event);
}
static jlong nativeSendMotionEvent(JNIEnv* env, jobject clazz, jlong ptr, jobject eventObj) {
sp<InputQueue> queue = reinterpret_cast<InputQueue*>(ptr);
MotionEvent* originalEvent = android_view_MotionEvent_getNativePtr(env, eventObj);
if (!originalEvent) {
jniThrowRuntimeException(env, "Could not obtain MotionEvent pointer.");
return -1;
}
MotionEvent* event = queue->createMotionEvent();
event->copyFrom(originalEvent, true /* keepHistory */);
queue->enqueueEvent(event);
return reinterpret_cast<jlong>(event);
}
static const JNINativeMethod g_methods[] = {
{ "nativeInit", "(Ljava/lang/ref/WeakReference;Landroid/os/MessageQueue;)J",
(void*) nativeInit },
{ "nativeDispose", "(J)V", (void*) nativeDispose },
{ "nativeSendKeyEvent", "(JLandroid/view/KeyEvent;Z)J", (void*) nativeSendKeyEvent },
{ "nativeSendMotionEvent", "(JLandroid/view/MotionEvent;)J", (void*) nativeSendMotionEvent },
};
static const char* const kInputQueuePathName = "android/view/InputQueue";
int register_android_view_InputQueue(JNIEnv* env)
{
jclass clazz = FindClassOrDie(env, kInputQueuePathName);
gInputQueueClassInfo.finishInputEvent = GetMethodIDOrDie(env, clazz, "finishInputEvent",
"(JZ)V");
return RegisterMethodsOrDie(env, kInputQueuePathName, g_methods, NELEM(g_methods));
}
} // namespace android
| 33.095941 | 97 | 0.671312 | [
"object"
] |
24c70ca17524a1f63a89f056d88377e691622a8e | 2,648 | hpp | C++ | ESMF/src/Infrastructure/Mesh/src/Moab/moab/UnknownInterface.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2018-07-05T16:48:58.000Z | 2018-07-05T16:48:58.000Z | ESMF/src/Infrastructure/Mesh/src/Moab/moab/UnknownInterface.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | ESMF/src/Infrastructure/Mesh/src/Moab/moab/UnknownInterface.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | null | null | null | /* Filename : UnkonwnInterface.h
* Creator : Clinton Stimpson
*
* Date : 10 Jan 2002
*
* Owner : Clinton Stimpson
*
* Description: Contains declarations for MBuuid which keeps
* track of different interfaces.
* Also contains the declaration for the base class
* UknownInterface from which all interfaces are
* derived from
*/
#ifndef MOAB_UNKNOWN_INTERFACE_HPP
#define MOAB_UNKNOWN_INTERFACE_HPP
#include <memory.h>
namespace moab {
//! struct that handles universally unique id's for the Mesh Database
// note: this MBuuid is compliant with the windows GUID.
// It is possible to do a memcpy() to copy the data from a MBuuid to a GUID
// if we want to support dll registration
struct MBuuid
{
//! default constructor that initializes to zero
MBuuid()
{
memset( this, 0, sizeof(MBuuid) );
}
//! constructor that takes initialization arguments
MBuuid( unsigned l, unsigned short w1, unsigned short w2,
unsigned char b1, unsigned char b2, unsigned char b3,
unsigned char b4, unsigned char b5, unsigned char b6,
unsigned char b7, unsigned char b8 )
{
data1 = l;
data2 = w1;
data3 = w2;
data4[0] = b1;
data4[1] = b2;
data4[2] = b3;
data4[3] = b4;
data4[4] = b5;
data4[5] = b6;
data4[6] = b7;
data4[7] = b8;
}
//! copy constructor
MBuuid( const MBuuid& mdbuuid )
{
memcpy( this, &mdbuuid, sizeof(MBuuid));
}
//! sets this uuid equal to another one
MBuuid &operator=(const MBuuid& orig)
{
memcpy( this, &orig, sizeof(MBuuid));
return *this;
}
//! returns whether two uuid's are equal
bool operator==(const MBuuid& orig) const
{
return !memcmp(this, &orig, sizeof(MBuuid));
}
//! returns whether two uuid's are not equal
bool operator!=(const MBuuid& orig) const
{
return!(*this == orig);
}
//! uuid data storage
unsigned data1;
unsigned short data2;
unsigned short data3;
unsigned char data4[8];
};
//! uuid for an unknown interface
//! this can be used to either return a default interface
//! or a NULL interface
static const MBuuid IDD_MBUnknown = MBuuid( 0xf4f6605e, 0x2a7e, 0x4760,
0xbb, 0x06, 0xb9, 0xed, 0x27, 0xe9, 0x4a, 0xec );
//! base class for all interface classes
class UnknownInterface
{
public:
virtual int QueryInterface
( const MBuuid&, UnknownInterface** ) = 0;
virtual ~UnknownInterface() {}
};
} // namespace moab
#endif // MOAB_UNKNOWN_INTERFACE_HPP
| 26.217822 | 75 | 0.625378 | [
"mesh"
] |
24c9fd3188ec2d403713d76bede54645675e70e4 | 18,221 | cpp | C++ | src/solve.cpp | yp/Heu-MCHC | 30c4a5e189c7ab67d82357d2c8a98833a556345a | [
"BSD-3-Clause"
] | 1 | 2020-06-30T04:39:34.000Z | 2020-06-30T04:39:34.000Z | src/solve.cpp | yp/Heu-MCHC | 30c4a5e189c7ab67d82357d2c8a98833a556345a | [
"BSD-3-Clause"
] | null | null | null | src/solve.cpp | yp/Heu-MCHC | 30c4a5e189c7ab67d82357d2c8a98833a556345a | [
"BSD-3-Clause"
] | null | null | null | /**
*
*
* Heu-MCHC
*
* A fast and accurate heuristic algorithm for the haplotype inference
* problem on pedigree data with recombinations and mutations
*
* Copyright (C) 2009,2010,2011 Yuri PIROLA
*
* Distributed under the terms of the GNU General Public License (GPL)
*
*
* This file is part of Heu-MCHC.
*
* Heu-MCHC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Heu-MCHC 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 Heu-MCHC. If not, see <http://www.gnu.org/licenses/>.
*
**/
#include "solve.hpp"
#include "util.h"
#include "log.h"
#include "belief-propagation.hpp"
#include "locus-graph.hpp"
#ifndef MAX_ITER
#define MAX_ITER 100
#endif
#include "my_time.h"
extern pmytime pt_gauss;
#include <m4ri/m4ri.h>
using namespace ped;
static void
print_mapping_variables(FILE* fout, system_desc& sd) {
fprintf(fout, "* Column headers\n");
for (system_desc::cols_node* cn= sd.cols_begin();
cn != sd.cols_end();
cn= cn->next()) {
fprintf(fout, "* %s\n", (**cn).header()->to_c_str());
}
}
static void
print_system_description(FILE* fout, system_desc& sd, bool force= false) {
if (!force && sd.n_cols()-sd.n_rows()>300) {fprintf(fout, "* System description too big. Skipped.\n");return;}
print_mapping_variables(fout, sd);
fprintf(fout, "* System description\n");
// fprintf(fout, "* ");
// for (system_desc::cols_node* cn= sd.cols_begin();
// cn != sd.cols_end();
// cn= cn->next()) {
// fprintf(fout, "%5d ", (**cn).header()->id);}
// fprintf(fout, "\n");
for (system_desc::rows_node* rn= sd.rows_begin();
rn != sd.rows_end();
rn= rn->next()) {
fprintf(fout, "* " ST_FMTL(5) " ", (**rn).header()->id);
system_desc::cols_node* cn= sd.cols_begin();
system_desc::row_node* ri= (**rn).begin();
while (ri != (**rn).end()) {
if ((**ri).col().header()->id == (**cn).header()->id) {
fprintf(fout, "X");
cn= cn->next();
ri= ri->next();
} else {
fprintf(fout, " ");
cn= cn->next();
}
}
fprintf(fout, "\n");
}
}
static system_desc::cols_node*
apply_bp(system_desc& sd, const size_t iter,
const BP_T* p,
const double gamma,
const size_t max_iter=100) {
INFO("Iteration of belief propagation.");
DEBUG("Set the priori probabilities.");
for (system_desc::cols_node* cs= sd.cols_begin();
cs != sd.cols_end() &&
!(**cs).header()->phantom;
cs= cs->next()) {
(**cs).header()->p1= p[(**cs).header()->mv.kind()];
}
struct _bp_config bp = {
gamma,
max_iter,
false //true //iter==10 //false
};
belief_propagation(sd, &bp);
// set to 1 one of the variables that has the highest q1 probability
system_desc::cols_node* max1= NULL;
BP_T q1max= BP0;
size_t n_max= 0;
for (system_desc::cols_node* cs= sd.cols_begin();
cs != sd.cols_end() &&
!(**cs).header()->phantom;
cs= cs->next()) {
const BP_T q1t= (**cs).header()->q1;
// TRACE("Variable %3d with q1 %23.20f.", (**cs).header()->id, q1t);
if((max1==NULL) || ONE_MORE_PROBABLE_THAN(q1t, q1max)) {
max1= cs;
q1max= q1t;
n_max= 1;
} else if (q1t == q1max) {
++n_max;
}
}
INFO("The maximum posteriori probability is %.8e.", BP2D(q1max));
INFO("Variables with posteriori probability %.8e are:", BP2D(q1max));
max1= NULL;
for (system_desc::cols_node* cs= sd.cols_begin();
cs != sd.cols_end();
cs= cs->next()) {
if (!(**cs).header()->phantom) {
const BP_T q1t= (**cs).header()->q1;
if (q1t==q1max) {
INFO("%s", (**cs).header()->to_c_str());
if ((max1==NULL) && (rnd_01() < (1.0/n_max))) {
max1= cs;
}
--n_max;
}
}
}
my_assert(max1 != NULL);
INFO("Setting variable " ST_FMTL(5) " %s to 1.",
(**max1).header()->id, (**max1).header()->mv.to_c_str());
return max1;
}
// check if the remaining constraints are all satisfied
static bool
is_system_feasible(const system_desc& sd) {
// if the panthom variables are not assigned, then the system is feasible
bool feasible= true;
for (system_desc::rows_node* rs= sd.rows_begin();
feasible && rs != sd.rows_end();
rs= rs->next()) {
// The last element of each row has to be a phantom variable
my_assert((**rs).end()->prev()->data().col().header()->phantom);
feasible= !(**(**rs).end()->prev()).col().header()->assigned;
}
return feasible;
}
static system_desc::cols_node*
remove_column(system_desc::cols_node* csn,
bool change) {
DEBUG("Removing variable " ST_FMTL(5) " .", (**csn).header()->id);
for (system_desc::col_node* cn= (**csn).begin();
cn != (**csn).end();
){
// If requested, change the fixed value of the phantom variable
if (change) {
DEBUG("Changing assignment of constraint " ST_FMTL(5) " ", (**cn).row().header()->id);
col_h* const chp= (**cn).row().end()->prev()->data().col().header();
my_assert(chp->phantom);
chp->assigned= !chp->assigned;
chp->p1= chp->assigned?BP1:BP0;
}
system_desc::row_node* const rn= (**cn).row_n();
rn->remove();
cn= cn->free_and_remove(sd_del());
}
delete (**csn).header();
delete csn->pdata();
return csn->remove();
}
static system_desc::rows_node*
remove_row(system_desc::rows_node* rsn) {
DEBUG("Removing constraint " ST_FMTL(5) " .", (**rsn).header()->id);
for (system_desc::row_node* rn= (**rsn).begin();
rn != (**rsn).end();
){
system_desc::col_node* const cn= (**rn).col_n();
cn->remove();
rn= rn->free_and_remove(sd_del());
}
delete (**rsn).header();
delete rsn->pdata();
return rsn->remove();
}
static bool
simplify_empty_columns(system_desc& sd) {
bool mod= false;
for (system_desc::cols_node* csn= sd.cols_begin();
csn != sd.cols_end();
) {
if ((**csn).size()==0) {
DEBUG("it header %p", (void*)((**csn).header()));
DEBUG("Variable [%s] does not appear in any constraints.",
(**csn).header()->to_c_str());
csn= remove_column(csn, false);
mod= true;
} else {
csn= csn->next();
}
}
return mod;
}
static inline unsigned int
count_ones(const unsigned int v) {
unsigned int c; // store the total here
static const int S[] = {1, 2, 4, 8, 16}; // Magic Binary Numbers
static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};
c = v - ((v >> 1) & B[0]);
c = ((c >> S[1]) & B[1]) + (c & B[1]);
c = ((c >> S[2]) + c) & B[2];
c = ((c >> S[3]) + c) & B[3];
c = ((c >> S[4]) + c) & B[4];
return c;
}
#ifdef _SIMPLIFY_CYCLE_CONSTRAINTS
static void
simplify_cycle_constraints(cycle_constraints_t& cc,
cycle_constraints_t& ncc) {
// Build the variable set
e_vars_t ev;
size_t i= 0;
for (cycle_constraints_t::iterator it= cc.begin();
it!=cc.end();
++it, ++i) {
ev.insert(((*it)->events).begin(), ((*it)->events).end());
}
std::vector<e_variable_t> evv(ev.begin(), ev.end());
const size_t n_cc= i;
const size_t n_var= evv.size();
// Shuffle the variable set
for (i= 0; i<n_var; ++i) {
const size_t newv= rand()%n_var;
e_variable_t _t= evv[i];
evv[i]= evv[newv];
evv[newv]= _t;
}
i= 0;
std::map<e_variable_t, int> evm;
for (std::vector<e_variable_t>::const_iterator it= evv.begin();
it!= evv.end(); ++it, ++i) {
evm[*it]= i;
}
// Build the binary matrix
mzd_t* bm= mzd_init(n_cc, n_var+1);
size_t r= 0;
for (cycle_constraints_t::iterator it= cc.begin();
it!=cc.end();
++it, ++r) {
for (e_vars_t::const_iterator ite= ((*it)->events).begin();
ite!=((*it)->events).end(); ++ite) {
mzd_write_bit(bm, r, evm[*ite], 1);
}
mzd_write_bit(bm, r, n_var, ((*it)->constant)?1:0);
}
const size_t rank= mzd_echelonize_m4ri(bm, 1, 0);
for (r= 0; r<rank; ++r) {
ped::cycle_constraint_t* c= new ped::cycle_constraint_t;
ncc.push_back(c);
for (i= r; i<n_var; ++i) {
if (mzd_read_bit(bm, r, i)==1) {
c->events.insert(evv[i]);
}
}
c->constant= (mzd_read_bit(bm, r, n_var)==1);
}
mzd_free(bm);
}
#endif
static bool
full_simplify_constraints_gauss(system_desc& sd, e_vars_t* const mmut)
throw (ped_hi_exception) {
MYTIME_start(pt_gauss);
bool mod= false;
const size_t num_constraints= sd.n_rows();
const size_t num_vars= sd.n_cols()-sd.n_rows();
INFO("Full Gauss elimination.");
mzd_t *bm_c = mzd_init(num_constraints, num_vars+1);
size_t c= 0;
for (system_desc::cols_node* cn= sd.cols_begin();
cn != sd.cols_end() && !(**cn).header()->phantom;
cn= cn->next()){
(**cn).header()->pos= c;
++c;
}
size_t i= 0;
size_t n_ones= 0;
for (system_desc::rows_node* rs= sd.rows_begin();
rs != sd.rows_end();
rs= rs->next(), ++i) {
for (system_desc::row_node* rn= (**rs).begin();
rn != (**rs).end() && !(**rn).col().header()->phantom;
rn= rn->next()) {
mzd_write_bit(bm_c, i, (**rn).col().header()->pos, 1);
++n_ones;
}
system_desc::row_node* pn= (**rs).end()->prev();
my_assert((**pn).col().header()->phantom);
mzd_write_bit(bm_c, i, num_vars, (**pn).col().header()->assigned?1:0);
}
for (size_t r= 0; r<num_constraints; ++r) {
const size_t newr= rand()%num_constraints;
mzd_row_swap(bm_c, r, newr);
}
INFO("Num. of one entries: " ST_FMTL(11) " ", n_ones);
const size_t rank_c= mzd_echelonize_m4ri(bm_c, 1, 2);
INFO("Rank of the complete matrix:" ST_FMTL(8) " ", rank_c);
size_t first_one= rank_c-1;
while ((first_one <= num_vars) && (mzd_read_bit(bm_c, rank_c-1, first_one)==0))
++first_one;
if (first_one==num_vars)
throw ped_hi_exception("Unsatisfable configuration found (from FullGauss).");
// Erasing variables that must assume a given value
// Such variables have only one 1 entry on a row
#ifdef LOG_INFO_ENABLED
size_t erased_vars= 0;
size_t set_vars= 0;
size_t erased_constr= 0;
#endif
const size_t lim32= num_vars-(num_vars%32);
size_t totones= 0;
for (i= 0; i<rank_c; ++i) {
// Check if row i has only one 1 entry in bm
size_t n_ones_in_row= 0;
unsigned int wrd;
for (size_t c= (i/32)*32; (c<lim32)&&(n_ones_in_row<2); c+= 32) {
wrd= mzd_read_bits(bm_c, i, c, 32);
n_ones_in_row+= count_ones(wrd);
}
if (lim32<num_vars) {
wrd= mzd_read_bits(bm_c, i, lim32, (num_vars%32));
n_ones_in_row+= count_ones(wrd);
}
totones+= n_ones_in_row;
TRACE("Constraint %5d has " ST_FMTL(5) " 1-entries in the row-echelon form.",
bm_c->rowperm[i], n_ones_in_row);
my_assert(n_ones_in_row>0);
if (n_ones_in_row==1) {
DEBUG("Constraint " ST_FMTL(5) " has only one 1-entry in the row-echelon form.",
bm_c->rowperm[i]);
// Find the only one 1-entry
size_t c=0;
while (c<num_vars && mzd_read_bit(bm_c, i, c)==0)
++c;
system_desc::cols_node* csn= sd.cols_begin();
while ((**csn).header()->pos!=c) {
csn= csn->next();
}
bool change= mzd_read_bit(bm_c, i, num_vars)==1;
ped::e_variable_t mv= (**csn).header()->mv;
#ifdef LOG_INFO_ENABLED
++erased_vars;
#endif
if (change) {
INFO("Adding variable %s to the result because of FullGaussSimplification.",
mv.to_c_str());
mmut->insert(mv);
#ifdef LOG_INFO_ENABLED
++set_vars;
#endif
} else {
INFO("Removing variable %s that must be unset because of FullGaussSimplification.",
mv.to_c_str());
}
remove_column(csn, change);
mod= true;
}
}
INFO("Erased " ST_FMTL(4) " variables (" ST_FMTL(4) " of them added as predicted events)",
erased_vars, set_vars);
if (rank_c<num_constraints) {
std::vector<size_t> toerase;
for (i=rank_c; i<num_constraints; ++i) {
DEBUG("Erasing constraint " ST_FMTL(5) " because it is linear dependent.", bm_c->rowperm[i]);
toerase.push_back(bm_c->rowperm[i]);
}
std::sort(toerase.begin(), toerase.end());
i= 0;
std::vector<size_t>::const_iterator it= toerase.begin();
for (system_desc::rows_node* rsn= sd.rows_begin();
rsn!= sd.rows_end() && it != toerase.end();
++i) {
if (i == *it) {
DEBUG("Erasing constraint " ST_FMTL(5) " .", *it);
system_desc::rows_node* rsn1= rsn->next();
mod= true;
remove_row(rsn);
rsn= rsn1;
++it;
#ifdef LOG_INFO_ENABLED
++erased_constr;
#endif
} else {
rsn= rsn->next();
}
}
INFO("Erased " ST_FMTL(4) " constraints.", erased_constr);
}
mzd_free(bm_c);
INFO("Gauss elimination terminated.");
MYTIME_stop(pt_gauss);
return mod;
}
// apply the gauss elimination, the constraint elimination,
// and the variable elimination
static void
simplify_constraints(system_desc& sd, e_vars_t* const mmut) {
INFO("Simplification of the system.");
const size_t num_constraints= sd.n_rows();
const size_t num_vars= sd.n_cols()-sd.n_rows();
DEBUG("Num. of remaining constraints: " ST_FMTL(5) " ", num_constraints);
DEBUG("Num. of remaining variables: " ST_FMTL(7) " ", num_vars);
full_simplify_constraints_gauss(sd, mmut);
simplify_empty_columns(sd);
#ifdef LOG_TRACE_ENABLED
DEBUG("Simplification terminated.");
print_system_description(stderr, sd);
#endif
}
static void
build_system_description(system_desc& sd,
cycle_constraints_t& cycle_constraints) {
for (cycle_constraints_t::const_iterator it= cycle_constraints.begin();
it!=cycle_constraints.end();
++it) {
const e_vars_t& cc= (*it)->events;
system_desc::row_t& r= sd.append_row(new row_h(*it))->data();
e_vars_t::iterator ccmvit= cc.begin();
system_desc::cols_node* cs= sd.cols_begin();
while (cs != sd.cols_end() && ccmvit != cc.end()) {
if ((**cs).header()->mv < *ccmvit) {
FINETRACE("Comparing variables %s to %s: SMALLER.",
cs->data().header()->mv.to_c_str(), (*ccmvit).to_c_str());
cs= cs->next();
} else if (*ccmvit < (**cs).header()->mv) {
FINETRACE("Comparing variables %s to %s: LARGER.",
cs->data().header()->mv.to_c_str(), (*ccmvit).to_c_str());
FINETRACE("Insert variable %s as column.", (*ccmvit).to_c_str());
system_desc::col_t& c=
sd.insert_col_before(new col_h(*ccmvit), cs)->data();
sd.insert_at(r, c, new bp_entry);
++ccmvit;
} else if (*ccmvit == (**cs).header()->mv) {
FINETRACE("Comparing variables %s to %s: EQUAL.",
cs->data().header()->mv.to_c_str(), (*ccmvit).to_c_str());
sd.insert_at(r, cs->data(), new bp_entry);
cs= cs->next();
++ccmvit;
}
}
while (ccmvit != cc.end()) {
FINETRACE("Insert variable %s as column.", (*ccmvit).to_c_str());
system_desc::col_t& c= sd.append_col(new col_h(*ccmvit))->data();
sd.insert_at(r, c, new bp_entry);
++ccmvit;
}
}
// Add the phantom variables
system_desc::rows_node* rn= sd.rows_begin();
for (cycle_constraints_t::const_iterator it= cycle_constraints.begin();
it!=cycle_constraints.end();
++it, rn= rn->next()) {
my_assert(rn != sd.rows_end());
system_desc::col_t& c= sd.append_col(new col_h((*it)->constant))->data();
sd.insert_at(rn->data(), c, new bp_entry);
}
#ifdef LOG_TRACE_ENABLED
print_system_description(stderr, sd);
#endif
}
e_vars_t*
calculate_minimum_solution(pgenped gp,
const size_t max_mut,
const double gamma,
const BP_T* p1
) throw (ped_hi_exception){
cycle_constraints_t cycle_constraints;
e_vars_t m_vars_univ;
build_constraints_from_pedigree(gp, cycle_constraints,
m_vars_univ);
#ifdef LOG_DEBUG_ENABLED
DEBUG("Constraints:");
int i= 0;
for (cycle_constraints_t::iterator it= cycle_constraints.begin();
it!=cycle_constraints.end();
++it, ++i) {
DEBUG("Constraint %4d.", i);
DEBUG("events: %s", to_c_str((*it)->events));
DEBUG("constant: %d", ((*it)->constant)?1:0);
}
#endif
system_desc sd;
#ifdef _SIMPLIFY_CYCLE_CONSTRAINTS
cycle_constraints_t new_cycle_constraints;
simplify_cycle_constraints(cycle_constraints, new_cycle_constraints);
#ifdef LOG_DEBUG_ENABLED
DEBUG("Simplified constraints:");
i= 0;
for (cycle_constraints_t::iterator it= new_cycle_constraints.begin();
it!=new_cycle_constraints.end();
++it, ++i) {
DEBUG("Constraint %4d.", i);
DEBUG("events: %s", to_c_str((*it)->events));
DEBUG("constant: %d", ((*it)->constant)?1:0);
}
#endif
// Build the system description
build_system_description(sd, new_cycle_constraints);
#else // IF NOT _SIMPLIFY_CYCLE_CONSTRAINTS
// Build the system description
build_system_description(sd, cycle_constraints);
#endif
e_vars_t* ris= new e_vars_t;
full_simplify_constraints_gauss(sd, ris);
#ifdef LOG_DEBUG_ENABLED
print_mapping_variables(stderr, sd);
#endif
// Apply the BP algorithm
size_t iter= 0;
size_t max_iter= MAX_ITER;
#ifdef LOG_INFO_ENABLED
for (unsigned int i= 0; i<ped::e_variable_t::N_KINDS; ++i) {
INFO("Base probability %s= %.4e.", ped::kind_names[i], BP2D(p1[i]));
}
#endif
INFO("Maximum no. of iterations= " ST_FMTL(4) " .", max_iter);
INFO("Damping gamma= %.5e.", gamma);
INFO("No. of constraints= " ST_FMTL(6) " .", sd.n_rows());
INFO("No. of variables= " ST_FMTL(7) " .", sd.n_cols()-sd.n_rows());
try {
while (!is_system_feasible(sd)){
INFO("Iteration " ST_FMTL(4) " .", iter+1);
simplify_constraints(sd, ris);
if (!is_system_feasible(sd)) {
system_desc::cols_node* mut_col= apply_bp(sd, iter,
p1,
gamma,
max_iter);
ris->insert((**mut_col).header()->mv);
remove_column(mut_col, true);
}
++iter;
if (ris->size()>max_mut)
throw ped_hi_exception("Maximum mutation limit passed.");
}
//Destroy the system and the cycle constraints
#ifdef _SIMPLIFY_CYCLE_CONSTRAINTS
for (cycle_constraints_t::iterator it= new_cycle_constraints.begin();
it!=new_cycle_constraints.end();
++it) {
delete *it;
}
#endif
for (cycle_constraints_t::iterator it= cycle_constraints.begin();
it!=cycle_constraints.end();
++it) {
delete *it;
}
sd.free(sd_del());
}
catch (int tmp) {
for (cycle_constraints_t::iterator it= cycle_constraints.begin();
it!=cycle_constraints.end();
++it) {
delete *it;
}
sd.free(sd_del());
delete ris;
throw;
}
return ris;
}
| 29.531605 | 112 | 0.639372 | [
"vector",
"3d"
] |
24cb725b34b7ff6a067603519851a648c42299e4 | 19,394 | hpp | C++ | giotto/externals/hera/bottleneck/bottleneck_detail.hpp | gtauzin/giotto-learn | 4cbd981f8113d44a80d68570a472d5a58245535b | [
"Apache-2.0"
] | 1 | 2019-10-16T11:41:40.000Z | 2019-10-16T11:41:40.000Z | giotto/externals/hera/bottleneck/bottleneck_detail.hpp | L2F-abelganz/giotto-learn | c290c70fa0c2f05d543633b78e297b506e36e4de | [
"Apache-2.0"
] | null | null | null | giotto/externals/hera/bottleneck/bottleneck_detail.hpp | L2F-abelganz/giotto-learn | c290c70fa0c2f05d543633b78e297b506e36e4de | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2015, M. Kerber, D. Morozov, A. Nigmetov
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You are under no obligation whatsoever to provide any bug fixes, patches, or
upgrades to the features, functionality or performance of the source code
(Enhancements) to anyone; however, if you choose to make your Enhancements
available either publicly, or directly to copyright holder,
without imposing a separate written license agreement for such Enhancements,
then you hereby grant the following license: a non-exclusive, royalty-free
perpetual license to install, use, modify, prepare derivative works, incorporate
into other computer software, distribute, and sublicense such enhancements or
derivative works thereof, in binary and source code form.
*/
#ifndef HERA_BOTTLENECK_HPP
#define HERA_BOTTLENECK_HPP
#ifdef FOR_R_TDA
#undef DEBUG_BOUND_MATCH
#undef DEBUG_MATCHING
#undef VERBOSE_BOTTLENECK
#endif
#include <iomanip>
#include <sstream>
#include <string>
#include <cctype>
#include "bottleneck_detail.h"
namespace hera {
namespace bt {
template<class Real>
void binarySearch(const Real epsilon,
std::pair<Real, Real>& result,
BoundMatchOracle<Real>& oracle,
const Real infinityCost,
bool isResultInitializedCorrectly,
const Real distProbeInit)
{
// aliases for result components
Real& distMin = result.first;
Real& distMax = result.second;
distMin = std::max(distMin, infinityCost);
distMax = std::max(distMax, infinityCost);
Real distProbe;
if (not isResultInitializedCorrectly) {
distProbe = distProbeInit;
if (oracle.isMatchLess(distProbe)) {
// distProbe is an upper bound,
// find lower bound with binary search
do {
distMax = distProbe;
distProbe /= 2.0;
} while (oracle.isMatchLess(distProbe));
distMin = distProbe;
} else {
// distProbe is a lower bound,
// find upper bound with exponential search
do {
distMin = distProbe;
distProbe *= 2.0;
} while (!oracle.isMatchLess(distProbe));
distMax = distProbe;
}
}
// bounds are correct , perform binary search
distProbe = ( distMin + distMax ) / 2.0;
while (( distMax - distMin ) / distMin >= epsilon ) {
if (distMax < infinityCost) {
distMin = infinityCost;
distMax = infinityCost;
break;
}
if (oracle.isMatchLess(distProbe)) {
distMax = distProbe;
} else {
distMin = distProbe;
}
distProbe = ( distMin + distMax ) / 2.0;
}
distMin = std::max(distMin, infinityCost);
distMax = std::max(distMax, infinityCost);
}
template<class Real>
inline Real getOneDimensionalCost(std::vector<Real> &set_A, std::vector<Real> &set_B)
{
if (set_A.size() != set_B.size()) {
return std::numeric_limits<Real>::infinity();
}
if (set_A.empty()) {
return Real(0.0);
}
std::sort(set_A.begin(), set_A.end());
std::sort(set_B.begin(), set_B.end());
Real result = 0.0;
for(size_t i = 0; i < set_A.size(); ++i) {
result = std::max(result, (std::fabs(set_A[i] - set_B[i])));
}
return result;
}
template<class Real>
inline Real getInfinityCost(const DiagramPointSet <Real> &A, const DiagramPointSet <Real> &B)
{
std::vector<Real> x_plus_A, x_minus_A, y_plus_A, y_minus_A;
std::vector<Real> x_plus_B, x_minus_B, y_plus_B, y_minus_B;
for(auto iter_A = A.cbegin(); iter_A != A.cend(); ++iter_A) {
Real x = iter_A->getRealX();
Real y = iter_A->getRealY();
if ( x == std::numeric_limits<Real>::infinity()) {
y_plus_A.push_back(y);
} else if (x == -std::numeric_limits<Real>::infinity()) {
y_minus_A.push_back(y);
} else if (y == std::numeric_limits<Real>::infinity()) {
x_plus_A.push_back(x);
} else if (y == -std::numeric_limits<Real>::infinity()) {
x_minus_A.push_back(x);
}
}
for(auto iter_B = B.cbegin(); iter_B != B.cend(); ++iter_B) {
Real x = iter_B->getRealX();
Real y = iter_B->getRealY();
if (x == std::numeric_limits<Real>::infinity()) {
y_plus_B.push_back(y);
} else if (x == -std::numeric_limits<Real>::infinity()) {
y_minus_B.push_back(y);
} else if (y == std::numeric_limits<Real>::infinity()) {
x_plus_B.push_back(x);
} else if (y == -std::numeric_limits<Real>::infinity()) {
x_minus_B.push_back(x);
}
}
Real infinity_cost = getOneDimensionalCost(x_plus_A, x_plus_B);
infinity_cost = std::max(infinity_cost, getOneDimensionalCost(x_minus_A, x_minus_B));
infinity_cost = std::max(infinity_cost, getOneDimensionalCost(y_plus_A, y_plus_B));
infinity_cost = std::max(infinity_cost, getOneDimensionalCost(y_minus_A, y_minus_B));
return infinity_cost;
}
// return the interval (distMin, distMax) such that:
// a) actual bottleneck distance between A and B is contained in the interval
// b) if the interval is not (0,0), then (distMax - distMin) / distMin < epsilon
template<class Real>
inline std::pair<Real, Real> bottleneckDistApproxInterval(DiagramPointSet<Real>& A, DiagramPointSet<Real>& B, const Real epsilon)
{
// empty diagrams are not considered as error
if (A.empty() and B.empty())
return std::make_pair(0.0, 0.0);
Real infinity_cost = getInfinityCost(A, B);
if (infinity_cost == std::numeric_limits<Real>::infinity())
return std::make_pair(infinity_cost, infinity_cost);
// link diagrams A and B by adding projections
addProjections(A, B);
// TODO: think about that!
// we need one threshold for checking if the distance is 0,
// another one for the oracle!
constexpr Real epsThreshold { 1.0e-10 };
std::pair<Real, Real> result { 0.0, 0.0 };
bool useRangeSearch { true };
// construct an oracle
BoundMatchOracle<Real> oracle(A, B, epsThreshold, useRangeSearch);
// check for distance = 0
if (oracle.isMatchLess(2*epsThreshold)) {
return result;
}
// get a 3-approximation of maximal distance between A and B
// as a starting value for probe distance
Real distProbe { getFurthestDistance3Approx<Real, DiagramPointSet<Real>>(A, B) };
binarySearch(epsilon, result, oracle, infinity_cost, false, distProbe);
return result;
}
template<class Real>
void sampleDiagramForHeur(const DiagramPointSet<Real>& dgmIn, DiagramPointSet<Real>& dgmOut)
{
struct pair_hash {
std::size_t operator()(const std::pair<Real, Real> p) const
{
return std::hash<Real>()(p.first) ^ std::hash<Real>()(p.second);
}
};
std::unordered_map<std::pair<Real, Real>, int, pair_hash> m;
for(auto ptIter = dgmIn.cbegin(); ptIter != dgmIn.cend(); ++ptIter) {
if (ptIter->isNormal() and not ptIter->isInfinity()) {
m[std::make_pair(ptIter->getRealX(), ptIter->getRealY())]++;
}
}
if (m.size() < 2) {
dgmOut = dgmIn;
return;
}
std::vector<int> v;
for(const auto& ptQtyPair : m) {
v.push_back(ptQtyPair.second);
}
std::sort(v.begin(), v.end());
int maxLeap = v[1] - v[0];
int cutVal = v[0];
for(int i = 1; i < static_cast<int>(v.size())- 1; ++i) {
int currLeap = v[i+1] - v[i];
if (currLeap > maxLeap) {
maxLeap = currLeap;
cutVal = v[i];
}
}
std::vector<std::pair<Real, Real>> vv;
// keep points whose multiplicites are at most cutVal
// quick-and-dirty: fill in vv with copies of each point
// to construct DiagramPointSet from it later
for(const auto& ptQty : m) {
if (ptQty.second < cutVal) {
for(int i = 0; i < ptQty.second; ++i) {
vv.push_back(std::make_pair(ptQty.first.first, ptQty.first.second));
}
}
}
dgmOut.clear();
dgmOut = DiagramPointSet<Real>(vv.begin(), vv.end());
}
// return the interval (distMin, distMax) such that:
// a) actual bottleneck distance between A and B is contained in the interval
// b) if the interval is not (0,0), then (distMax - distMin) / distMin < epsilon
template<class Real>
std::pair<Real, Real> bottleneckDistApproxIntervalWithInitial(DiagramPointSet<Real>& A, DiagramPointSet<Real>& B,
const Real epsilon,
const std::pair<Real, Real> initialGuess,
const Real infinity_cost)
{
// empty diagrams are not considered as error
if (A.empty() and B.empty())
return std::make_pair(0.0, 0.0);
// link diagrams A and B by adding projections
addProjections(A, B);
constexpr Real epsThreshold { 1.0e-10 };
std::pair<Real, Real> result { 0.0, 0.0 };
bool useRangeSearch { true };
// construct an oracle
BoundMatchOracle<Real> oracle(A, B, epsThreshold, useRangeSearch);
Real& distMin {result.first};
Real& distMax {result.second};
// initialize search interval from initialGuess
distMin = initialGuess.first;
distMax = initialGuess.second;
assert(distMin <= distMax);
// make sure that distMin is a lower bound
while(oracle.isMatchLess(distMin)) {
// distMin is in fact an upper bound, so assign it to distMax
distMax = distMin;
// and decrease distMin by 5 %
distMin = 0.95 * distMin;
}
// make sure that distMax is an upper bound
while(not oracle.isMatchLess(distMax)) {
// distMax is in fact a lower bound, so assign it to distMin
distMin = distMax;
// and increase distMax by 5 %
distMax = 1.05 * distMax;
}
// bounds are found, perform binary search
Real distProbe = ( distMin + distMax ) / 2.0;
binarySearch(epsilon, result, oracle, infinity_cost, true, distProbe);
return result;
}
// return the interval (distMin, distMax) such that:
// a) actual bottleneck distance between A and B is contained in the interval
// b) if the interval is not (0,0), then (distMax - distMin) / distMin < epsilon
// use heuristic: initial estimate on sampled diagrams
template<class Real>
std::pair<Real, Real> bottleneckDistApproxIntervalHeur(DiagramPointSet<Real>& A, DiagramPointSet<Real>& B, const Real epsilon)
{
// empty diagrams are not considered as error
if (A.empty() and B.empty())
return std::make_pair(0.0, 0.0);
Real infinity_cost = getInfinityCost(A, B);
if (infinity_cost == std::numeric_limits<Real>::infinity())
return std::make_pair(infinity_cost, infinity_cost);
DiagramPointSet<Real> sampledA, sampledB;
sampleDiagramForHeur(A, sampledA);
sampleDiagramForHeur(B, sampledB);
std::pair<Real, Real> initGuess = bottleneckDistApproxInterval(sampledA, sampledB, epsilon);
initGuess.first = std::max(initGuess.first, infinity_cost);
initGuess.second = std::max(initGuess.second, infinity_cost);
return bottleneckDistApproxIntervalWithInitial<Real>(A, B, epsilon, initGuess, infinity_cost);
}
// get approximate distance,
// see bottleneckDistApproxInterval
template<class Real>
Real bottleneckDistApprox(DiagramPointSet<Real>& A, DiagramPointSet<Real>& B, const Real epsilon)
{
auto interval = bottleneckDistApproxInterval<Real>(A, B, epsilon);
return interval.second;
}
template<class Real>
Real bottleneckDistExactFromSortedPwDist(DiagramPointSet<Real>&A, DiagramPointSet<Real>& B, std::vector<Real>& pairwiseDist, const int decPrecision)
{
// trivial case: we have only one candidate
if (pairwiseDist.size() == 1)
return pairwiseDist[0];
bool useRangeSearch = true;
Real distEpsilon = std::numeric_limits<Real>::max();
Real diffThreshold = 0.1;
for(int k = 0; k < decPrecision; ++k) {
diffThreshold /= 10.0;
}
for(size_t k = 0; k < pairwiseDist.size() - 2; ++k) {
auto diff = pairwiseDist[k+1]- pairwiseDist[k];
if ( diff > diffThreshold and diff < distEpsilon ) {
distEpsilon = diff;
}
}
distEpsilon /= 3.0;
BoundMatchOracle<Real> oracle(A, B, distEpsilon, useRangeSearch);
// binary search
size_t iterNum {0};
size_t idxMin {0}, idxMax {pairwiseDist.size() - 1};
size_t idxMid;
while(idxMax > idxMin) {
idxMid = static_cast<size_t>(floor(idxMin + idxMax) / 2.0);
iterNum++;
// not A[imid] < dist <=> A[imid] >= dist <=> A[imid[ >= dist + eps
if (oracle.isMatchLess(pairwiseDist[idxMid] + distEpsilon / 2.0)) {
idxMax = idxMid;
} else {
idxMin = idxMid + 1;
}
}
idxMid = static_cast<size_t>(floor(idxMin + idxMax) / 2.0);
return pairwiseDist[idxMid];
}
template<class Real>
Real bottleneckDistExact(DiagramPointSet<Real>& A, DiagramPointSet<Real>& B)
{
return bottleneckDistExact(A, B, 14);
}
template<class Real>
Real bottleneckDistExact(DiagramPointSet<Real>& A, DiagramPointSet<Real>& B, const int decPrecision)
{
using DgmPoint = DiagramPoint<Real>;
constexpr Real epsilon = 0.001;
auto interval = bottleneckDistApproxInterval(A, B, epsilon);
if (interval.first == interval.second)
return interval.first;
const Real delta = 0.50001 * (interval.second - interval.first);
const Real approxDist = 0.5 * ( interval.first + interval.second);
const Real minDist = interval.first;
const Real maxDist = interval.second;
if ( delta == 0 ) {
return interval.first;
}
// copy points from A to a vector
// todo: get rid of this?
std::vector<DgmPoint> pointsA;
pointsA.reserve(A.size());
for(const auto& ptA : A) {
pointsA.push_back(ptA);
}
// in this vector we store the distances between the points
// that are candidates to realize
std::vector<Real> pairwiseDist;
{
// vector to store centers of vertical stripes
// two for each point in A and the id of the corresponding point
std::vector<std::pair<Real, DgmPoint>> xCentersVec;
xCentersVec.reserve(2 * pointsA.size());
for(auto ptA : pointsA) {
xCentersVec.push_back(std::make_pair(ptA.getRealX() - approxDist, ptA));
xCentersVec.push_back(std::make_pair(ptA.getRealX() + approxDist, ptA));
}
// lambda to compare pairs <coordinate, id> w.r.t coordinate
auto compLambda = [](std::pair<Real, DgmPoint> a, std::pair<Real, DgmPoint> b)
{ return a.first < b.first; };
std::sort(xCentersVec.begin(), xCentersVec.end(), compLambda);
// todo: sort points in B, reduce search range in lower and upper bounds
for(auto ptB : B) {
// iterator to the first stripe such that ptB lies to the left
// from its right boundary (x_B <= x_j + \delta iff x_j >= x_B - \delta
auto itStart = std::lower_bound(xCentersVec.begin(),
xCentersVec.end(),
std::make_pair(ptB.getRealX() - delta, ptB),
compLambda);
for(auto iterA = itStart; iterA < xCentersVec.end(); ++iterA) {
if ( ptB.getRealX() < iterA->first - delta) {
// from that moment x_B >= x_j - delta
// is violated: x_B no longer lies to right from the left
// boundary of current stripe
break;
}
// we're here => ptB lies in vertical stripe,
// check if distance fits into the interval we've found
Real pwDist = distLInf(iterA->second, ptB);
if (pwDist >= minDist and pwDist <= maxDist) {
pairwiseDist.push_back(pwDist);
}
}
}
}
{
// for y
// vector to store centers of vertical stripes
// two for each point in A and the id of the corresponding point
std::vector<std::pair<Real, DgmPoint>> yCentersVec;
yCentersVec.reserve(2 * pointsA.size());
for(auto ptA : pointsA) {
yCentersVec.push_back(std::make_pair(ptA.getRealY() - approxDist, ptA));
yCentersVec.push_back(std::make_pair(ptA.getRealY() + approxDist, ptA));
}
// lambda to compare pairs <coordinate, id> w.r.t coordinate
auto compLambda = [](std::pair<Real, DgmPoint> a, std::pair<Real, DgmPoint> b)
{ return a.first < b.first; };
std::sort(yCentersVec.begin(), yCentersVec.end(), compLambda);
// todo: sort points in B, reduce search range in lower and upper bounds
for(auto ptB : B) {
auto itStart = std::lower_bound(yCentersVec.begin(),
yCentersVec.end(),
std::make_pair(ptB.getRealY() - delta, ptB),
compLambda);
for(auto iterA = itStart; iterA < yCentersVec.end(); ++iterA) {
if ( ptB.getRealY() < iterA->first - delta) {
break;
}
Real pwDist = distLInf(iterA->second, ptB);
if (pwDist >= minDist and pwDist <= maxDist) {
pairwiseDist.push_back(pwDist);
}
}
}
}
std::sort(pairwiseDist.begin(), pairwiseDist.end());
return bottleneckDistExactFromSortedPwDist(A, B, pairwiseDist, decPrecision);
}
} // end namespace bt
} // end namespace hera
#endif // HERA_BOTTLENECK_HPP
| 38.177165 | 755 | 0.623646 | [
"vector"
] |
24d1769f77cf710bfbc1955f4eac3f670e8b462f | 319 | cc | C++ | third_party/OpenMesh-8.1/Doc/Examples/nav_code4a.cc | hporro/grafica_cpp | 1427bb6e8926b44be474b906e9f52cca77b3df9d | [
"MIT"
] | 216 | 2018-09-09T11:53:56.000Z | 2022-03-19T13:41:35.000Z | Doc/Examples/nav_code4a.cc | planetmarshall/openmesh | c6833ff28a126769694bf694a55b1b30ee30a161 | [
"BSD-3-Clause"
] | 13 | 2018-10-23T08:29:09.000Z | 2021-09-08T06:45:34.000Z | Doc/Examples/nav_code4a.cc | planetmarshall/openmesh | c6833ff28a126769694bf694a55b1b30ee30a161 | [
"BSD-3-Clause"
] | 41 | 2018-09-13T08:50:41.000Z | 2022-02-23T00:33:54.000Z | // Get the halfedge handle of i.e. the halfedge
// that is associated to the first vertex
// of our set of vertices
PolyMesh::HalfedgeHandle heh = mesh.halfedge_handle(*(mesh.vertices_begin()));
// Now get the handle of its opposing halfedge
PolyMesh::HalfedgeHandle opposite_heh = mesh.opposite_halfedge_handle(heh);
| 39.875 | 78 | 0.777429 | [
"mesh"
] |
24d2f482b11a8177043a6a102568e56e4beeaa86 | 7,063 | cpp | C++ | test/DerivativeSignalTest.cpp | asmaalrawi/geopm | e93548dfdd693a17c81163787ba467891937356d | [
"BSD-3-Clause"
] | 1 | 2018-11-27T16:53:06.000Z | 2018-11-27T16:53:06.000Z | test/DerivativeSignalTest.cpp | asmaalrawi/geopm | e93548dfdd693a17c81163787ba467891937356d | [
"BSD-3-Clause"
] | null | null | null | test/DerivativeSignalTest.cpp | asmaalrawi/geopm | e93548dfdd693a17c81163787ba467891937356d | [
"BSD-3-Clause"
] | 1 | 2018-06-24T17:32:25.000Z | 2018-06-24T17:32:25.000Z | /*
* Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation
*
* 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 Intel 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 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <memory>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "DerivativeSignal.hpp"
#include "Helper.hpp"
#include "MockSignal.hpp"
#include "geopm_test.hpp"
using geopm::Signal;
using geopm::DerivativeSignal;
using testing::Return;
using testing::InvokeWithoutArgs;
class DerivativeSignalTest : public ::testing::Test
{
protected:
void SetUp(void);
std::shared_ptr<MockSignal> m_time_sig;
std::shared_ptr<MockSignal> m_y_sig;
std::unique_ptr<Signal> m_sig;
// example data
std::vector<double> m_sample_values_0;
double m_exp_slope_0;
std::vector<double> m_sample_values_1;
double m_exp_slope_1;
std::vector<double> m_sample_values_2;
double m_exp_slope_2;
int m_num_history_sample = 8;
double m_sleep_time = 0.001;
};
void DerivativeSignalTest::SetUp(void)
{
m_time_sig = std::make_shared<MockSignal>();
m_y_sig = std::make_shared<MockSignal>();
m_sig = geopm::make_unique<DerivativeSignal>(m_time_sig, m_y_sig,
m_num_history_sample, m_sleep_time);
// should have slope of 0.0
m_sample_values_0 = {5.5, 5.5, 5.5, 5.5};
m_exp_slope_0 = 0.0;
// should have slope of 1.0
m_sample_values_1 = {0.000001, 0.999999, 2.000001,
2.999999, 4.000001, 4.999999,
6.000001, 6.999999, 8.000001,
8.999999};
m_exp_slope_1 = 1.0;
// should have slope of .238 with least squares fit
m_sample_values_2 = {0, 1, 2, 3, 0, 1, 2, 3};
m_exp_slope_2 = 0.238;
}
TEST_F(DerivativeSignalTest, read_flat)
{
size_t ii = 0;
EXPECT_CALL(*m_time_sig, read()).Times(m_num_history_sample)
.WillRepeatedly(InvokeWithoutArgs([&ii]() {
++ii;
return ii;
}));
EXPECT_CALL(*m_y_sig, read()).Times(m_num_history_sample)
.WillRepeatedly(Return(7.7));
double result = m_sig->read();
EXPECT_NEAR(m_exp_slope_0, result, 0.0001);
}
TEST_F(DerivativeSignalTest, read_slope_1)
{
size_t ii = 0;
double val = 2.5;
EXPECT_CALL(*m_time_sig, read()).Times(m_num_history_sample)
.WillRepeatedly(InvokeWithoutArgs([&ii]() {
++ii;
return ii;
}));
EXPECT_CALL(*m_y_sig, read()).Times(m_num_history_sample)
.WillRepeatedly(InvokeWithoutArgs([&val]() {
val += 1.0;;
return val;
}));
double result = m_sig->read();
EXPECT_NEAR(m_exp_slope_1, result, 0.0001);
}
TEST_F(DerivativeSignalTest, read_batch_first)
{
EXPECT_CALL(*m_time_sig, setup_batch());
EXPECT_CALL(*m_y_sig, setup_batch());
m_sig->setup_batch();
EXPECT_CALL(*m_time_sig, sample()).WillOnce(Return(2.0));
EXPECT_CALL(*m_y_sig, sample()).WillOnce(Return(7.7));
double result = m_sig->sample();
EXPECT_TRUE(std::isnan(result));
}
TEST_F(DerivativeSignalTest, read_batch_flat)
{
EXPECT_CALL(*m_time_sig, setup_batch());
EXPECT_CALL(*m_y_sig, setup_batch());
m_sig->setup_batch();
double result = NAN;
for (size_t ii = 0; ii < m_sample_values_0.size(); ++ii) {
EXPECT_CALL(*m_time_sig, sample()).WillOnce(Return(ii));
EXPECT_CALL(*m_y_sig, sample()).WillOnce(Return(m_sample_values_0[ii]));
result = m_sig->sample();
}
EXPECT_NEAR(m_exp_slope_0, result, 0.0001);
}
TEST_F(DerivativeSignalTest, read_batch_slope_1)
{
EXPECT_CALL(*m_time_sig, setup_batch());
EXPECT_CALL(*m_y_sig, setup_batch());
m_sig->setup_batch();
double result = NAN;
for (size_t ii = 0; ii < m_sample_values_1.size(); ++ii) {
EXPECT_CALL(*m_time_sig, sample()).WillOnce(Return(ii));
EXPECT_CALL(*m_y_sig, sample()).WillOnce(Return(m_sample_values_1[ii]));
result = m_sig->sample();
}
EXPECT_NEAR(m_exp_slope_1, result, 0.0001);
}
TEST_F(DerivativeSignalTest, read_batch_slope_2)
{
EXPECT_CALL(*m_time_sig, setup_batch());
EXPECT_CALL(*m_y_sig, setup_batch());
m_sig->setup_batch();
double result = NAN;
for (size_t ii = 0; ii < m_sample_values_2.size(); ++ii) {
EXPECT_CALL(*m_time_sig, sample()).WillOnce(Return(ii));
EXPECT_CALL(*m_y_sig, sample()).WillOnce(Return(m_sample_values_2[ii]));
result = m_sig->sample();
}
EXPECT_NEAR(m_exp_slope_2, result, 0.0001);
}
TEST_F(DerivativeSignalTest, setup_batch)
{
// check that setup_batch can be safely called twice
EXPECT_CALL(*m_time_sig, setup_batch()).Times(1);
EXPECT_CALL(*m_y_sig, setup_batch()).Times(1);
m_sig->setup_batch();
m_sig->setup_batch();
}
TEST_F(DerivativeSignalTest, errors)
{
#ifdef GEOPM_DEBUG
// cannot construct with null signals
GEOPM_EXPECT_THROW_MESSAGE(DerivativeSignal(nullptr, m_y_sig, 0, 0),
GEOPM_ERROR_LOGIC,
"time_sig and y_sig cannot be null");
GEOPM_EXPECT_THROW_MESSAGE(DerivativeSignal(m_time_sig, nullptr, 0, 0),
GEOPM_ERROR_LOGIC,
"time_sig and y_sig cannot be null");
#endif
// cannot call sample without setup_batch
GEOPM_EXPECT_THROW_MESSAGE(m_sig->sample(), GEOPM_ERROR_RUNTIME,
"setup_batch() must be called before sample()");
}
| 34.120773 | 85 | 0.655104 | [
"vector"
] |
24d660b655b94550e3fcd825437dd584affa6b82 | 1,686 | hpp | C++ | src/sqlite/value.hpp | wesselj1/mx3playground | 9b8c3e783f574a76cc17a9470b57e72a1b38be1a | [
"MIT"
] | 766 | 2015-01-01T17:33:40.000Z | 2022-02-23T08:20:20.000Z | src/sqlite/value.hpp | wesselj1/mx3playground | 9b8c3e783f574a76cc17a9470b57e72a1b38be1a | [
"MIT"
] | 43 | 2015-01-04T05:59:54.000Z | 2017-06-19T10:53:59.000Z | src/sqlite/value.hpp | wesselj1/mx3playground | 9b8c3e783f574a76cc17a9470b57e72a1b38be1a | [
"MIT"
] | 146 | 2015-01-09T19:38:23.000Z | 2021-09-30T08:39:44.000Z | #pragma once
#include "stl.hpp"
#include <iosfwd>
namespace mx3 { namespace sqlite {
class Value final {
public:
Value();
Value(std::nullptr_t x);
Value(int x);
Value(int64_t x);
Value(double x);
Value(const char * x);
Value(string x);
Value(vector<uint8_t> x);
Value(Value&& other) noexcept;
Value(const Value& other);
~Value();
Value& operator=(const Value& other);
Value& operator=(Value&& other) noexcept;
bool operator==(const Value& other) const;
enum class Type {
// Do not change the orders of these here, since they dictate ordering.
NUL,
INT,
DOUBLE,
STRING,
BLOB
};
Value::Type type() const { return m_type; }
bool is_null() const { return m_type == Type::NUL; }
bool is_numeric() const { return m_type == Type::INT || m_type == Type::DOUBLE; }
string move_string();
const string& string_value() const;
vector<uint8_t> move_blob();
const vector<uint8_t>& blob_value() const;
int int_value() const;
int64_t int64_value() const;
double double_value() const;
private:
Value::Type m_type;
union {
int64_t m_int64;
double m_double;
string m_string;
vector<uint8_t> m_blob;
};
};
using Row = vector<Value>;
// a comparison operator that also compares double and int values correctly
bool operator<(const Value& l, const Value& r);
std::ostream& operator <<(std::ostream& os, const mx3::sqlite::Value& v);
std::ostream& operator <<(std::ostream& os, const vector<mx3::sqlite::Value>& v);
std::ostream& operator <<(std::ostream& os, Value::Type t);
} } // end mx3::sqlite
| 25.545455 | 85 | 0.628114 | [
"vector"
] |
24d8812a3c549ab8986d0e6adb521c047216b9c6 | 3,725 | cpp | C++ | examples/opencl/mandelbrot/maps/main_maps.cpp | josephwinston/hpxcl | ebd18f245beea46be943ffa22e2fb8145b0b2836 | [
"BSL-1.0"
] | null | null | null | examples/opencl/mandelbrot/maps/main_maps.cpp | josephwinston/hpxcl | ebd18f245beea46be943ffa22e2fb8145b0b2836 | [
"BSL-1.0"
] | null | null | null | examples/opencl/mandelbrot/maps/main_maps.cpp | josephwinston/hpxcl | ebd18f245beea46be943ffa22e2fb8145b0b2836 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2014 Martin Stumpf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/hpx.hpp>
#include <hpx/hpx_init.hpp>
#include <hpx/include/iostreams.hpp>
#include <hpx/apply.hpp>
#include <hpx/util/static.hpp>
#include "../../../../opencl.hpp"
#include "maps_image_generator.hpp"
#include "requesthandler.hpp"
#include "webserver.hpp"
//#include "../maps_webserver.hpp"
#include <string>
#include <boost/shared_ptr.hpp>
int hpx_main(boost::program_options::variables_map & vm)
{
std::size_t num_kernels = 0;
bool verbose = false;
// Print help message on wrong argument count
if (vm.count("num-parallel-kernels"))
num_kernels = vm["num-parallel-kernels"].as<std::size_t>();
if (vm.count("v"))
verbose = true;
// The main scope
{
// get all devices
std::vector<hpx::opencl::device> devices =
hpx::opencl::get_all_devices(CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR, "OpenCL 1.1").get();
// Check whether there are any devices
if(devices.size() < 1)
{
hpx::cerr << "No OpenCL devices found!" << hpx::endl;
return hpx::finalize();
}
else
{
hpx::cout << devices.size() << " OpenCL devices found!" << hpx::endl;
}
size_t tilesize_x = 256;
size_t tilesize_y = 256;
size_t lines_per_gpu = 16;
// generate requesthandler, will order requests and convert coordinates
hpx::opencl::examples::mandelbrot::requesthandler requesthandler(
tilesize_x,
tilesize_y,
lines_per_gpu);
// create image_generator
hpx::opencl::examples::mandelbrot::maps_image_generator
img_gen(tilesize_x,
lines_per_gpu,
num_kernels,
verbose,
boost::bind(
&hpx::opencl::examples::mandelbrot::requesthandler::query_request,
&requesthandler),
devices);
// wait for workers to finish initialization
if(verbose) hpx::cout << "waiting for workers to finish startup ..." << hpx::endl;
img_gen.wait_for_startup_finished();
hpx::cout << "Starting webservers ..." << hpx::endl;
// generate webserver
hpx::opencl::examples::mandelbrot::webserver webserver(8080,
&requesthandler);
// start the webserver
webserver.start();
while(true)
{
hpx::this_thread::sleep_for(boost::posix_time::milliseconds(1000));
}
webserver.stop();
}
if(verbose) hpx::cout << "Program finished." << hpx::endl;
// End the program
return hpx::finalize();
}
//////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
// Configure application-specific options
boost::program_options::options_description cmdline(
"Usage: " HPX_APPLICATION_STRING " [options]");
cmdline.add_options()
( "num-parallel-kernels"
, boost::program_options::value<std::size_t>()->default_value(3)
, "the number of parallel kernel invocations per gpu") ;
cmdline.add_options()
( "v"
, "verbose output") ;
return hpx::init(cmdline, argc, argv);
}
| 29.8 | 109 | 0.54443 | [
"vector"
] |
24d8cafd2df39e8f066606c32d196d7f948b480f | 13,276 | cpp | C++ | source/SceneStateStackStagingArea.cpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | source/SceneStateStackStagingArea.cpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | source/SceneStateStackStagingArea.cpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#include <GTGE/SceneStateStackStagingArea.hpp>
#include <GTGE/SceneStateStackBranch.hpp>
#include <GTGE/Scene.hpp>
#include <GTGE/GTEngine.hpp>
namespace GT
{
SceneStateStackStagingArea::SceneStateStackStagingArea(SceneStateStackBranch &branchIn)
: branch(branchIn), inserts(), deletes(), updates(), hierarchy()
{
}
SceneStateStackStagingArea::~SceneStateStackStagingArea()
{
this->Clear();
}
Scene & SceneStateStackStagingArea::GetScene()
{
return this->branch.GetScene();
}
const Scene & SceneStateStackStagingArea::GetScene() const
{
return this->branch.GetScene();
}
void SceneStateStackStagingArea::StageInsert(uint64_t sceneNodeID)
{
// If a delete command with the scene node is already staged, what we actually want to do is remove the delete command and
// turn the insert into an update.
auto iDelete = this->deletes.Find(sceneNodeID);
if (iDelete != nullptr)
{
// Remove the delete command.
delete iDelete->value;
this->deletes.RemoveByIndex(iDelete->index);
// Convert to an update command.
this->inserts.RemoveFirstOccuranceOf(sceneNodeID);
this->StageUpdate(sceneNodeID);
}
else
{
// If the scene node is in the updates list we need to remove it.
this->updates.RemoveFirstOccuranceOf(sceneNodeID);
if (!this->inserts.Exists(sceneNodeID))
{
this->inserts.PushBack(sceneNodeID);
this->AddToHierarchy(sceneNodeID);
}
}
}
void SceneStateStackStagingArea::StageDelete(uint64_t sceneNodeID)
{
// If an insert command with the scene node is already staged, all we want to do is remove it from the inserts and just
// ignore everything.
size_t index;
if (this->inserts.FindFirstIndexOf(sceneNodeID, index))
{
this->inserts.Remove(index);
this->RemoveFromHierarchy(sceneNodeID);
}
else
{
// If the scene node is in the updates list we need to remove it.
this->updates.RemoveFirstOccuranceOf(sceneNodeID);
if (!this->deletes.Exists(sceneNodeID))
{
auto sceneNode = this->GetScene().GetSceneNodeByID(sceneNodeID);
assert(sceneNode != nullptr);
{
auto sceneNodeSerializer = new BasicSerializer;
sceneNode->Serialize(*sceneNodeSerializer, this->branch.GetStateStack().GetSceneNodeSerializationFlags());
this->deletes.Add(sceneNodeID, sceneNodeSerializer);
this->AddToHierarchy(sceneNodeID);
}
}
}
}
void SceneStateStackStagingArea::StageUpdate(uint64_t sceneNodeID)
{
// We ignore update commands if an insert or delete command is already present.
if (!this->inserts.Exists(sceneNodeID) &&
!this->deletes.Exists(sceneNodeID) &&
!this->updates.Exists(sceneNodeID))
{
this->updates.PushBack(sceneNodeID);
}
// Always make sure the hierarchy is updated.
this->AddToHierarchy(sceneNodeID);
}
void SceneStateStackStagingArea::Clear()
{
for (size_t i = 0; i < this->deletes.count; ++i)
{
delete this->deletes.buffer[i]->value;
}
this->inserts.Clear();
this->deletes.Clear();
this->updates.Clear();
this->hierarchy.Clear();
}
void SceneStateStackStagingArea::GetRevertCommands(SceneStateStackRestoreCommands &commands)
{
// TODO: Investigate why I'm not using commands.AddInsert(), .AddDelete() and .AddUpdate().
// We need to do opposites. Inserts become deletes, deletes become inserts and updates are back traced until we find the most recent one.
// Inserts
for (size_t i = 0; i < this->inserts.count; ++i)
{
auto sceneNodeID = this->inserts[i];
commands.deletes.Add(sceneNodeID, nullptr);
}
// Deletes
for (size_t i = 0; i < this->deletes.count; ++i)
{
auto sceneNodeID = this->deletes.buffer[i]->key;
auto sceneNodeSerializer = this->deletes.buffer[i]->value;
commands.inserts.Add(sceneNodeID, sceneNodeSerializer);
}
// Updates
for (size_t i = 0; i < this->updates.count; ++i)
{
auto sceneNodeID = this->updates[i];
auto sceneNodeSerializer = this->branch.FindMostRecentSerializer(sceneNodeID, this->branch.GetCurrentFrameIndex());
commands.updates.Add(sceneNodeID, sceneNodeSerializer);
}
// Hierarchy
for (size_t i = 0; i < this->hierarchy.count; ++i)
{
auto sceneNodeID = this->hierarchy.buffer[i]->key;
auto parentSceneNodeID = this->branch.FindMostRecentParentSceneNodeID(sceneNodeID, this->branch.GetCurrentFrameIndex());
if (!commands.deletes.Exists(sceneNodeID))
{
commands.hierarchy.Add(sceneNodeID, parentSceneNodeID);
}
}
}
void SceneStateStackStagingArea::GetRestoreCommands(SceneStateStackRestoreCommands &commands)
{
// Inserts
for (size_t i = 0; i < this->inserts.count; ++i)
{
auto sceneNodeID = this->inserts.buffer[i];
auto parentSceneNodeID = this->GetParentSceneNodeIDFromHierarchy(sceneNodeID);
commands.AddInsert(sceneNodeID, parentSceneNodeID, this->GetScene());
}
// Deletes
for (size_t i = 0; i < this->deletes.count; ++i)
{
auto sceneNodeID = this->deletes.buffer[i]->key;
auto parentSceneNodeID = this->GetParentSceneNodeIDFromHierarchy(sceneNodeID);
commands.AddDelete(sceneNodeID, parentSceneNodeID, nullptr, nullptr);
}
// Updates
for (size_t i = 0; i < this->updates.count; ++i)
{
auto sceneNodeID = this->updates.buffer[i];
auto parentSceneNodeID = this->GetParentSceneNodeIDFromHierarchy(sceneNodeID);
commands.AddUpdate(sceneNodeID, parentSceneNodeID, this->GetScene());
}
}
/////////////////////////////////////////////////
// Serialization/Deserialization
void SceneStateStackStagingArea::Serialize(Serializer &serializer) const
{
// We need to use an intermediary serializer to get an accurate size.
BasicSerializer intermediarySerializer;
// Inserts.
intermediarySerializer.Write(static_cast<uint32_t>(this->inserts.count));
for (size_t i = 0; i < this->inserts.count; ++i)
{
intermediarySerializer.Write(this->inserts[i]);
}
// Deletes.
intermediarySerializer.Write(static_cast<uint32_t>(this->deletes.count));
for (size_t i = 0; i < this->deletes.count; ++i)
{
auto sceneNodeID = this->deletes.buffer[i]->key;
auto sceneNodeSerializer = this->deletes.buffer[i]->value;
intermediarySerializer.Write(sceneNodeID);
intermediarySerializer.Write(static_cast<uint32_t>(sceneNodeSerializer->GetBufferSizeInBytes()));
intermediarySerializer.Write(sceneNodeSerializer->GetBuffer(), sceneNodeSerializer->GetBufferSizeInBytes());
}
// Updates.
intermediarySerializer.Write(static_cast<uint32_t>(this->updates.count));
for (size_t i = 0; i < this->updates.count; ++i)
{
intermediarySerializer.Write(this->updates[i]);
}
// Hierarchy.
intermediarySerializer.Write(static_cast<uint32_t>(this->hierarchy.count));
for (size_t i = 0; i < this->hierarchy.count; ++i)
{
intermediarySerializer.Write(this->hierarchy.buffer[i]->key);
intermediarySerializer.Write(this->hierarchy.buffer[i]->value);
}
Serialization::ChunkHeader header;
header.id = Serialization::ChunkID_SceneStateStackStagingArea;
header.version = 1;
header.sizeInBytes = intermediarySerializer.GetBufferSizeInBytes();
serializer.Write(header);
serializer.Write(intermediarySerializer.GetBuffer(), intermediarySerializer.GetBufferSizeInBytes());
}
void SceneStateStackStagingArea::Deserialize(Deserializer &deserializer)
{
// We should clear the staging area just in case.
this->Clear();
Serialization::ChunkHeader header;
deserializer.Read(header);
{
assert(header.id == Serialization::ChunkID_SceneStateStackStagingArea);
{
switch (header.version)
{
case 1:
{
// Inserts.
uint32_t insertsCount;
deserializer.Read(insertsCount);
for (uint32_t i = 0; i < insertsCount; ++i)
{
uint64_t sceneNodeID;
deserializer.Read(sceneNodeID);
this->inserts.PushBack(sceneNodeID);
}
// Deletes.
uint32_t deletesCount;
deserializer.Read(deletesCount);
for (uint32_t i = 0; i < deletesCount; ++i)
{
uint64_t sceneNodeID;
deserializer.Read(sceneNodeID);
// The next chunk of data is the serialized data of the scene node. What we do here is ready the data into a temp buffer, and then
// write that to a new BasicSerializer object.
uint32_t serializerSizeInBytes;
deserializer.Read(serializerSizeInBytes);
void* serializerData = malloc(serializerSizeInBytes);
deserializer.Read(serializerData, serializerSizeInBytes);
auto sceneNodeSerializer = new BasicSerializer;
sceneNodeSerializer->Write(serializerData, serializerSizeInBytes);
this->deletes.Add(sceneNodeID, sceneNodeSerializer);
free(serializerData);
}
// Updates.
uint32_t updatesCount;
deserializer.Read(updatesCount);
for (uint32_t i = 0; i < updatesCount; ++i)
{
uint64_t sceneNodeID;
deserializer.Read(sceneNodeID);
this->updates.PushBack(sceneNodeID);
}
// Hierarchy.
uint32_t hierarchyCount;
deserializer.Read(hierarchyCount);
for (uint32_t i = 0; i < hierarchyCount; ++i)
{
uint64_t sceneNodeID;
deserializer.Read(sceneNodeID);
uint64_t parentSceneNodeID;
deserializer.Read(parentSceneNodeID);
this->hierarchy.Add(sceneNodeID, parentSceneNodeID);
}
break;
}
default:
{
g_Context->Logf("Error deserializing SceneStateStackStagingArea. The main chunk is an unsupported version (%d).", header.version);
deserializer.Seek(header.sizeInBytes);
break;
}
}
}
}
}
////////////////////////////////////////
// Private
void SceneStateStackStagingArea::AddToHierarchy(uint64_t sceneNodeID)
{
auto &scene = this->GetScene();
auto sceneNode = scene.GetSceneNodeByID(sceneNodeID);
assert(sceneNode != nullptr);
{
auto parentSceneNode = sceneNode->GetParent();
if (parentSceneNode != nullptr)
{
this->hierarchy.Add(sceneNodeID, parentSceneNode->GetID());
}
else
{
this->hierarchy.Add(sceneNodeID, 0); // 0 = no parent.
}
}
}
void SceneStateStackStagingArea::RemoveFromHierarchy(uint64_t sceneNodeID)
{
this->hierarchy.RemoveByKey(sceneNodeID);
}
uint64_t SceneStateStackStagingArea::GetParentSceneNodeIDFromHierarchy(uint64_t childSceneNodeID) const
{
auto iHierarchy = this->hierarchy.Find(childSceneNodeID);
if (iHierarchy != nullptr)
{
return iHierarchy->value;
}
return 0;
}
}
| 33.356784 | 158 | 0.555363 | [
"object"
] |
24daa91b3d7d8e9c0fdb51d990f1d13653b90b06 | 24,934 | cpp | C++ | src/polyphase/haplothreader.cpp | xiaoluo91/whatshap | 9882248c722b1020321fea6e9491c1cc5b75354b | [
"MIT"
] | 174 | 2018-07-04T06:59:02.000Z | 2022-03-29T03:30:18.000Z | src/polyphase/haplothreader.cpp | xiaoluo91/whatshap | 9882248c722b1020321fea6e9491c1cc5b75354b | [
"MIT"
] | 132 | 2018-07-21T01:16:15.000Z | 2022-03-30T14:25:45.000Z | src/polyphase/haplothreader.cpp | xiaoluo91/whatshap | 9882248c722b1020321fea6e9491c1cc5b75354b | [
"MIT"
] | 21 | 2018-07-05T14:37:10.000Z | 2022-03-10T08:02:37.000Z | #include "haplothreader.h"
#include <limits>
#include <algorithm>
#include <unordered_set>
#include <random>
constexpr uint64_t ClusterTuple::TUPLE_MASKS[];
const ClusterTuple ClusterTuple::INVALID_TUPLE = ClusterTuple((TupleCode)-1);
HaploThreader::HaploThreader (uint32_t ploidy, double switchCost, double affineSwitchCost, bool symmetryOptimization, uint32_t rowLimit) :
ploidy(ploidy),
switchCost(switchCost),
affineSwitchCost(affineSwitchCost),
symmetryOptimization(symmetryOptimization),
rowLimit(rowLimit)
{
}
std::vector<std::vector<GlobalClusterId>> HaploThreader::computePaths (const std::vector<Position>& blockStarts,
const std::vector<std::vector<GlobalClusterId>>& covMap,
const std::vector<std::vector<double>>& coverage,
const std::vector<std::vector<uint32_t>>& consensus,
const std::vector<std::unordered_map<uint32_t, uint32_t>>& genotypes
) const {
Position numVars = covMap.size();
std::vector<std::vector<GlobalClusterId>> path;
for (uint32_t i = 0; i < blockStarts.size(); i++) {
Position start = blockStarts[i];
Position end = i == blockStarts.size()-1 ? numVars : blockStarts[i+1];
if (end > start) {
std::vector<std::vector<GlobalClusterId>> section = computePaths(blockStarts[i], end, covMap, coverage, consensus, genotypes, numVars);
for (auto tuple : section) {
path.push_back(tuple);
}
}
}
return path;
}
std::vector<std::vector<GlobalClusterId>> HaploThreader::computePaths (Position start, Position end,
const std::vector<std::vector<GlobalClusterId>>& covMap,
const std::vector<std::vector<double>>& coverage,
const std::vector<std::vector<uint32_t>>& consensus,
const std::vector<std::unordered_map<uint32_t, uint32_t>>& genotypes,
Position displayedEnd
) const {
// the actual DP table with sparse columns
std::vector<std::unordered_map<ClusterTuple, ClusterEntry>> m;
// data structure to store the final result
std::vector<std::vector<GlobalClusterId>> path;
// initialize first column
if (displayedEnd == 0)
displayedEnd = end;
Position firstUnthreadedPosition = start;
/*
* Compute the genotype conform tuples for the first column and quit if this set is empty.
* Note that tuples in general only contain local cluster ids, which must be mapped by covMap[column_id]
* in order to retrieve global cluster ids. The local ids make for a compact representation, but the global
* ids are necessary to compare tuples from different column.
*/
std::vector<ClusterTuple> confTuples = computeGenotypeConformTuples(covMap[start], consensus[start], genotypes[start]);
if (confTuples.size() == 0) {
std::cout<<"First variant has no clusters!"<<std::endl;
return path;
}
// auxiliary vector to store the optimal permutations of the conform tuples
std::vector<ClusterTuple> permedTuples;
// auxiliary vector to store a vector for each tuple of a column. This vector contains the global cluster ids and is sorted
std::unordered_map<ClusterTuple, std::vector<GlobalClusterId>> sortedGlobalTuples;
// allocated space to store the current column, before it is stored in the DP table
std::unordered_map<ClusterTuple, ClusterEntry> column;
// allocated space to store the optima for the current column
Score minimumInColumn = std::numeric_limits<Score>::infinity();
ClusterTuple minimumTupleInColumn = ClusterTuple::INVALID_TUPLE;
ClusterTuple minimumPredTupleInColumn = ClusterTuple::INVALID_TUPLE;
// fill first column by only using the coverage cost of each candidate tuple
for (ClusterTuple t : confTuples) {
column[t] = ClusterEntry(getCoverageCost(t, coverage[start]), ClusterTuple::INVALID_TUPLE);
firstUnthreadedPosition = start + 1;
if (column[t].score < minimumInColumn) {
minimumInColumn = column[t].score;
minimumTupleInColumn = t;
}
}
// cut down rows if parameter is set
if (rowLimit > 0 && column.size() >= rowLimit) {
std::vector<std::pair<ClusterTuple, ClusterEntry>> tuplePairs(column.begin(), column.end());
std::sort(tuplePairs.begin(), tuplePairs.end(), [this] (const std::pair<ClusterTuple, ClusterEntry>& a, const std::pair<ClusterTuple, ClusterEntry>& b) { return a.second.score < b.second.score; });
for (uint32_t i = rowLimit; i < tuplePairs.size(); i++) {
column.erase(tuplePairs[i].first);
}
}
// store first column in DP table
m.push_back(std::unordered_map<ClusterTuple, ClusterEntry>(column.begin(), column.end()));
// precompute the sorted vector with global cluster ids for every entry in first column
for (std::pair<ClusterTuple, ClusterEntry> predEntry : m[0]) {
std::vector<GlobalClusterId> tupleGlobal = predEntry.first.asVector(ploidy, covMap[0]);
std::sort(tupleGlobal.begin(), tupleGlobal.end());
sortedGlobalTuples[predEntry.first] = tupleGlobal;
}
/*
* The basic idea of this algorithm is, that for every position we generate candidate tuples, which represent
* the multiset of clusters, through which the haplotypes are threaded at this exact position. Therefore, for
* every candidate we have to compute the coverage costs and the best predecessor tuple from the last column.
* The best predecessor is the tuple, which minimizes the sum over its own total cost, plus the switch costs
* to the candidate of the current column.
*
* There is heavy symmetry optimization included in this algorithm. First, for a completely computed column
* there is no point in having two tuples t1 and t2, which are permutations of each other. Since we consider
* all genotype conform tuples in the next column anyways, we only need to store the better of the two t1 and
* t2. This elimination of permutations is mainly done by the candidate generation and by the switch cost
* functions:
*
* 1. The candidate generator avoids permutations by construction.
* 2. The advanced switch cost function is able to compute the minimal switch costs between a tuple t1 and all
* permutations of a tuple t2. If one candidate for the current column is processed, all of its
* permutations are actually processed as well. We only keep the permutation of t2 with the lowest switch
* cost, since all other permutations have equal coverage costs and can thus be discarded.
*
* After a column is computed, it is optionally pruned by removing non-profitable tuples. Let t1 and t2 be
* tuples in the current column. Then t2 is non-profitable if it holds that
*
* total_cost(t2) >= total_cost(t1) + switch_cost(t1, t2)
*
*/
for (Position pos = start + 1; pos < end; pos++) {
// reset variables
confTuples.clear();
permedTuples.clear();
column.clear();
Score minimum = std::numeric_limits<Score>::infinity();
ClusterTuple minimumPred = ClusterTuple::INVALID_TUPLE;
bool minExists = false;
minimumInColumn = std::numeric_limits<Score>::infinity();
minimumTupleInColumn = ClusterTuple::INVALID_TUPLE;
minimumPredTupleInColumn = ClusterTuple::INVALID_TUPLE;
// compute genotype conform tuples
confTuples = computeGenotypeConformTuples(covMap[pos], consensus[pos], genotypes[pos]);
// iterate over generated tuples
for (ClusterTuple rowTuple : confTuples) {
// variables to store best score and backtracking direction
minimum = std::numeric_limits<Score>::infinity();
minimumPred = ClusterTuple::INVALID_TUPLE;
// auxiliary data, is precomputed once here
std::vector<GlobalClusterId> rowTupleGlobal = rowTuple.asVector(ploidy, covMap[pos]);
std::sort(rowTupleGlobal.begin(), rowTupleGlobal.end());
// this is the tuple into which the rowTuple will be transformed when the best permutation is found
ClusterTuple bestPerm;
// compare each new tuple with every tuple from previous column
for (std::pair<ClusterTuple, ClusterEntry> predEntry : m[pos-1-start]) {
// retrieve precomputed sorted vector over global ids
std::vector<GlobalClusterId> prevTupleGlobal = sortedGlobalTuples[predEntry.first];
// compute optimal switch cost
Score s = predEntry.second.score + getSwitchCostAllPerms(prevTupleGlobal, rowTupleGlobal);
if (s < minimum) {
minExists = true;
minimum = s;
// minDissim = d;
minimumPred = predEntry.first;
}
}
if (minExists) {
// in addition to best score over all predecessors, we need the best permutation of rowTuple to achieve this
std::vector<GlobalClusterId> prevTuple = sortedGlobalTuples[minimumPred];
std::vector<uint32_t> residualPosPrev; // positions in previous tuple, which could not be matched to position in current tuple
std::vector<uint32_t> residualPosCur; // positions in current tuple, which could not be matched to position in previous tuple
getSwitchCostAllPerms(prevTuple, rowTupleGlobal, residualPosPrev, residualPosCur);
if (residualPosPrev.size() != residualPosCur.size()) {
std::cout<<"Residual sizes unequal"<<std::endl;
for (auto i = prevTuple.begin(); i != prevTuple.end(); ++i)
std::cout << *i << ' ';
std::cout<<std::endl;
for (auto i = rowTupleGlobal.begin(); i != rowTupleGlobal.end(); ++i)
std::cout << *i << ' ';
std::cout<<std::endl;
}
std::vector<GlobalClusterId> bestPermGlobal(minimumPred.asVector(ploidy, covMap[pos-1]));
for (uint32_t i = 0; i < residualPosCur.size(); i++) {
GlobalClusterId residueCur = rowTupleGlobal[residualPosCur[i]];
GlobalClusterId residuePrev = prevTuple[residualPosPrev[i]];
for (uint32_t j = 0; j < ploidy; j++) {
if (bestPermGlobal[j] == residuePrev) {
bestPermGlobal[j] = residueCur;
break;
}
}
}
std::unordered_map<GlobalClusterId, LocalClusterId> globalToLocal;
for (uint32_t i = 0; i < covMap[pos].size(); i++)
globalToLocal[covMap[pos][i]] = i;
for (uint32_t i = 0; i < ploidy; i++)
bestPerm.set(globalToLocal[bestPermGlobal[i]], i);
} else {
bestPerm = rowTuple;
}
Score coverageCost = getCoverageCost(rowTuple, coverage[pos]);
if (coverageCost != getCoverageCost(bestPerm, coverage[pos])) {
std::cout<<"Row tuples have unequal coverage cost"<<std::endl;
std::cout<<rowTuple.asString(ploidy, covMap[pos])<<std::endl;
std::cout<<bestPerm.asString(ploidy, covMap[pos])<<std::endl;
}
// report best recursion
if (minExists) {
column[bestPerm] = ClusterEntry(minimum + coverageCost, minimumPred);
} else {
column[bestPerm] = ClusterEntry(coverageCost, ClusterTuple::INVALID_TUPLE);
}
firstUnthreadedPosition = pos+1;
if (column[bestPerm].score < minimumInColumn) {
minimumInColumn = column[bestPerm].score;
minimumTupleInColumn = bestPerm;
minimumPredTupleInColumn = minimumPred;
}
permedTuples.push_back(bestPerm);
}
// precompute the sorted vectors with global cluster ids for this column (will be reused in next column)
sortedGlobalTuples.clear();
for (ClusterTuple t : permedTuples) {
std::vector<GlobalClusterId> tupleGlobal = t.asVector(ploidy, covMap[pos]);
std::sort(tupleGlobal.begin(), tupleGlobal.end());
sortedGlobalTuples[t] = tupleGlobal;
}
uint32_t allRows = column.size();
if (symmetryOptimization) {
// remove non-profitable entries
std::vector<ClusterTuple> profitableTuples;
std::vector<ClusterTuple> pivotTuples;
profitableTuples.push_back(minimumTupleInColumn);
pivotTuples.push_back(minimumTupleInColumn);
uint32_t rounds = 2;
for (uint32_t i = 0; i < rounds; i++) {
for (ClusterTuple t : permedTuples) {
bool profitable = true;
bool pivot = true;
for (ClusterTuple p : pivotTuples) {
if (p == t)
continue;
Score s = getSwitchCostAllPerms(sortedGlobalTuples[p], sortedGlobalTuples[t]);
if (column[t].score >= column[p].score + s) {
profitable = false;
pivot = false;
break;
} else if (s < (double)(rounds-i) * switchCost) {
pivot = false;
}
}
if (profitable) {
profitableTuples.push_back(t);
if (pivot && pivotTuples.size() < ploidy*ploidy) {
pivotTuples.push_back(t);
}
} else {
column.erase(t);
}
}
}
}
// cut down rows if parameter is set
if (rowLimit > 0 && column.size() >= rowLimit) {
std::vector<std::pair<ClusterTuple, ClusterEntry>> tuplePairs(column.begin(), column.end());
std::sort(tuplePairs.begin(), tuplePairs.end(), [this] (const std::pair<ClusterTuple, ClusterEntry>& a, const std::pair<ClusterTuple, ClusterEntry>& b) { return a.second.score < b.second.score; });
for (uint32_t i = rowLimit; i < tuplePairs.size(); i++) {
column.erase(tuplePairs[i].first);
}
}
//std::cout<<"Column "<<pos<<": "<<minimumInColumn<<"\t ("<<column.size()<<" rows, before "<<allRows<<")"<<std::endl;
// write column into dp table(s)
m.push_back(std::unordered_map<ClusterTuple, ClusterEntry>(column.begin(), column.end()));
}
// discard auxiliary data
sortedGlobalTuples.clear();
// backtracking start
ClusterTuple currentRow = ClusterTuple::INVALID_TUPLE;
Score minimum = std::numeric_limits<Score>::infinity();
for (std::pair<ClusterTuple, ClusterEntry> entry : m[firstUnthreadedPosition-1-start]) {
if (entry.second.score < minimum) {
minimum = entry.second.score;
currentRow = entry.first;
}
}
if (currentRow == ClusterTuple::INVALID_TUPLE) {
std::cout<<"No minimum in last threaded column!"<<std::endl;
} else {
if (currentRow.asVector(ploidy, covMap[firstUnthreadedPosition-1]).size() == 0)
std::cout<<"Problem occured at position "<<(firstUnthreadedPosition-1)<<" in row "<<currentRow.asString(ploidy, covMap[firstUnthreadedPosition-1])<<std::endl;
path.push_back(currentRow.asVector(ploidy, covMap[firstUnthreadedPosition-1]));
}
// backtracking iteration
for (Position pos = firstUnthreadedPosition-1; pos > start; pos--) {
currentRow = m[pos-start][currentRow].pred;
if (currentRow.asVector(ploidy, covMap[pos-1]).size() == 0) {
std::cout<<"Problem occured at position "<<(pos-1)<<" in row "<<currentRow.asString(ploidy, covMap[pos-1])<<std::endl;
std::vector<GlobalClusterId> fallback;
for (uint32_t i = 0; i < ploidy; i++)
fallback.push_back(0);
path.push_back(fallback);
} else {
path.push_back(currentRow.asVector(ploidy, covMap[pos-1]));
}
}
// reverse as we constructed it back to front
std::reverse(path.begin(), path.end());
return path;
}
Score HaploThreader::getCoverageCost(ClusterTuple tuple, const std::vector<double>& coverage) const {
// tuple contains local cluster ids, which have to be translated with covMap to get the global ids
Score cost = 0.0;
for (uint32_t i = 0; i < ploidy; i++) {
double cov = coverage[tuple.get(i)];
if (cov == 0) {
return std::numeric_limits<double>::infinity();
} else {
uint32_t expCount = std::round(cov*(double)ploidy);
uint32_t realCount = tuple.count(tuple.get(i), ploidy);
if (realCount != expCount) {
cost += 1.0;
}
}
}
return cost;
}
Score HaploThreader::getSwitchCostAllPerms(const std::vector<GlobalClusterId>& prevTuple, const std::vector<GlobalClusterId>& curTuple) const {
uint32_t pIdx = 0;
uint32_t cIdx = 0;
uint32_t switches = 0;
// compare zig-zag-wise over sorted tuples
while ((pIdx < ploidy) & (cIdx < ploidy)) {
if (prevTuple[pIdx] == curTuple[cIdx]) {
pIdx++; cIdx++;
} else if (prevTuple[pIdx] < curTuple[cIdx]) {
switches++;
pIdx++;
} else {
cIdx++;
}
}
switches += (ploidy - pIdx);
return switchCost*switches + affineSwitchCost*(switches > 0);
}
Score HaploThreader::getSwitchCostAllPerms(const std::vector<GlobalClusterId>& prevTuple, const std::vector<GlobalClusterId>& curTuple,
std::vector<uint32_t>& residualPosPrev, std::vector<uint32_t>& residualPosCur) const {
uint32_t pIdx = 0;
uint32_t cIdx = 0;
// compare zig-zag-wise over sorted tuples
while ((pIdx < ploidy) & (cIdx < ploidy)) {
if (prevTuple[pIdx] == curTuple[cIdx]) {
pIdx++; cIdx++;
} else if (prevTuple[pIdx] < curTuple[cIdx]) {
residualPosPrev.push_back(pIdx);
pIdx++;
} else {
residualPosCur.push_back(cIdx);
cIdx++;
}
}
for (uint32_t i = pIdx; i < ploidy; i++)
residualPosPrev.push_back(i);
for (uint32_t j = cIdx; j < ploidy; j++)
residualPosCur.push_back(j);
return switchCost*residualPosPrev.size() + affineSwitchCost*(residualPosPrev.size() > 0);
}
std::vector<ClusterTuple> HaploThreader::computeGenotypeConformTuples (const std::vector<GlobalClusterId>& clusters,
const std::vector<uint32_t>& consensus,
const std::unordered_map<uint32_t, uint32_t>& genotype) const {
std::vector<ClusterTuple> perfect = getGenotypeConformTuples (clusters, consensus, genotype);
if (perfect.size() > 0) {
return perfect;
} else {
const std::vector<uint32_t> consensusDummy(clusters.size(), 0);
const std::unordered_map<uint32_t, uint32_t> genotypeDummy({ {0, ploidy} });
std::vector<ClusterTuple> noMatch = getGenotypeConformTuples (clusters, consensusDummy, genotypeDummy);
return noMatch;
}
}
std::vector<ClusterTuple> HaploThreader::getGenotypeConformTuples (const std::vector<GlobalClusterId>& clusters, const std::vector<uint32_t>& consensus,
const std::unordered_map<uint32_t, uint32_t>& genotype) const {
std::vector<ClusterTuple> conformTuples;
// convert genotype map to vector
uint32_t maxAllele = 0;
for (std::pair<uint32_t, uint32_t> entry : genotype) {
maxAllele = std::max(maxAllele, entry.first+1);
}
std::vector<uint32_t> genotypeVec(maxAllele, 0);
for (std::pair<uint32_t, uint32_t> entry : genotype) {
genotypeVec[entry.first] = entry.second;
}
// split clusters by consensus-allele
std::vector<std::vector<LocalClusterId>> clusterGroups(maxAllele, std::vector<LocalClusterId>(0));
for (LocalClusterId i = 0; i < clusters.size(); i++) {
clusterGroups[consensus[i]].push_back(i);
}
// if genotype not reachable: return empty vector
for (uint32_t allele = 0; allele < maxAllele; allele++) {
if (genotypeVec[allele] > 0 && clusterGroups[allele].size() == 0)
return conformTuples;
}
/*
* For each allele, store a vector, which contains all combinations (as vectors) from respective local cluster ids
*/
std::vector<std::vector<std::vector<LocalClusterId>>> alleleWiseCombs;
for (uint32_t allele = 0; allele < maxAllele; allele++) {
// create vector of combinations for current allele
std::vector<std::vector<LocalClusterId>> combsOfAllele;
uint32_t numElem = genotypeVec[allele];
uint32_t maxElem = clusterGroups[allele].size();
if (numElem > 0) {
std::vector<uint32_t> v(numElem, 0);
/*
* store vector, until maxElem-1 is in the last field, because then we must just
* have stored the vector [maxElem-1, maxElem-1, ..., maxElem-1] and we are finished.
*/
while (v[numElem-1] < maxElem) {
// translate to local cluster ids and store in combsOfAllele
std::vector<uint32_t> c(numElem, 0);
for (uint32_t i = 0; i < numElem; i++)
c[i] = clusterGroups[allele][v[i]];
combsOfAllele.push_back(c);
// increment like a counter
v[0]++;
// if element i-1 overflowed, increase element i by 1 (which then might also overflow and so on)
for (uint32_t i = 1; i < numElem; i++)
if (v[i-1] >= maxElem)
v[i]++;
// any element i-1 which overflowed will be set to its minimum, i.e. the value of element i
for (uint32_t i = numElem-1; i > 0; i--)
if (v[i-1] >= maxElem)
v[i-1] = v[i];
}
}
alleleWiseCombs.push_back(combsOfAllele); // added vector may be empty
}
/*
* Next step is to generate all combinations of size ploidy, so all combinations from
* allele 0 times all combinations from allele 1 times ...
*/
/*
* This vector contains one entry per allele. indices[i] = j means, that we choose the j-th combination
* from allele i to construct the next element of our result
*/
std::vector<uint32_t> indices(maxAllele, 0);
while (indices[maxAllele-1] < alleleWiseCombs[maxAllele-1].size()) {
/*
* As long as our last index is still valid, we can copy the current combination to result
*/
std::vector<uint32_t> x;
for (uint32_t allele = 0; allele < maxAllele; allele++) {
if (alleleWiseCombs[allele].size() == 0)
continue;
// append the indices[allele]-th combination from alleleWiseCombs[allele] to x
for (uint32_t c : alleleWiseCombs[allele][indices[allele]])
x.push_back(c);
}
// append to solution
conformTuples.push_back(ClusterTuple(x));
// increment like a counter
indices[0]++;
/*
* If element i-1 overflowed, increase element i by 1 (which then might also overflow and so on)
* and set element i-1 to zero
*/
for (uint32_t i = 1; i < maxAllele; i++) {
// second condition indices[i-1] > 0 is necessary, because there might be alleles with no combinations
if (indices[i-1] >= alleleWiseCombs[i-1].size() && indices[i-1] > 0) {
indices[i]++;
indices[i-1] = 0;
}
}
}
return conformTuples;
}
| 46.605607 | 209 | 0.589677 | [
"vector"
] |
24e3d544a8cb6b8be311df01d2c0698db979e770 | 5,827 | cpp | C++ | Base/PLRenderer/src/Effect/EffectPassLayer.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLRenderer/src/Effect/EffectPassLayer.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Base/PLRenderer/src/Effect/EffectPassLayer.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: EffectPassLayer.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "PLRenderer/RendererContext.h"
#include "PLRenderer/Renderer/Program.h"
#include "PLRenderer/Renderer/ProgramUniform.h"
#include "PLRenderer/Texture/TextureManager.h"
#include "PLRenderer/Texture/TextureHandler.h"
#include "PLRenderer/Material/Parameter.h"
#include "PLRenderer/Material/ParameterManager.h"
#include "PLRenderer/Effect/Effect.h"
#include "PLRenderer/Effect/EffectPass.h"
#include "PLRenderer/Effect/EffectManager.h"
#include "PLRenderer/Effect/EffectTechnique.h"
#include "PLRenderer/Effect/EffectPassLayer.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
using namespace PLMath;
namespace PLRenderer {
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Makes the texture buffer of the texture handlers texture to the current renderer texture buffer
*/
bool EffectPassLayer::Bind(uint32 nStage, ParameterManager *pParameterManager) const
{
// Get effect
Effect &cEffect = m_pFXPass->GetTechnique().GetEffect();
// Get renderer
Renderer &cRenderer = cEffect.GetEffectManager().GetRendererContext().GetRenderer();
// Bind texture
if (!pParameterManager || !BindTexture(pParameterManager->GetParameter(m_sTexture), nStage))
BindTexture(cEffect.GetParameterManager().GetParameter(m_sTexture), nStage);
// Set sampler states
for (uint32 i=0; i<Sampler::Number; i++)
cRenderer.SetSamplerState(nStage, static_cast<Sampler::Enum>(i), m_cSamplerStates.Get(static_cast<Sampler::Enum>(i)));
// Fixed functions
FixedFunctions *pFixedFunctions = cRenderer.GetFixedFunctions();
if (pFixedFunctions) {
// Set texture stage states
for (uint32 i=0; i<FixedFunctions::TextureStage::Number; i++)
pFixedFunctions->SetTextureStageState(nStage, static_cast<FixedFunctions::TextureStage::Enum>(i), m_cFixedFunctionsTextureStageStates.Get(static_cast<FixedFunctions::TextureStage::Enum>(i)));
}
// Done
return true;
}
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Binds a texture
*/
bool EffectPassLayer::BindTexture(const Parameter *pParameter, uint32 nStage) const
{
// Check parameter
if (pParameter && pParameter->GetType() == Parameters::TextureBuffer) {
// Get texture
const TextureHandler *pTextureHandler = pParameter->GetValueTextureHandler();
if (pTextureHandler) {
const Texture *pTexture = pTextureHandler->GetTexture();
bool bResult = true; // No error by default
if (!pTexture) {
// Use the default texture to avoid ugly graphics...
pTexture = m_pFXPass->GetTechnique().GetEffect().GetEffectManager().GetRendererContext().GetTextureManager().GetStandard();
if (!pTexture)
return false; // Error! :(
// Error!
bResult = false;
}
TextureBuffer *pTextureBuffer = pTexture->GetTextureBuffer();
if (pTextureBuffer) {
{ // Set the GPU program uniform
Program *pProgram = m_pFXPass->GetProgram();
if (pProgram) {
ProgramUniform *pProgramUniform = pProgram->GetUniform(pParameter->GetName());
if (pProgramUniform && pProgramUniform->Set(pTextureBuffer) > -1) {
// Done
return bResult;
}
}
}
if (bResult)
pTextureHandler->Bind(nStage);
else {
// Bind the fallback texture
pTexture->Bind(nStage);
// Fixed functions
FixedFunctions *pFixedFunctions = pTextureBuffer->GetRenderer().GetFixedFunctions();
if (pFixedFunctions) {
// Set identity texture matrix
pFixedFunctions->SetTransformState(static_cast<FixedFunctions::Transform::Enum>(static_cast<uint32>(FixedFunctions::Transform::Texture0) + nStage), Matrix4x4::Identity);
}
}
// Done
return bResult;
}
}
}
// Error!
return false;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLRenderer
| 38.335526 | 194 | 0.611292 | [
"transform"
] |
24e3fc894ca8c61847e19ef52a2eed8f2ea1f315 | 19,283 | cpp | C++ | test/Library/Astrodynamics/Trajectory.test.cpp | cowlicks/library-astrodynamics | aec161a1e5a1294820a90e1a74633b5a71d59a33 | [
"Apache-2.0"
] | null | null | null | test/Library/Astrodynamics/Trajectory.test.cpp | cowlicks/library-astrodynamics | aec161a1e5a1294820a90e1a74633b5a71d59a33 | [
"Apache-2.0"
] | null | null | null | test/Library/Astrodynamics/Trajectory.test.cpp | cowlicks/library-astrodynamics | aec161a1e5a1294820a90e1a74633b5a71d59a33 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library/Astrodynamics
/// @file Library/Astrodynamics/Trajectory.test.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Astrodynamics/Trajectory/Models/Tabulated.hpp>
#include <Library/Astrodynamics/Trajectory.hpp>
#include <Library/Physics/Coordinate/Frame.hpp>
#include <Global.test.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (Library_Astrodynamics_Trajectory, Constructor)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
EXPECT_TRUE(trajectory.isDefined()) ;
}
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Trajectory trajectory = { states } ;
EXPECT_TRUE(trajectory.isDefined()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, EqualToOperator)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
EXPECT_TRUE(trajectory == trajectory) ;
}
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states_A =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model_A = { states_A } ;
const Trajectory trajectory_A = { model_A } ;
const Array<State> states_B =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 0.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model_B = { states_B } ;
const Trajectory trajectory_B = { model_B } ;
EXPECT_FALSE(trajectory_A == trajectory_B) ;
EXPECT_FALSE(trajectory_A == Trajectory::Undefined()) ;
EXPECT_FALSE(Trajectory::Undefined() == trajectory_B) ;
}
{
EXPECT_FALSE(Trajectory::Undefined() == Trajectory::Undefined()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, NotEqualToOperator)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
EXPECT_FALSE(trajectory != trajectory) ;
}
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states_A =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model_A = { states_A } ;
const Trajectory trajectory_A = { model_A } ;
const Array<State> states_B =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 0.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model_B = { states_B } ;
const Trajectory trajectory_B = { model_B } ;
EXPECT_TRUE(trajectory_A != trajectory_B) ;
EXPECT_TRUE(trajectory_A != Trajectory::Undefined()) ;
EXPECT_TRUE(Trajectory::Undefined() != trajectory_B) ;
}
{
EXPECT_TRUE(Trajectory::Undefined() != Trajectory::Undefined()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, StreamOperator)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
testing::internal::CaptureStdout() ;
EXPECT_NO_THROW(std::cout << trajectory << std::endl) ;
EXPECT_FALSE(testing::internal::GetCapturedStdout().empty()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, IsDefined)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
EXPECT_TRUE(trajectory.isDefined()) ;
}
{
EXPECT_FALSE(Trajectory::Undefined().isDefined()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, AccessModel)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
EXPECT_TRUE(trajectory.accessModel().is<Tabulated>()) ;
}
{
EXPECT_ANY_THROW(Trajectory::Undefined().accessModel()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, GetStateAt)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
EXPECT_EQ(states.at(0), trajectory.getStateAt(states.at(0).accessInstant())) ;
EXPECT_EQ(states.at(1), trajectory.getStateAt(states.at(1).accessInstant())) ;
EXPECT_EQ
(
State(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0, 500), Scale::UTC), Position::Meters({ 0.5, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr)),
trajectory.getStateAt(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0, 500), Scale::UTC))
) ;
EXPECT_ANY_THROW(trajectory.getStateAt(Instant::DateTime(DateTime(2017, 12, 31, 23, 59, 59), Scale::UTC))) ;
EXPECT_ANY_THROW(trajectory.getStateAt(Instant::DateTime(DateTime(2017, 12, 31, 23, 59, 58), Scale::UTC))) ;
EXPECT_ANY_THROW(trajectory.getStateAt(Instant::DateTime(DateTime(2017, 12, 31, 23, 59, 59), Scale::UTC))) ;
EXPECT_ANY_THROW(trajectory.getStateAt(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 2), Scale::UTC))) ;
EXPECT_ANY_THROW(trajectory.getStateAt(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 3), Scale::UTC))) ;
EXPECT_ANY_THROW(trajectory.getStateAt(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 2), Scale::UTC))) ;
EXPECT_EQ(states.at(0), trajectory.getStateAt(states.at(0).accessInstant())) ;
EXPECT_EQ(states.at(1), trajectory.getStateAt(states.at(1).accessInstant())) ;
EXPECT_EQ
(
State(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0, 500), Scale::UTC), Position::Meters({ 0.5, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr)),
trajectory.getStateAt(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0, 500), Scale::UTC))
) ;
}
{
EXPECT_ANY_THROW(Trajectory::Undefined().getStateAt(Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC))) ;
}
}
TEST (Library_Astrodynamics_Trajectory, GetStatesAt)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
{
const Array<Instant> referenceInstants =
{
states.at(0).accessInstant(),
Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0, 500), Scale::UTC),
states.at(1).accessInstant()
} ;
const Array<State> referenceStates =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0, 500), Scale::UTC), Position::Meters({ 0.5, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
EXPECT_EQ(referenceStates, trajectory.getStatesAt(referenceInstants)) ;
}
{
const Array<Instant> referenceInstants =
{
Instant::DateTime(DateTime(2017, 12, 31, 23, 59, 59), Scale::UTC),
states.at(0).accessInstant(),
states.at(1).accessInstant(),
Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 2), Scale::UTC)
} ;
EXPECT_ANY_THROW(trajectory.getStatesAt(referenceInstants)) ;
}
}
{
EXPECT_ANY_THROW(Trajectory::Undefined().getStatesAt({ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC) })) ;
}
}
TEST (Library_Astrodynamics_Trajectory, Print)
{
using library::core::types::Shared ;
using library::core::ctnr::Array ;
using library::physics::time::Scale ;
using library::physics::time::Instant ;
using library::physics::time::DateTime ;
using library::physics::coord::Position ;
using library::physics::coord::Velocity ;
using library::physics::coord::Frame ;
using library::astro::Trajectory ;
using library::astro::trajectory::State ;
using library::astro::trajectory::models::Tabulated ;
{
const Shared<const Frame> gcrfSPtr = Frame::GCRF() ;
const Array<State> states =
{
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC), Position::Meters({ 0.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) },
{ Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 1), Scale::UTC), Position::Meters({ 1.0, 0.0, 0.0 }, gcrfSPtr), Velocity::MetersPerSecond({ 1.0, 0.0, 0.0 }, gcrfSPtr) }
} ;
const Tabulated model = { states } ;
const Trajectory trajectory = { model } ;
testing::internal::CaptureStdout() ;
EXPECT_NO_THROW(trajectory.print(std::cout, true)) ;
EXPECT_NO_THROW(trajectory.print(std::cout, false)) ;
EXPECT_FALSE(testing::internal::GetCapturedStdout().empty()) ;
}
}
TEST (Library_Astrodynamics_Trajectory, Undefined)
{
using library::astro::Trajectory ;
{
EXPECT_NO_THROW(Trajectory::Undefined()) ;
EXPECT_FALSE(Trajectory::Undefined().isDefined()) ;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | 35.446691 | 191 | 0.585179 | [
"model"
] |
0086c87260dc3bb6f314678c248a253c1b55166c | 170,239 | cpp | C++ | src/shoebill/JniFunctions.cpp | eupedroosouza/ShoebillPlugin | 49bc98348061f08c8ec6e1ce9919d6736656bee9 | [
"Apache-2.0"
] | 6 | 2016-06-18T02:06:02.000Z | 2020-10-17T12:25:54.000Z | src/shoebill/JniFunctions.cpp | eupedroosouza/ShoebillPlugin | 49bc98348061f08c8ec6e1ce9919d6736656bee9 | [
"Apache-2.0"
] | 13 | 2015-11-13T13:00:33.000Z | 2021-12-09T13:49:52.000Z | src/shoebill/JniFunctions.cpp | eupedroosouza/ShoebillPlugin | 49bc98348061f08c8ec6e1ce9919d6736656bee9 | [
"Apache-2.0"
] | 7 | 2017-03-01T15:02:34.000Z | 2022-03-13T16:22:21.000Z | /**
* Copyright (C) 2011-2015 MK124 & 123marvin123
*
* 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 "JniFunctions.h"
#include "sampgdk.h"
#include "EncodingUtils.h"
#include "Shoebill.h"
#include "amx/amx.h"
#include "SimpleInlineHook.hpp"
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setServerCodepage
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setServerCodepage
(JNIEnv *, jclass, jint codepage) {
Shoebill::GetInstance().setServerCodepage((unsigned int) codepage);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getServerCodepage
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerCodepage
(JNIEnv *, jclass) {
return (jint) Shoebill::GetInstance().getServerCodepage();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerCodepage
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerCodepage
(JNIEnv *, jclass, jint playerid, jint codepage) {
Shoebill::GetInstance().setPlayerCodepage(playerid, (unsigned int) codepage);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerCodepage
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCodepage
(JNIEnv *, jclass, jint playerid) {
return (jint) Shoebill::GetInstance().getPlayerCodepage(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createObject
* Signature: (IFFFFFFF)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createObject
(JNIEnv *, jclass, jint modelid, jfloat x, jfloat y, jfloat z, jfloat rX, jfloat rY, jfloat rZ,
jfloat drawDistance) {
return CreateObject(modelid, x, y, z, rX, rY, rZ, drawDistance);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachObjectToVehicle
* Signature: (IIFFFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachObjectToVehicle
(JNIEnv *, jclass, jint objectid, jint vehicleid, jfloat x, jfloat y, jfloat z, jfloat rX, jfloat rY,
jfloat rZ) {
AttachObjectToVehicle(objectid, vehicleid, x, y, z, rX, rY, rZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachObjectToObject
* Signature: (IIFFFFFFI)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachObjectToObject
(JNIEnv *, jclass, jint objectid, jint attachtoid, jfloat offsetX, jfloat offsetY, jfloat offsetZ, jfloat rotX,
jfloat rotY, jfloat rotZ, jint syncRotation) {
AttachObjectToObject(objectid, attachtoid, offsetX, offsetY, offsetZ, rotX, rotY, rotZ, (bool) syncRotation);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachObjectToPlayer
* Signature: (IIFFFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachObjectToPlayer
(JNIEnv *, jclass, jint objectid, jint playerid,
jfloat offsetX, jfloat offsetY, jfloat offsetZ, jfloat rX, jfloat rY, jfloat rZ) {
AttachObjectToPlayer(objectid, playerid, offsetX, offsetY, offsetZ, rX, rY, rZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setObjectPos
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setObjectPos
(JNIEnv *, jclass, jint objectid, jfloat x, jfloat y, jfloat z) {
SetObjectPos(objectid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getObjectPos
* Signature: (ILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getObjectPos
(JNIEnv *env, jclass, jint objectid, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetObjectPos(objectid, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setObjectRot
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setObjectRot
(JNIEnv *, jclass, jint objectid, jfloat rotX, jfloat rotY, jfloat rotZ) {
SetObjectRot(objectid, rotX, rotY, rotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getObjectRot
* Signature: (ILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getObjectRot
(JNIEnv *env, jclass, jint objectid, jobject rotate) {
assertNotNull(rotate, "rotate", __FUNCTION__);
static auto cls = env->GetObjectClass(rotate);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float rotX, rotY, rotZ;
GetObjectRot(objectid, &rotX, &rotY, &rotZ);
env->SetFloatField(rotate, fidX, rotX);
env->SetFloatField(rotate, fidY, rotY);
env->SetFloatField(rotate, fidZ, rotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isValidObject
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isValidObject
(JNIEnv *, jclass, jint objectid) {
return (jboolean) IsValidObject(objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: destroyObject
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_destroyObject
(JNIEnv *, jclass, jint objectid) {
DestroyObject(objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: moveObject
* Signature: (IFFFFFFF)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_moveObject
(JNIEnv *, jclass, jint objectid, jfloat x, jfloat y, jfloat z, jfloat speed, jfloat rotX, jfloat rotY,
jfloat rotZ) {
return MoveObject(objectid, x, y, z, speed, rotX, rotY, rotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: stopObject
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_stopObject
(JNIEnv *, jclass, jint objectid) {
StopObject(objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isObjectMoving
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isObjectMoving
(JNIEnv *, jclass, jint objectid) {
return (jboolean) IsObjectMoving(objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: editObject
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_editObject
(JNIEnv *, jclass, jint playerid, jint objectid) {
return (jboolean) EditObject(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: editPlayerObject
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_editPlayerObject
(JNIEnv *, jclass, jint playerid, jint objectid) {
return (jboolean) EditPlayerObject(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: selectObject
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_selectObject
(JNIEnv *, jclass, jint playerid) {
SelectObject(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: cancelEdit
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_cancelEdit
(JNIEnv *, jclass, jint playerid) {
CancelEdit(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createPlayerObject
* Signature: (IIFFFFFFF)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createPlayerObject
(JNIEnv *, jclass, jint playerid, jint modelid, jfloat x, jfloat y, jfloat z, jfloat rX, jfloat rY, jfloat rZ,
jfloat drawDistance) {
return CreatePlayerObject(playerid, modelid, x, y, z, rX, rY, rZ, drawDistance);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachPlayerObjectToVehicle
* Signature: (IIIFFFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachPlayerObjectToVehicle
(JNIEnv *, jclass, jint playerid, jint objectid, jint vehicleid, jfloat fOffsetX, jfloat fOffsetY,
jfloat fOffsetZ, jfloat fRotX, jfloat fRotY, jfloat fRotZ) {
AttachPlayerObjectToVehicle(playerid, objectid, vehicleid, fOffsetX, fOffsetY, fOffsetZ, fRotX, fRotY, fRotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerObjectPos
* Signature: (IIFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerObjectPos
(JNIEnv *, jclass, jint playerid, jint objectid, jfloat x, jfloat y, jfloat z) {
SetPlayerObjectPos(playerid, objectid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerObjectPos
* Signature: (IILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerObjectPos
(JNIEnv *env, jclass, jint playerid, jint objectid, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetPlayerObjectPos(playerid, objectid, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerObjectRot
* Signature: (IIFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerObjectRot
(JNIEnv *, jclass, jint playerid, jint objectid, jfloat rotX, jfloat rotY, jfloat rotZ) {
SetPlayerObjectRot(playerid, objectid, rotX, rotY, rotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerObjectRot
* Signature: (IILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerObjectRot
(JNIEnv *env, jclass, jint playerid, jint objectid, jobject rotate) {
assertNotNull(rotate, "rotate", __FUNCTION__);
static auto cls = env->GetObjectClass(rotate);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float rotX, rotY, rotZ;
GetPlayerObjectRot(playerid, objectid, &rotX, &rotY, &rotZ);
env->SetFloatField(rotate, fidX, rotX);
env->SetFloatField(rotate, fidY, rotY);
env->SetFloatField(rotate, fidZ, rotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isValidPlayerObject
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isValidPlayerObject
(JNIEnv *, jclass, jint playerid, jint objectid) {
return (jboolean) IsValidPlayerObject(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: destroyPlayerObject
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_destroyPlayerObject
(JNIEnv *, jclass, jint playerid, jint objectid) {
DestroyPlayerObject(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: movePlayerObject
* Signature: (IIFFFFFFF)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_movePlayerObject
(JNIEnv *, jclass, jint playerid, jint objectid, jfloat x, jfloat y, jfloat z, jfloat speed, jfloat rotX,
jfloat rotY, jfloat rotZ) {
return MovePlayerObject(playerid, objectid, x, y, z, speed, rotX, rotY, rotZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: stopPlayerObject
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_stopPlayerObject
(JNIEnv *, jclass, jint playerid, jint objectid) {
StopPlayerObject(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerObjectMoving
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerObjectMoving
(JNIEnv *, jclass, jint playerid, jint objectid) {
return (jboolean) IsPlayerObjectMoving(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachPlayerObjectToPlayer
* Signature: (IIIFFFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachPlayerObjectToPlayer
(JNIEnv *, jclass, jint playerid, jint objectid, jint attachplayerid,
jfloat offsetX, jfloat offsetY, jfloat offsetZ, jfloat rX, jfloat rY, jfloat rZ) {
AttachPlayerObjectToPlayer(playerid, objectid, attachplayerid, offsetX, offsetY, offsetZ, rX, rY, rZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setObjectMaterial
* Signature: (IIILjava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setObjectMaterial
(JNIEnv *env, jclass, jint objectid, jint materialindex, jint modelid, jstring txdname, jstring texturename,
jint materialcolor) {
assertNotNull(txdname, "txdname", __FUNCTION__);assertNotNull(texturename, "texturename", __FUNCTION__);
auto codepage = Shoebill::GetInstance().getServerCodepage();
auto str_txdname = wcs2mbs(env, codepage, txdname, 1024);
auto str_texturename = wcs2mbs(env, codepage, texturename, 1024);
SetObjectMaterial(objectid, materialindex, modelid, str_txdname, str_texturename, materialcolor);
delete[] str_texturename;
delete[] str_txdname;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerObjectMaterial
* Signature: (IIIILjava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerObjectMaterial
(JNIEnv *env, jclass, jint playerid, jint objectid, jint materialindex, jint modelid, jstring txdname,
jstring texturename, jint materialcolor) {
assertNotNull(txdname, "txdname", __FUNCTION__);assertNotNull(texturename, "texturename", __FUNCTION__);
auto codepage = Shoebill::GetInstance().getServerCodepage();
auto str_txdname = wcs2mbs(env, codepage, txdname, 1024);
auto str_texturename = wcs2mbs(env, codepage, texturename, 1024);
SetPlayerObjectMaterial(playerid, objectid, materialindex, modelid, str_txdname, str_texturename, materialcolor);
delete[] str_texturename;
delete[] str_txdname;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setObjectMaterialText
* Signature: (ILjava/lang/String;IILjava/lang/String;IIIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setObjectMaterialText
(JNIEnv *env, jclass, jint objectid, jstring text, jint materialindex, jint materialsize, jstring fontface,
jint fontsize, jint bold, jint fontcolor, jint backcolor, jint textalignment) {
assertNotNull(text, "text", __FUNCTION__);assertNotNull(fontface, "fontface", __FUNCTION__);
auto codepage = Shoebill::GetInstance().getServerCodepage();
auto str_text = wcs2mbs(env, codepage, text, 1024);
auto str_fontface = wcs2mbs(env, codepage, fontface, 128);
SetObjectMaterialText(objectid, str_text, materialindex, materialsize, str_fontface, fontsize, (bool) bold,
fontcolor,
backcolor, textalignment);
delete[] str_text;
delete[] str_fontface;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerObjectMaterialText
* Signature: (IILjava/lang/String;IILjava/lang/String;IIIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerObjectMaterialText
(JNIEnv *env, jclass, jint playerid, jint objectid, jstring text, jint materialindex, jint materialsize,
jstring fontface, jint fontsize, jint bold, jint fontcolor, jint backcolor, jint textalignment) {
assertNotNull(text, "text", __FUNCTION__);assertNotNull(fontface, "fontface", __FUNCTION__);
auto codepage = Shoebill::GetInstance().getPlayerCodepage(playerid);
auto str_text = wcs2mbs(env, codepage, text, 1024);
auto str_fontface = wcs2mbs(env, codepage, fontface, 128);
SetPlayerObjectMaterialText(playerid, objectid, str_text, materialindex, materialsize, str_fontface, fontsize,
(bool) bold, fontcolor, backcolor, textalignment);
delete[] str_text;
delete[] str_fontface;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setSpawnInfo
* Signature: (IIIFFFFIIIIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setSpawnInfo
(JNIEnv *, jclass, jint playerid, jint teamid, jint skinid, jfloat x, jfloat y, jfloat z,
jfloat rotation, jint weapon1, jint ammo1, jint weapon2, jint ammo2, jint weapon3, jint ammo3) {
SetSpawnInfo(playerid, teamid, skinid, x, y, z, rotation, weapon1, ammo1, weapon2, ammo2, weapon3, ammo3);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: spawnPlayer
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_spawnPlayer
(JNIEnv *, jclass, jint playerid) {
SpawnPlayer(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: getAnimationName
* Signature: (I)[Ljava/lang/String;
*/
JNIEXPORT jobjectArray JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getAnimationName(JNIEnv *env, jclass,
jint animationIndex) {
char animLib[32] = "None", animName[32] = "None";
GetAnimationName(animationIndex, animLib, 32, animName, 32);
auto objectArray = static_cast<jobjectArray>(env->NewObjectArray(2, env->FindClass("java/lang/String"),
env->NewStringUTF("")));
env->SetObjectArrayElement(objectArray, 0, env->NewStringUTF(animLib));
env->SetObjectArrayElement(objectArray, 1, env->NewStringUTF(animName));
return objectArray;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerPos
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerPos
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z) {
SetPlayerPos(playerid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerPosFindZ
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerPosFindZ
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z) {
SetPlayerPosFindZ(playerid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerPos
* Signature: (ILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerPos
(JNIEnv *env, jclass, jint playerid, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetPlayerPos(playerid, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerFacingAngle
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerFacingAngle
(JNIEnv *, jclass, jint playerid, jfloat angle) {
SetPlayerFacingAngle(playerid, angle);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerFacingAngle
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerFacingAngle
(JNIEnv *, jclass, jint playerid) {
float angle;
GetPlayerFacingAngle(playerid, &angle);
return angle;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerInRangeOfPoint
* Signature: (IFFFF)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerInRangeOfPoint
(JNIEnv *, jclass, jint playerid, jfloat range, jfloat x, jfloat y, jfloat z) {
return (jboolean) IsPlayerInRangeOfPoint(playerid, range, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerStreamedIn
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerStreamedIn
(JNIEnv *, jclass, jint playerid, jint forplayerid) {
return (jboolean) IsPlayerStreamedIn(playerid, forplayerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerInterior
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerInterior
(JNIEnv *, jclass, jint playerid, jint interiorid) {
SetPlayerInterior(playerid, interiorid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerInterior
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerInterior
(JNIEnv *, jclass, jint playerid) {
return GetPlayerInterior(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerHealth
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerHealth
(JNIEnv *, jclass, jint playerid, jfloat health) {
SetPlayerHealth(playerid, health);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerHealth
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerHealth
(JNIEnv *, jclass, jint playerid) {
float health;
GetPlayerHealth(playerid, &health);
return health;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerArmour
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerArmour
(JNIEnv *, jclass, jint playerid, jfloat armour) {
SetPlayerArmour(playerid, armour);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerArmour
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerArmour
(JNIEnv *, jclass, jint playerid) {
float armour;
GetPlayerArmour(playerid, &armour);
return armour;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerAmmo
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerAmmo
(JNIEnv *, jclass, jint playerid, jint weaponslot, jint ammo) {
SetPlayerAmmo(playerid, weaponslot, ammo);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerAmmo
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerAmmo
(JNIEnv *, jclass, jint playerid) {
return GetPlayerAmmo(playerid);;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerWeaponState
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerWeaponState
(JNIEnv *, jclass, jint playerid) {
return GetPlayerWeaponState(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerTargetPlayer
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerTargetPlayer
(JNIEnv *, jclass, jint playerid) {
return GetPlayerTargetPlayer(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerTeam
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerTeam
(JNIEnv *, jclass, jint playerid, jint teamid) {
SetPlayerTeam(playerid, teamid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerTeam
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerTeam
(JNIEnv *, jclass, jint playerid) {
return GetPlayerTeam(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerScore
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerScore
(JNIEnv *, jclass, jint playerid, jint score) {
SetPlayerScore(playerid, score);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerScore
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerScore
(JNIEnv *, jclass, jint playerid) {
return GetPlayerScore(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerDrunkLevel
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerDrunkLevel
(JNIEnv *, jclass, jint playerid) {
return GetPlayerDrunkLevel(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerDrunkLevel
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerDrunkLevel
(JNIEnv *, jclass, jint playerid, jint level) {
SetPlayerDrunkLevel(playerid, level);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerColor
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerColor
(JNIEnv *, jclass, jint playerid, jint color) {
SetPlayerColor(playerid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerColor
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerColor
(JNIEnv *, jclass, jint playerid) {
return GetPlayerColor(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerSkin
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerSkin
(JNIEnv *, jclass, jint playerid, jint skinid) {
SetPlayerSkin(playerid, skinid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerSkin
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerSkin
(JNIEnv *, jclass, jint playerid) {
return GetPlayerSkin(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: givePlayerWeapon
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_givePlayerWeapon
(JNIEnv *, jclass, jint playerid, jint weaponid, jint ammo) {
GivePlayerWeapon(playerid, weaponid, ammo);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: resetPlayerWeapons
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_resetPlayerWeapons
(JNIEnv *, jclass, jint playerid) {
ResetPlayerWeapons(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerArmedWeapon
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerArmedWeapon
(JNIEnv *, jclass, jint playerid, jint weaponid) {
SetPlayerArmedWeapon(playerid, weaponid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerWeaponData
* Signature: (IILnet/gtaun/shoebill/data/WeaponData;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerWeaponData
(JNIEnv *env, jclass, jint playerid, jint slot, jobject weapondata) {
assertNotNull(weapondata, "weapondata", __FUNCTION__);
static auto cls = env->GetObjectClass(weapondata);
static auto fidAmmo = env->GetFieldID(cls, "ammo", "I");
static auto setWeaponMethodId = env->GetMethodID(cls, "setModel", "(I)V");
int weaponid, ammo;
GetPlayerWeaponData(playerid, slot, &weaponid, &ammo);
env->CallVoidMethod(weapondata, setWeaponMethodId, weaponid);
env->SetIntField(weapondata, fidAmmo, ammo);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: givePlayerMoney
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_givePlayerMoney
(JNIEnv *, jclass, jint playerid, jint money) {
GivePlayerMoney(playerid, money);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: resetPlayerMoney
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_resetPlayerMoney
(JNIEnv *, jclass, jint playerid) {
ResetPlayerMoney(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerName
* Signature: (ILjava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerName
(JNIEnv *env, jclass, jint playerid, jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, MAX_PLAYER_NAME);
auto ret = SetPlayerName(playerid, str);
delete[] str;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerMoney
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerMoney
(JNIEnv *, jclass, jint playerid) {
return GetPlayerMoney(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerState
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerState
(JNIEnv *, jclass, jint playerid) {
return GetPlayerState(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerIp
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerIp
(JNIEnv *env, jclass, jint playerid) {
char ip[20];
GetPlayerIp(playerid, ip, sizeof(ip));
return env->NewStringUTF(ip);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerPing
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerPing
(JNIEnv *, jclass, jint playerid) {
return GetPlayerPing(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerWeapon
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerWeapon
(JNIEnv *, jclass, jint playerid) {
return GetPlayerWeapon(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerKeys
* Signature: (ILnet/gtaun/shoebill/object/impl/PlayerKeyStateImpl;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerKeys
(JNIEnv *env, jclass, jint playerid, jobject keystate) {
assertNotNull(keystate, "keystate", __FUNCTION__);
static auto cls = env->GetObjectClass(keystate);
static auto fidKeys = env->GetFieldID(cls, "keys", "I");
static auto fidUpdown = env->GetFieldID(cls, "updownValue", "I");
static auto fidLeftright = env->GetFieldID(cls, "leftrightValue", "I");
int keys, updown, leftright;
GetPlayerKeys(playerid, &keys, &updown, &leftright);
env->SetIntField(keystate, fidKeys, keys);
env->SetIntField(keystate, fidUpdown, updown);
env->SetIntField(keystate, fidLeftright, leftright);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerName
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerName
(JNIEnv *env, jclass, jint playerid) {
char name[MAX_PLAYER_NAME];
GetPlayerName(playerid, name, sizeof(name));
return mbs2wcs(env, Shoebill::GetInstance().getServerCodepage(), name, MAX_PLAYER_NAME);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerTime
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerTime
(JNIEnv *, jclass, jint playerid, jint hour, jint minute) {
SetPlayerTime(playerid, hour, minute);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerTime
* Signature: (ILjava/sql/Time;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerTime
(JNIEnv *env, jclass, jint playerid, jobject time) {
assertNotNull(time, "time", __FUNCTION__);
static auto cls = env->GetObjectClass(time);
static auto fidHour = env->GetFieldID(cls, "hour", "I");
static auto fidMinute = env->GetFieldID(cls, "minute", "I");
int hour, minute;
GetPlayerTime(playerid, &hour, &minute);
env->SetIntField(time, fidHour, hour);
env->SetIntField(time, fidMinute, minute);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: togglePlayerClock
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_togglePlayerClock
(JNIEnv *, jclass, jint playerid, jboolean toggle) {
TogglePlayerClock(playerid, toggle);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerWeather
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerWeather
(JNIEnv *, jclass, jint playerid, jint weather) {
SetPlayerWeather(playerid, weather);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: forceClassSelection
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_forceClassSelection
(JNIEnv *, jclass, jint playerid) {
ForceClassSelection(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerWantedLevel
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerWantedLevel
(JNIEnv *, jclass, jint playerid, jint level) {
SetPlayerWantedLevel(playerid, level);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerWantedLevel
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerWantedLevel
(JNIEnv *, jclass, jint playerid) {
return GetPlayerWantedLevel(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerFightingStyle
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerFightingStyle
(JNIEnv *, jclass, jint playerid, jint style) {
SetPlayerFightingStyle(playerid, style);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerFightingStyle
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerFightingStyle
(JNIEnv *, jclass, jint playerid) {
return GetPlayerFightingStyle(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerVelocity
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerVelocity
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z) {
SetPlayerVelocity(playerid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerVelocity
* Signature: (ILnet/gtaun/shoebill/data/Velocity;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerVelocity
(JNIEnv *env, jclass, jint playerid, jobject velocity) {
assertNotNull(velocity, "velocity", __FUNCTION__);
static auto cls = env->GetObjectClass(velocity);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetPlayerVelocity(playerid, &x, &y, &z);
env->SetFloatField(velocity, fidX, x);
env->SetFloatField(velocity, fidY, y);
env->SetFloatField(velocity, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playCrimeReportForPlayer
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playCrimeReportForPlayer
(JNIEnv *, jclass, jint playerid, jint suspectid, jint crime) {
PlayCrimeReportForPlayer(playerid, suspectid, crime);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playAudioStreamForPlayer
* Signature: (ILjava/lang/String;FFFFI)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playAudioStreamForPlayer
(JNIEnv *env, jclass, jint player, jstring url, jfloat posX, jfloat posY, jfloat posZ, jfloat distance,
jint usepos) {
assertNotNull(url, "url", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(player), url, 1024);
PlayAudioStreamForPlayer(player, str, posX, posY, posZ, distance, (bool) usepos);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: stopAudioStreamForPlayer
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_stopAudioStreamForPlayer
(JNIEnv *, jclass, jint playerid) {
StopAudioStreamForPlayer(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerShopName
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerShopName
(JNIEnv *env, jclass, jint playerid, jstring name) {
assertNotNull(name, "name", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), name, 64);
SetPlayerShopName(playerid, str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerSkillLevel
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerSkillLevel
(JNIEnv *, jclass, jint playerid, jint skill, jint level) {
SetPlayerSkillLevel(playerid, skill, level);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerSurfingVehicleID
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerSurfingVehicleID
(JNIEnv *, jclass, jint playerid) {
return GetPlayerSurfingVehicleID(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerSurfingObjectID
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerSurfingObjectID
(JNIEnv *, jclass, jint playerid) {
return GetPlayerSurfingObjectID(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: removeBuildingForPlayer
* Signature: (IIFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_removeBuildingForPlayer
(JNIEnv *, jclass, jint player, jint modelid, jfloat x, jfloat y, jfloat z, jfloat radius) {
RemoveBuildingForPlayer(player, modelid, x, y, z, radius);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: getPlayerLastShotVectors
* Signature: (ILjava/lang/Object;Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerLastShotVectors
(JNIEnv *env, jclass, jint playerid, jobject origin, jobject hitpos) {
assertNotNull(origin, "origin", __FUNCTION__); assertNotNull(hitpos, "hitpos", __FUNCTION__);
static auto cls = env->GetObjectClass(origin);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z, hx, hy, hz;
GetPlayerLastShotVectors(playerid, &x, &y, &z, &hx, &hy, &hz);
env->SetFloatField(origin, fidX, x);
env->SetFloatField(origin, fidY, y);
env->SetFloatField(origin, fidZ, z);
env->SetFloatField(hitpos, fidX, hx);
env->SetFloatField(hitpos, fidY, hy);
env->SetFloatField(hitpos, fidZ, hz);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerAttachedObject
* Signature: (IIIIFFFFFFFFF)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerAttachedObject
(JNIEnv *, jclass, jint playerid, jint index, jint modelid, jint bone, jfloat offsetX, jfloat offsetY,
jfloat offsetZ, jfloat rotX, jfloat rotY, jfloat rotZ, jfloat scaleX, jfloat scaleY, jfloat scaleZ,
jint materialcolor1, jint materialcolor2) {
return (jboolean) SetPlayerAttachedObject(playerid, index, modelid, bone,
offsetX, offsetY, offsetZ, rotX, rotY, rotZ, scaleX, scaleY, scaleZ,
materialcolor1, materialcolor2);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: removePlayerAttachedObject
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_removePlayerAttachedObject
(JNIEnv *, jclass, jint playerid, jint index) {
return (jboolean) RemovePlayerAttachedObject(playerid, index);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerAttachedObjectSlotUsed
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerAttachedObjectSlotUsed
(JNIEnv *, jclass, jint playerid, jint index) {
return (jboolean) IsPlayerAttachedObjectSlotUsed(playerid, index);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: editAttachedObject
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_editAttachedObject
(JNIEnv *, jclass, jint playerid, jint index) {
return (jboolean) EditAttachedObject(playerid, index);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createPlayerTextDraw
* Signature: (IFFLjava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createPlayerTextDraw
(JNIEnv *env, jclass, jint playerid, jfloat x, jfloat y, jstring text) {
assertNotNullReturn(text, "text", __FUNCTION__, 0);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), text, 2048);
auto ret = CreatePlayerTextDraw(playerid, x, y, str);
delete[] str;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawDestroy
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawDestroy
(JNIEnv *, jclass, jint playerid, jint textid) {
PlayerTextDrawDestroy(playerid, textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawLetterSize
* Signature: (IIFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawLetterSize
(JNIEnv *, jclass, jint playerid, jint textid, jfloat x, jfloat y) {
PlayerTextDrawLetterSize(playerid, textid, x, y);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawTextSize
* Signature: (IIFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawTextSize
(JNIEnv *, jclass, jint playerid, jint textid, jfloat x, jfloat y) {
PlayerTextDrawTextSize(playerid, textid, x, y);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawAlignment
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawAlignment
(JNIEnv *, jclass, jint playerid, jint textid, jint alignment) {
PlayerTextDrawAlignment(playerid, textid, alignment);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawColor
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawColor
(JNIEnv *, jclass, jint playerid, jint textid, jint color) {
PlayerTextDrawColor(playerid, textid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawUseBox
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawUseBox
(JNIEnv *, jclass, jint playerid, jint textid, jint use) {
PlayerTextDrawUseBox(playerid, textid, (bool) use);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawBoxColor
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawBoxColor
(JNIEnv *, jclass, jint playerid, jint textid, jint color) {
PlayerTextDrawBoxColor(playerid, textid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawSetShadow
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetShadow
(JNIEnv *, jclass, jint playerid, jint textid, jint size) {
PlayerTextDrawSetShadow(playerid, textid, size);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawSetOutline
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetOutline
(JNIEnv *, jclass, jint playerid, jint textid, jint size) {
PlayerTextDrawSetOutline(playerid, textid, size);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawBackgroundColor
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawBackgroundColor
(JNIEnv *, jclass, jint playerid, jint textid, jint color) {
PlayerTextDrawBackgroundColor(playerid, textid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawFont
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawFont
(JNIEnv *, jclass, jint playerid, jint textid, jint font) {
PlayerTextDrawFont(playerid, textid, font);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawSetProportional
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetProportional
(JNIEnv *, jclass, jint playerid, jint textid, jint set) {
PlayerTextDrawSetProportional(playerid, textid, (bool) set);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawSetSelectable
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetSelectable
(JNIEnv *, jclass, jint playerid, jint textid, jint set) {
PlayerTextDrawSetSelectable(playerid, textid, (bool) set);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawShow
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawShow
(JNIEnv *, jclass, jint playerid, jint textid) {
PlayerTextDrawShow(playerid, textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawHide
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawHide
(JNIEnv *, jclass, jint playerid, jint textid) {
PlayerTextDrawHide(playerid, textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerTextDrawSetString
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetString
(JNIEnv *env, jclass, jint playerid, jint textid, jstring string) {
assertNotNull(string, "string", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), string, 2048);
PlayerTextDrawSetString(playerid, textid, str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: playerTextDrawSetPreviewModel
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetPreviewModel
(JNIEnv *, jclass, jint playerid, jint textId, jint modelindex) {
PlayerTextDrawSetPreviewModel(playerid, textId, modelindex);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: playerTextDrawSetPreviewRot
* Signature: (IIFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetPreviewRot
(JNIEnv *, jclass, jint playerid, jint textId, jfloat fRotX, jfloat fRotY, jfloat fRotZ, jfloat fZoom) {
PlayerTextDrawSetPreviewRot(playerid, textId, fRotX, fRotY, fRotZ, fZoom);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: playerTextDrawSetPreviewVehCol
* Signature: (IIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerTextDrawSetPreviewVehCol
(JNIEnv *, jclass, jint playerid, jint textId, jint color1, jint color2) {
PlayerTextDrawSetPreviewVehCol(playerid, textId, color1, color2);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerChatBubble
* Signature: (ILjava/lang/String;IFI)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerChatBubble
(JNIEnv *env, jclass, jint playerid, jstring text, jint color, jfloat drawdistance, jint expiretime) {
assertNotNull(text, "text", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), text, 256);
SetPlayerChatBubble(playerid, str, color, drawdistance, expiretime);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: putPlayerInVehicle
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_putPlayerInVehicle
(JNIEnv *, jclass, jint playerid, jint vehicleid, jint seatid) {
PutPlayerInVehicle(playerid, vehicleid, seatid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerVehicleID
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerVehicleID
(JNIEnv *, jclass, jint playerid) {
return GetPlayerVehicleID(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerVehicleSeat
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerVehicleSeat
(JNIEnv *, jclass, jint playerid) {
return GetPlayerVehicleSeat(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: removePlayerFromVehicle
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_removePlayerFromVehicle
(JNIEnv *, jclass, jint playerid) {
RemovePlayerFromVehicle(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: togglePlayerControllable
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_togglePlayerControllable
(JNIEnv *, jclass, jint playerid, jboolean toggle) {
TogglePlayerControllable(playerid, toggle);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerPlaySound
* Signature: (IIFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerPlaySound
(JNIEnv *, jclass, jint playerid, jint soundid, jfloat x, jfloat y, jfloat z) {
PlayerPlaySound(playerid, soundid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: applyAnimation
* Signature: (ILjava/lang/String;Ljava/lang/String;FIIIIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_applyAnimation
(JNIEnv *env, jclass, jint playerid, jstring animlib, jstring animname,
jfloat delta, jint loop, jint lockX, jint lockY, jint freeze, jint time, jint forcesync) {
assertNotNull(animlib, "animlib", __FUNCTION__); assertNotNull(animlib, "animlib", __FUNCTION__);
auto str_animlib = env->GetStringUTFChars(animlib, nullptr);
auto str_animname = env->GetStringUTFChars(animname, nullptr);
ApplyAnimation(playerid, str_animlib, str_animname, delta, (bool) loop, (bool) lockX, (bool) lockY, (bool) freeze,
time, (bool) forcesync);
env->ReleaseStringUTFChars(animlib, str_animlib);
env->ReleaseStringUTFChars(animname, str_animname);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: clearAnimations
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_clearAnimations
(JNIEnv *, jclass, jint playerid, jint forcesync) {
ClearAnimations(playerid, (bool) forcesync);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerAnimationIndex
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerAnimationIndex
(JNIEnv *, jclass, jint playerid) {
return GetPlayerAnimationIndex(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerSpecialAction
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerSpecialAction
(JNIEnv *, jclass, jint playerid) {
return GetPlayerSpecialAction(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerSpecialAction
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerSpecialAction
(JNIEnv *, jclass, jint playerid, jint actionid) {
SetPlayerSpecialAction(playerid, actionid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerCheckpoint
* Signature: (IFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerCheckpoint
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z, jfloat size) {
SetPlayerCheckpoint(playerid, x, y, z, size);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: disablePlayerCheckpoint
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disablePlayerCheckpoint
(JNIEnv *, jclass, jint playerid) {
DisablePlayerCheckpoint(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerRaceCheckpoint
* Signature: (IIFFFFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerRaceCheckpoint
(JNIEnv *, jclass, jint playerid, jint type, jfloat x, jfloat y, jfloat z,
jfloat nextX, jfloat nextY, jfloat nextZ, jfloat size) {
SetPlayerRaceCheckpoint(playerid, type, x, y, z, nextX, nextY, nextZ, size);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: disablePlayerRaceCheckpoint
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disablePlayerRaceCheckpoint
(JNIEnv *, jclass, jint playerid) {
DisablePlayerRaceCheckpoint(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerWorldBounds
* Signature: (IFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerWorldBounds
(JNIEnv *, jclass, jint playerid, jfloat x_max, jfloat x_min, jfloat y_max, jfloat y_min) {
SetPlayerWorldBounds(playerid, x_max, x_min, y_max, y_min);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerMarkerForPlayer
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerMarkerForPlayer
(JNIEnv *, jclass, jint playerid, jint showplayerid, jint color) {
SetPlayerMarkerForPlayer(playerid, showplayerid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: showPlayerNameTagForPlayer
* Signature: (IIZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_showPlayerNameTagForPlayer
(JNIEnv *, jclass, jint playerid, jint showplayerid, jboolean show) {
ShowPlayerNameTagForPlayer(playerid, showplayerid, show);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerMapIcon
* Signature: (IIFFFIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerMapIcon
(JNIEnv *, jclass, jint playerid, jint iconid, jfloat x, jfloat y, jfloat z, jint markertype, jint color,
jint style) {
SetPlayerMapIcon(playerid, iconid, x, y, z, markertype, color, style);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: removePlayerMapIcon
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_removePlayerMapIcon
(JNIEnv *, jclass, jint playerid, jint iconid) {
RemovePlayerMapIcon(playerid, iconid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerCameraPos
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerCameraPos
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z) {
SetPlayerCameraPos(playerid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerCameraLookAt
* Signature: (IFFFI)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerCameraLookAt
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z, jint cut) {
SetPlayerCameraLookAt(playerid, x, y, z, cut);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setCameraBehindPlayer
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setCameraBehindPlayer
(JNIEnv *, jclass, jint playerid) {
SetCameraBehindPlayer(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerCameraPos
* Signature: (ILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraPos
(JNIEnv *env, jclass, jint playerid, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetPlayerCameraPos(playerid, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerCameraFrontVector
* Signature: (ILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraFrontVector
(JNIEnv *env, jclass, jint playerid, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetPlayerCameraFrontVector(playerid, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerCameraMode
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraMode
(JNIEnv *, jclass, jint playerid) {
return GetPlayerCameraMode(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: getPlayerCameraAspectRatio
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraAspectRatio
(JNIEnv *, jclass, jint playerid) {
return GetPlayerCameraAspectRatio(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: getPlayerCameraZoom
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraZoom
(JNIEnv *, jclass, jint playerid) {
return GetPlayerCameraZoom(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachCameraToObject
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachCameraToObject
(JNIEnv *, jclass, jint playerid, jint objectid) {
AttachCameraToObject(playerid, objectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachCameraToPlayerObject
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachCameraToPlayerObject
(JNIEnv *, jclass, jint playerid, jint playerobjectid) {
AttachCameraToPlayerObject(playerid, playerobjectid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: interpolateCameraPos
* Signature: (IFFFFFFII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_interpolateCameraPos
(JNIEnv *, jclass, jint playerid, jfloat FromX, jfloat FromY, jfloat FromZ, jfloat ToX, jfloat ToY, jfloat ToZ,
jint time, jint cut) {
InterpolateCameraPos(playerid, FromX, FromY, FromZ, ToX, ToY, ToZ, time, cut);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: interpolateCameraLookAt
* Signature: (IFFFFFFII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_interpolateCameraLookAt
(JNIEnv *, jclass, jint playerid, jfloat FromX, jfloat FromY, jfloat FromZ, jfloat ToX, jfloat ToY, jfloat ToZ,
jint time, jint cut) {
InterpolateCameraLookAt(playerid, FromX, FromY, FromZ, ToX, ToY, ToZ, time, cut);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerConnected
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerConnected
(JNIEnv *, jclass, jint playerid) {
return (jboolean) IsPlayerConnected(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerInVehicle
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerInVehicle
(JNIEnv *, jclass, jint playerid, jint vehicleid) {
return (jboolean) IsPlayerInVehicle(playerid, vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerInAnyVehicle
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerInAnyVehicle
(JNIEnv *, jclass, jint playerid) {
return (jboolean) IsPlayerInAnyVehicle(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerInCheckpoint
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerInCheckpoint
(JNIEnv *, jclass, jint playerid) {
return (jboolean) IsPlayerInCheckpoint(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerInRaceCheckpoint
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerInRaceCheckpoint
(JNIEnv *, jclass, jint playerid) {
return (jboolean) IsPlayerInRaceCheckpoint(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setPlayerVirtualWorld
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerVirtualWorld
(JNIEnv *, jclass, jint playerid, jint worldid) {
SetPlayerVirtualWorld(playerid, worldid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerVirtualWorld
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerVirtualWorld
(JNIEnv *, jclass, jint playerid) {
return GetPlayerVirtualWorld(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: enableStuntBonusForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_enableStuntBonusForPlayer
(JNIEnv *, jclass, jint playerid, jint enabled) {
EnableStuntBonusForPlayer(playerid, (bool) enabled);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: enableStuntBonusForAll
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_enableStuntBonusForAll
(JNIEnv *, jclass, jboolean enabled) {
EnableStuntBonusForAll(enabled);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: togglePlayerSpectating
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_togglePlayerSpectating
(JNIEnv *, jclass, jint playerid, jboolean toggle) {
TogglePlayerSpectating(playerid, toggle);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerSpectatePlayer
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerSpectatePlayer
(JNIEnv *, jclass, jint playerid, jint targetplayerid, jint mode) {
PlayerSpectatePlayer(playerid, targetplayerid, mode);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: playerSpectateVehicle
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_playerSpectateVehicle
(JNIEnv *, jclass, jint playerid, jint targetvehicleid, jint mode) {
PlayerSpectateVehicle(playerid, targetvehicleid, mode);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: startRecordingPlayerData
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_startRecordingPlayerData
(JNIEnv *env, jclass, jint playerid, jint recordtype, jstring recordname) {
assertNotNull(recordname, "recordname", __FUNCTION__);
auto str_recordname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), recordname, 64);
StartRecordingPlayerData(playerid, recordtype, str_recordname);
delete[] str_recordname;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: stopRecordingPlayerData
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_stopRecordingPlayerData
(JNIEnv *, jclass, jint playerid) {
StopRecordingPlayerData(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: selectTextDraw
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_selectTextDraw
(JNIEnv *, jclass, jint playerid, jint hovercolor) {
SelectTextDraw(playerid, hovercolor);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: cancelSelectTextDraw
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_cancelSelectTextDraw
(JNIEnv *, jclass, jint playerid) {
CancelSelectTextDraw(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: createExplosionForPlayer
* Signature: (IFFFIF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createExplosionForPlayer
(JNIEnv *, jclass, jint playerid, jfloat x, jfloat y, jfloat z, jint type, jfloat radius) {
CreateExplosionForPlayer(playerid, x, y, z, type, radius);
}
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerVarNameAtIndex
(JNIEnv *env, jclass, jint index) {
char varname[64];
auto len = 0;
GetSVarNameAtIndex(index, varname, len);
return mbs2wcs(env, Shoebill::GetInstance().getServerCodepage(), varname, len);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: sendClientMessage
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendClientMessage
(JNIEnv *env, jclass, jint playerid, jint color, jstring message) {
assertNotNull(message, "message", __FUNCTION__);
auto msg = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), message, 144);
SendClientMessage(playerid, color, msg);
delete[] msg;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: sendClientMessageToAll
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendClientMessageToAll
(JNIEnv *env, jclass, jint color, jstring message) {
assertNotNull(message, "message", __FUNCTION__);
auto msg = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), message, 144);
SendClientMessageToAll(color, msg);
delete[] msg;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: sendPlayerMessageToPlayer
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendPlayerMessageToPlayer
(JNIEnv *env, jclass, jint playerid, jint senderid, jstring message) {
assertNotNull(message, "message", __FUNCTION__);
auto msg = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(senderid), message, 144);
SendPlayerMessageToPlayer(playerid, senderid, msg);
delete[] msg;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: sendPlayerMessageToAll
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendPlayerMessageToAll
(JNIEnv *env, jclass, jint senderid, jstring message) {
assertNotNull(message, "message", __FUNCTION__);
auto msg = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), message, 144);
SendPlayerMessageToAll(senderid, msg);
delete[] msg;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: sendDeathMessage
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendDeathMessage
(JNIEnv *, jclass, jint killerid, jint victimid, jint reason) {
SendDeathMessage(killerid, victimid, reason);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: sendDeathMessageToPlayer
* Signature: (IIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendDeathMessageToPlayer
(JNIEnv *, jclass, jint playerid, jint killer, jint killee, jint weapon) {
SendDeathMessageToPlayer(playerid, killer, killee, weapon);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gameTextForAll
* Signature: (Ljava/lang/String;II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gameTextForAll
(JNIEnv *env, jclass, jstring string, jint time, jint style) {
assertNotNull(string, "string", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), string, 256);
GameTextForAll(str, time, style);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gameTextForPlayer
* Signature: (ILjava/lang/String;II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gameTextForPlayer
(JNIEnv *env, jclass, jint playerid, jstring string, jint time, jint style) {
assertNotNull(string, "string", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), string, 256);
GameTextForPlayer(playerid, str, time, style);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setTimer
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setTimer
(JNIEnv *, jclass, jint /* index */, jint interval, jint repeating) {
return SetTimer(interval, repeating > 0, nullptr, nullptr);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: killTimer
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_killTimer
(JNIEnv *, jclass, jint timerid) {
KillTimer(timerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getMaxPlayers
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getMaxPlayers
(JNIEnv *, jclass) {
return GetMaxPlayers();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setGameModeText
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setGameModeText
(JNIEnv *env, jclass, jstring string) {
assertNotNull(string, "string", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), string, 128);
SetGameModeText(str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setTeamCount
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setTeamCount
(JNIEnv *, jclass, jint count) {
SetTeamCount(count);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addPlayerClass
* Signature: (IFFFFIIIIII)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addPlayerClass
(JNIEnv *, jclass, jint modelid, jfloat spawn_x, jfloat spawn_y, jfloat spawn_z,
jfloat z_angle, jint weapon1, jint weapon1_ammo, jint weapon2, jint weapon2_ammo, jint weapon3,
jint weapon3_ammo) {
return AddPlayerClass(modelid, spawn_x, spawn_y, spawn_z, z_angle,
weapon1, weapon1_ammo, weapon2, weapon2_ammo, weapon3, weapon3_ammo);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addPlayerClassEx
* Signature: (IIFFFFIIIIII)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addPlayerClassEx
(JNIEnv *, jclass, jint teamid, jint modelid, jfloat spawn_x, jfloat spawn_y, jfloat spawn_z,
jfloat z_angle, jint weapon1, jint weapon1_ammo, jint weapon2, jint weapon2_ammo, jint weapon3,
jint weapon3_ammo) {
return AddPlayerClassEx(teamid, modelid, spawn_x, spawn_y, spawn_z, z_angle,
weapon1, weapon1_ammo, weapon2, weapon2_ammo, weapon3, weapon3_ammo);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addStaticVehicle
* Signature: (IFFFFII)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addStaticVehicle
(JNIEnv *, jclass, jint modelid, jfloat spawn_x, jfloat spawn_y, jfloat spawn_z,
jfloat z_angle, jint color1, jint color2) {
return AddStaticVehicle(modelid, spawn_x, spawn_y, spawn_z, z_angle, color1, color2);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addStaticVehicleEx
* Signature: (IFFFFIII)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addStaticVehicleEx
(JNIEnv *, jclass, jint modelid, jfloat spawn_x, jfloat spawn_y, jfloat spawn_z,
jfloat z_angle, jint color1, jint color2, jint respawn_delay, jboolean addsiren) {
return AddStaticVehicleEx(modelid, spawn_x, spawn_y, spawn_z, z_angle, color1, color2, respawn_delay, addsiren);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addStaticPickup
* Signature: (IIFFFI)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addStaticPickup
(JNIEnv *, jclass, jint model, jint type, jfloat x, jfloat y, jfloat z, jint virtualworld) {
return AddStaticPickup(model, type, x, y, z, virtualworld);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createPickup
* Signature: (IIFFFI)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createPickup
(JNIEnv *, jclass, jint model, jint type, jfloat x, jfloat y, jfloat z, jint virtualworld) {
return CreatePickup(model, type, x, y, z, virtualworld);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: destroyPickup
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_destroyPickup
(JNIEnv *, jclass, jint pickup) {
DestroyPickup(pickup);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: showNameTags
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_showNameTags
(JNIEnv *, jclass, jboolean enabled) {
ShowNameTags(enabled);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: showPlayerMarkers
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_showPlayerMarkers
(JNIEnv *, jclass, jint mode) {
ShowPlayerMarkers(mode);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gameModeExit
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gameModeExit
(JNIEnv *, jclass) {
GameModeExit();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setWorldTime
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setWorldTime
(JNIEnv *, jclass, jint hour) {
SetWorldTime(hour);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getWeaponName
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getWeaponName
(JNIEnv *env, jclass, jint weaponid) {
char name[32];
GetWeaponName(weaponid, name, sizeof(name));
return env->NewStringUTF(name);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: enableTirePopping
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_enableTirePopping
(JNIEnv *, jclass, jboolean enabled) {
EnableTirePopping(enabled);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: enableVehicleFriendlyFire
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_enableVehicleFriendlyFire
(JNIEnv *, jclass) {
EnableVehicleFriendlyFire();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: allowInteriorWeapons
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_allowInteriorWeapons
(JNIEnv *, jclass, jboolean allow) {
AllowInteriorWeapons(allow);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setWeather
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setWeather
(JNIEnv *, jclass, jint weatherid) {
SetWeather(weatherid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setGravity
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setGravity
(JNIEnv *, jclass, jfloat gravity) {
SetGravity(gravity);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setDeathDropAmount
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setDeathDropAmount
(JNIEnv *, jclass, jint amount) {
SetDeathDropAmount(amount);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createExplosion
* Signature: (FFFIF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createExplosion
(JNIEnv *, jclass, jfloat x, jfloat y, jfloat z, jint type, jfloat radius) {
CreateExplosion(x, y, z, type, radius);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: enableZoneNames
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_enableZoneNames
(JNIEnv *, jclass, jboolean enabled) {
EnableZoneNames(enabled);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: usePlayerPedAnims
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_usePlayerPedAnims
(JNIEnv *, jclass) {
UsePlayerPedAnims();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: disableInteriorEnterExits
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disableInteriorEnterExits
(JNIEnv *, jclass) {
DisableInteriorEnterExits();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setNameTagDrawDistance
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setNameTagDrawDistance
(JNIEnv *, jclass, jfloat distance) {
SetNameTagDrawDistance(distance);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: disableNameTagLOS
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disableNameTagLOS
(JNIEnv *, jclass) {
DisableNameTagLOS();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: limitGlobalChatRadius
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_limitGlobalChatRadius
(JNIEnv *, jclass, jfloat chat_radius) {
LimitGlobalChatRadius(chat_radius);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: limitPlayerMarkerRadius
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_limitPlayerMarkerRadius
(JNIEnv *, jclass, jfloat chat_radius) {
LimitPlayerMarkerRadius(chat_radius);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: connectNPC
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_connectNPC
(JNIEnv *env, jclass, jstring name, jstring script) {
assertNotNull(name, "name", __FUNCTION__); assertNotNull(script, "script", __FUNCTION__);
auto str_name = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, 24);
auto str_script = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), script, 64);
ConnectNPC(str_name, str_script);
delete[] str_name;
delete[] str_script;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerNPC
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerNPC
(JNIEnv *, jclass, jint playerid) {
return (jboolean) IsPlayerNPC(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isPlayerAdmin
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isPlayerAdmin
(JNIEnv *, jclass, jint playerid) {
return (jboolean) IsPlayerAdmin(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: kick
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_kick
(JNIEnv *, jclass, jint playerid) {
Kick(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: ban
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_ban
(JNIEnv *, jclass, jint playerid) {
Ban(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: banEx
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_banEx
(JNIEnv *env, jclass, jint playerid, jstring reason) {
assertNotNull(reason, "reason", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), reason, 1024);
BanEx(playerid, str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: sendRconCommand
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sendRconCommand
(JNIEnv *env, jclass, jstring cmd) {
assertNotNull(cmd, "cmd", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), cmd, 1024);
SendRconCommand(str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getServerVarAsString
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerVarAsString
(JNIEnv *env, jclass, jstring varname) {
assertNotNullReturn(varname, "varname", __FUNCTION__, NULL);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), varname, 64);
char var[2048];
GetServerVarAsString(str_varname, var, sizeof(var));
return mbs2wcs(env, Shoebill::GetInstance().getServerCodepage(), var, 2048);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setServerVarFloat
(JNIEnv *env, jclass, jstring varname, jfloat value) {
assertNotNull(varname, "varname", __FUNCTION__);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), varname, 64);
SetSVarFloat(str_varname, value);
delete[] str_varname;
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setServerVarInt
(JNIEnv *env, jclass, jstring varname, jint value) {
assertNotNull(varname, "varname", __FUNCTION__);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), varname, 64);
SetSVarInt(str_varname, value);
delete[] str_varname;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getServerVarAsInt
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerVarAsInt
(JNIEnv *env, jclass, jstring varname) {
assertNotNullReturn(varname, "varname", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), varname, 64);
auto ret = GetServerVarAsInt(str_varname);
delete[] str_varname;
return ret;
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setServerVarString
(JNIEnv *env, jclass, jstring varname, jstring value) {
assertNotNull(varname, "varname", __FUNCTION__); assertNotNull(value, "value", __FUNCTION__);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), varname, 64);
auto str_value = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), value, 2048);
SetSVarString(str_varname, str_value);
delete[] str_varname;
delete[] str_value;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getServerVarAsBool
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerVarAsFloat
(JNIEnv *env, jclass, jstring varname) {
assertNotNullReturn(varname, "varname", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), varname, 64);
auto ret = GetSVarFloat(str_varname);
delete[] str_varname;
return ret;
}
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_deleteServerVar
(JNIEnv *env, jclass, jstring varname) {
assertNotNullReturn(varname, "varname", __FUNCTION__, false);
auto str_varname = env->GetStringUTFChars(varname, nullptr);
auto result = DeleteSVar(str_varname);
env->ReleaseStringUTFChars(varname, str_varname);
return (jboolean) result;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerVarsUpperIndex
(JNIEnv *env, jclass) {
return GetSVarsUpperIndex();
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerVarType
(JNIEnv *env, jclass, jstring varname) {
assertNotNullReturn(varname, "varname", __FUNCTION__, 0);
auto str_varname = env->GetStringUTFChars(varname, nullptr);
auto result = GetSVarType(str_varname);
env->ReleaseStringUTFChars(varname, str_varname);
return result;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerNetworkStats
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerNetworkStats
(JNIEnv *env, jclass, jint playerid) {
char retstr[2048];
GetPlayerNetworkStats(playerid, retstr, sizeof(retstr));
return mbs2wcs(env, Shoebill::GetInstance().getServerCodepage(), retstr, 2048);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getNetworkStats
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getNetworkStats
(JNIEnv *env, jclass) {
char retstr[2048];
GetNetworkStats(retstr, sizeof(retstr));
return mbs2wcs(env, Shoebill::GetInstance().getServerCodepage(), retstr, 2048);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerVersion
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerVersion
(JNIEnv *env, jclass, jint playerid) {
char str[128];
GetPlayerVersion(playerid, str, sizeof(str));
return env->NewStringUTF(str);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: getServerTickRate
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getServerTickRate
(JNIEnv *, jclass) {
return GetServerTickRate();
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_GetConnectedTime
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1GetConnectedTime
(JNIEnv *, jclass, jint playerid) {
return NetStats_GetConnectedTime(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_MessagesReceived
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1MessagesReceived
(JNIEnv *, jclass, jint playerid) {
return NetStats_MessagesReceived(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_BytesReceived
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1BytesReceived
(JNIEnv *, jclass, jint playerid) {
return NetStats_BytesReceived(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_MessagesSent
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1MessagesSent
(JNIEnv *, jclass, jint playerid) {
return NetStats_MessagesSent(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_BytesSent
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1BytesSent
(JNIEnv *, jclass, jint playerid) {
return NetStats_BytesSent(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_MessagesRecvPerSecond
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1MessagesRecvPerSecond
(JNIEnv *, jclass, jint playerid) {
return NetStats_MessagesRecvPerSecond(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_PacketLossPercent
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1PacketLossPercent
(JNIEnv *, jclass, jint playerid) {
return NetStats_PacketLossPercent(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_ConnectionStatus
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1ConnectionStatus
(JNIEnv *, jclass, jint playerid) {
return NetStats_ConnectionStatus(playerid);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: netStats_GetIpPort
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_netStats_1GetIpPort
(JNIEnv *env, jclass, jint playerid) {
char ipPort[24];
NetStats_GetIpPort(playerid, ipPort, sizeof(ipPort));
return env->NewStringUTF(ipPort);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: blockIpAddress
* Signature: (Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_blockIpAddress
(JNIEnv *env, jclass, jstring ip, jint timeMs) {
assertNotNull(ip, "ip", __FUNCTION__);
auto ip_str = env->GetStringUTFChars(ip, nullptr);
BlockIpAddress(ip_str, timeMs);
env->ReleaseStringUTFChars(ip, ip_str);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: unBlockIpAddress
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_unBlockIpAddress
(JNIEnv *env, jclass, jstring ip) {
assertNotNull(ip, "ip", __FUNCTION__);
auto ip_str = env->GetStringUTFChars(ip, nullptr);
UnBlockIpAddress(ip_str);
env->ReleaseStringUTFChars(ip, ip_str);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createMenu
* Signature: (Ljava/lang/String;IFFFF)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createMenu
(JNIEnv *env, jclass, jstring title, jint columns, jfloat x, jfloat y, jfloat col1width, jfloat col2width) {
assertNotNullReturn(title, "title", __FUNCTION__, 0);
auto menuTitle = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), title, 32);
auto ret = CreateMenu(menuTitle, columns, x, y, col1width, col2width);
delete[] menuTitle;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: destroyMenu
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_destroyMenu
(JNIEnv *, jclass, jint menuid) {
DestroyMenu(menuid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addMenuItem
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addMenuItem
(JNIEnv *env, jclass, jint menuid, jint column, jstring menutext) {
assertNotNull(menutext, "menutext", __FUNCTION__);
auto menuText = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), menutext, 32);
AddMenuItem(menuid, column, menuText);
delete[] menuText;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setMenuColumnHeader
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setMenuColumnHeader
(JNIEnv *env, jclass, jint menuid, jint column, jstring columnheader) {
assertNotNull(columnheader, "columnheader", __FUNCTION__);
auto header = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), columnheader, 32);
AddMenuItem(menuid, column, header);
delete[] header;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: showMenuForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_showMenuForPlayer
(JNIEnv *, jclass, jint menuid, jint playerid) {
ShowMenuForPlayer(menuid, playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: hideMenuForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_hideMenuForPlayer
(JNIEnv *, jclass, jint menuid, jint playerid) {
HideMenuForPlayer(menuid, playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isValidMenu
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isValidMenu
(JNIEnv *, jclass, jint menuid) {
return (jboolean) IsValidMenu(menuid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: disableMenu
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disableMenu
(JNIEnv *, jclass, jint menuid) {
DisableMenu(menuid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: disableMenuRow
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disableMenuRow
(JNIEnv *, jclass, jint menuid, jint row) {
DisableMenuRow(menuid, row);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getPlayerMenu
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerMenu
(JNIEnv *, jclass, jint playerid) {
return GetPlayerMenu(playerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawCreate
* Signature: (FFLjava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawCreate
(JNIEnv *env, jclass, jfloat x, jfloat y, jstring text) {
assertNotNullReturn(text, "text", __FUNCTION__, 0);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), text, 1024);
auto ret = TextDrawCreate(x, y, str);
delete[] str;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawDestroy
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawDestroy
(JNIEnv *, jclass, jint textid) {
TextDrawDestroy(textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawLetterSize
* Signature: (IFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawLetterSize
(JNIEnv *, jclass, jint textid, jfloat x, jfloat y) {
TextDrawLetterSize(textid, x, y);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawTextSize
* Signature: (IFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawTextSize
(JNIEnv *, jclass, jint textid, jfloat x, jfloat y) {
TextDrawTextSize(textid, x, y);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawAlignment
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawAlignment
(JNIEnv *, jclass, jint textid, jint alignment) {
TextDrawAlignment(textid, alignment);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawColor
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawColor
(JNIEnv *, jclass, jint textid, jint color) {
TextDrawColor(textid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawUseBox
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawUseBox
(JNIEnv *, jclass, jint textid, jboolean use) {
TextDrawUseBox(textid, use);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawBoxColor
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawBoxColor
(JNIEnv *, jclass, jint textid, jint color) {
TextDrawBoxColor(textid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawSetShadow
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetShadow
(JNIEnv *, jclass, jint textid, jint size) {
TextDrawSetShadow(textid, size);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawSetOutline
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetOutline
(JNIEnv *, jclass, jint textid, jint size) {
TextDrawSetOutline(textid, size);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawBackgroundColor
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawBackgroundColor
(JNIEnv *, jclass, jint textid, jint color) {
TextDrawBackgroundColor(textid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawFont
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawFont
(JNIEnv *, jclass, jint textid, jint font) {
TextDrawFont(textid, font);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawSetProportional
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetProportional
(JNIEnv *, jclass, jint textid, jint set) {
TextDrawSetProportional(textid, (bool) set);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawSetSelectable
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetSelectable
(JNIEnv *, jclass, jint textid, jint set) {
TextDrawSetSelectable(textid, (bool) set);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawShowForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawShowForPlayer
(JNIEnv *, jclass, jint playerid, jint textid) {
TextDrawShowForPlayer(playerid, textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawHideForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawHideForPlayer
(JNIEnv *, jclass, jint playerid, jint textid) {
TextDrawHideForPlayer(playerid, textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawShowForAll
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawShowForAll
(JNIEnv *, jclass, jint textid) {
TextDrawShowForAll(textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawHideForAll
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawHideForAll
(JNIEnv *, jclass, jint textid) {
TextDrawHideForAll(textid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: textDrawSetString
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetString
(JNIEnv *env, jclass, jint textid, jstring string) {
assertNotNull(string, "string", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), string, 1024);
TextDrawSetString(textid, str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: textDrawSetPreviewModel
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetPreviewModel
(JNIEnv *, jclass, jint textid, jint modelindex) {
TextDrawSetPreviewModel(textid, modelindex);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: textDrawSetPreviewRot
* Signature: (IFFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetPreviewRot
(JNIEnv *, jclass, jint textid, jfloat fRotX, jfloat fRotY, jfloat fRotZ, jfloat fZoom) {
TextDrawSetPreviewRot(textid, fRotX, fRotY, fRotZ, fZoom);
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: textDrawSetPreviewVehCol
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_textDrawSetPreviewVehCol
(JNIEnv *, jclass, jint textid, jint color1, jint color2) {
TextDrawSetPreviewVehCol(textid, color1, color2);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneCreate
* Signature: (FFFF)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneCreate
(JNIEnv *, jclass, jfloat minx, jfloat miny, jfloat maxx, jfloat maxy) {
return GangZoneCreate(minx, miny, maxx, maxy);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneDestroy
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneDestroy
(JNIEnv *, jclass, jint zoneid) {
GangZoneDestroy(zoneid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneShowForPlayer
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneShowForPlayer
(JNIEnv *, jclass, jint playerid, jint zoneid, jint color) {
GangZoneShowForPlayer(playerid, zoneid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneShowForAll
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneShowForAll
(JNIEnv *, jclass, jint zoneid, jint color) {
GangZoneShowForAll(zoneid, color);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneHideForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneHideForPlayer
(JNIEnv *, jclass, jint playerid, jint zoneid) {
GangZoneHideForPlayer(playerid, zoneid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneHideForAll
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneHideForAll
(JNIEnv *, jclass, jint zoneid) {
GangZoneHideForAll(zoneid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneFlashForPlayer
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneFlashForPlayer
(JNIEnv *, jclass, jint playerid, jint zoneid, jint flashcolor) {
GangZoneFlashForPlayer(playerid, zoneid, flashcolor);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneFlashForAll
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneFlashForAll
(JNIEnv *, jclass, jint zoneid, jint flashcolor) {
GangZoneFlashForAll(zoneid, flashcolor);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneStopFlashForPlayer
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneStopFlashForPlayer
(JNIEnv *, jclass, jint playerid, jint zoneid) {
GangZoneStopFlashForPlayer(playerid, zoneid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: gangZoneStopFlashForAll
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_gangZoneStopFlashForAll
(JNIEnv *, jclass, jint zoneid) {
GangZoneStopFlashForAll(zoneid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: create3DTextLabel
* Signature: (Ljava/lang/String;IFFFFIZ)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_create3DTextLabel
(JNIEnv *env, jclass, jstring text, jint color, jfloat x, jfloat y, jfloat z,
jfloat drawDistance, jint worldid, jboolean testLOS) {
assertNotNullReturn(text, "text", __FUNCTION__, 0);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), text, 1024);
auto ret = Create3DTextLabel(str, color, x, y, z, drawDistance, worldid, testLOS);
delete[] str;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: delete3DTextLabel
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_delete3DTextLabel
(JNIEnv *, jclass, jint id) {
Delete3DTextLabel(id);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attach3DTextLabelToPlayer
* Signature: (IIFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attach3DTextLabelToPlayer
(JNIEnv *, jclass, jint id, jint playerid, jfloat offsetX, jfloat offsetY, jfloat offsetZ) {
Attach3DTextLabelToPlayer(id, playerid, offsetX, offsetY, offsetZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attach3DTextLabelToVehicle
* Signature: (IIFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attach3DTextLabelToVehicle
(JNIEnv *, jclass, jint id, jint vehicleid, jfloat offsetX, jfloat offsetY, jfloat offsetZ) {
Attach3DTextLabelToVehicle(id, vehicleid, offsetX, offsetY, offsetZ);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: update3DTextLabelText
* Signature: (IILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_update3DTextLabelText
(JNIEnv *env, jclass, jint id, jint color, jstring text) {
assertNotNull(text, "text", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), text, 1024);
Update3DTextLabelText(id, color, str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createPlayer3DTextLabel
* Signature: (ILjava/lang/String;IFFFFIIZ)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createPlayer3DTextLabel
(JNIEnv *env, jclass, jint playerid, jstring text, jint color, jfloat x, jfloat y, jfloat z,
jfloat drawDistance, jint attachedplayerid, jint attachedvehicleid, jboolean testLOS) {
assertNotNullReturn(text, "text", __FUNCTION__, 0);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), text, 1024);
auto ret = CreatePlayer3DTextLabel(playerid, str, color, x, y, z, drawDistance, attachedplayerid, attachedvehicleid,
testLOS);
delete[] str;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: deletePlayer3DTextLabel
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_deletePlayer3DTextLabel
(JNIEnv *, jclass, jint playerid, jint id) {
DeletePlayer3DTextLabel(playerid, id);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: updatePlayer3DTextLabelText
* Signature: (IIILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_updatePlayer3DTextLabelText
(JNIEnv *env, jclass, jint playerid, jint id, jint color, jstring text) {
assertNotNull(text, "text", __FUNCTION__);
auto str = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), text, 1024);
UpdatePlayer3DTextLabelText(playerid, id, color, str);
delete[] str;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: showPlayerDialog
* Signature: (IIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_showPlayerDialog
(JNIEnv *env, jclass, jint playerid, jint dialogid, jint style,
jstring caption, jstring info, jstring button1, jstring button2) {
assertNotNullReturn(caption, "caption", __FUNCTION__, 0); assertNotNullReturn(info, "info", __FUNCTION__, 0);
assertNotNullReturn(button1, "button1", __FUNCTION__, 0); assertNotNullReturn(button2, "button2", __FUNCTION__, 0);
auto codepage = Shoebill::GetInstance().getPlayerCodepage(playerid);
auto str_caption = wcs2mbs(env, codepage, caption, 64), str_info = wcs2mbs(env, codepage, info, 1024),
str_button1 = wcs2mbs(env, codepage, button1, 32), str_button2 = wcs2mbs(env, codepage, button2, 32);
int ret = ShowPlayerDialog(playerid, dialogid, style, str_caption, str_info, str_button1, str_button2);
delete[] str_caption;
delete[] str_info;
delete[] str_button1;
delete[] str_button2;
return ret;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: createVehicle
* Signature: (IFFFFIII)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createVehicle
(JNIEnv *, jclass, jint model, jfloat x, jfloat y, jfloat z, jfloat rotation, jint color1, jint color2,
jint respawnDelay, jboolean addsiren) {
return CreateVehicle(model, x, y, z, rotation, color1, color2, respawnDelay, addsiren);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: destroyVehicle
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_destroyVehicle
(JNIEnv *, jclass, jint vehicleid) {
DestroyVehicle(vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isVehicleStreamedIn
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isVehicleStreamedIn
(JNIEnv *, jclass, jint vehicleid, jint forplayerid) {
return (jboolean) IsVehicleStreamedIn(vehicleid, forplayerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehiclePos
* Signature: (ILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehiclePos
(JNIEnv *env, jclass, jint vehicleid, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetVehiclePos(vehicleid, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehiclePos
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehiclePos
(JNIEnv *, jclass, jint vehicleid, jfloat x, jfloat y, jfloat z) {
SetVehiclePos(vehicleid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleZAngle
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleZAngle
(JNIEnv *, jclass, jint vehicleid) {
float angle;
GetVehicleZAngle(vehicleid, &angle);
return angle;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleRotationQuat
* Signature: (ILnet/gtaun/shoebill/data/Quaternion;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleRotationQuat
(JNIEnv *env, jclass, jint vehicleid, jobject quat) {
assertNotNull(quat, "quat", __FUNCTION__);
static auto cls = env->GetObjectClass(quat);
static auto fidW = env->GetFieldID(cls, "w", "F");
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float w, x, y, z;
GetVehicleRotationQuat(vehicleid, &w, &x, &y, &z);
env->SetFloatField(quat, fidW, w);
env->SetFloatField(quat, fidX, x);
env->SetFloatField(quat, fidY, y);
env->SetFloatField(quat, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleZAngle
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleZAngle
(JNIEnv *, jclass, jint vehicleid, jfloat angle) {
SetVehicleZAngle(vehicleid, angle);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleParamsForPlayer
* Signature: (IIZZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleParamsForPlayer
(JNIEnv *, jclass, jint vehicleid, jint playerid, jboolean objective, jboolean doorslocked) {
SetVehicleParamsForPlayer(vehicleid, playerid, objective, doorslocked);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: manualVehicleEngineAndLights
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_manualVehicleEngineAndLights
(JNIEnv *, jclass) {
ManualVehicleEngineAndLights();
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleParamsEx
* Signature: (IZZZZZZZ)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleParamsEx
(JNIEnv *, jclass, jint vehicleid, jint engine, jint lights,
jint alarm, jint doors, jint bonnet, jint boot, jint objective) {
//-1 is == true eventhough it should be false. Workaround:
SetVehicleParamsEx(vehicleid, engine == 1, lights == 1, alarm == 1,
doors == 1, bonnet == 1, boot == 1, objective == 1);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleParamsEx
* Signature: (ILnet/gtaun/shoebill/object/impl/VehicleParamImpl;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleParamsEx
(JNIEnv *env, jclass, jint vehicleid, jobject state) {
assertNotNull(state, "state", __FUNCTION__);
static auto cls = env->GetObjectClass(state);
static auto fidEngine = env->GetFieldID(cls, "engine", "I");
static auto fidLights = env->GetFieldID(cls, "lights", "I");
static auto fidAlarm = env->GetFieldID(cls, "alarm", "I");
static auto fidDoors = env->GetFieldID(cls, "doors", "I");
static auto fidBonnet = env->GetFieldID(cls, "bonnet", "I");
static auto fidBoot = env->GetFieldID(cls, "boot", "I");
static auto fidObjective = env->GetFieldID(cls, "objective", "I");
int engine, lights, alarm, doors, bonnet, boot, objective;
GetVehicleParamsEx(vehicleid, &engine, &lights, &alarm, &doors, &bonnet, &boot, &objective);
env->SetIntField(state, fidEngine, engine);
env->SetIntField(state, fidLights, lights);
env->SetIntField(state, fidAlarm, alarm);
env->SetIntField(state, fidDoors, doors);
env->SetIntField(state, fidBonnet, bonnet);
env->SetIntField(state, fidBoot, boot);
env->SetIntField(state, fidObjective, objective);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleToRespawn
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleToRespawn
(JNIEnv *, jclass, jint vehicleid) {
SetVehicleToRespawn(vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: linkVehicleToInterior
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_linkVehicleToInterior
(JNIEnv *, jclass, jint vehicleid, jint interiorid) {
LinkVehicleToInterior(vehicleid, interiorid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: addVehicleComponent
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_addVehicleComponent
(JNIEnv *, jclass, jint vehicleid, jint componentid) {
AddVehicleComponent(vehicleid, componentid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: removeVehicleComponent
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_removeVehicleComponent
(JNIEnv *, jclass, jint vehicleid, jint componentid) {
RemoveVehicleComponent(vehicleid, componentid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: changeVehicleColor
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_changeVehicleColor
(JNIEnv *, jclass, jint vehicleid, jint color1, jint color2) {
ChangeVehicleColor(vehicleid, color1, color2);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: changeVehiclePaintjob
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_changeVehiclePaintjob
(JNIEnv *, jclass, jint vehicleid, jint paintjobid) {
ChangeVehiclePaintjob(vehicleid, paintjobid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleHealth
* Signature: (IF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleHealth
(JNIEnv *, jclass, jint vehicleid, jfloat health) {
SetVehicleHealth(vehicleid, health);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleHealth
* Signature: (I)F
*/
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleHealth
(JNIEnv *, jclass, jint vehicleid) {
float health;
GetVehicleHealth(vehicleid, &health);
return health;
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: attachTrailerToVehicle
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_attachTrailerToVehicle
(JNIEnv *, jclass, jint trailerid, jint vehicleid) {
AttachTrailerToVehicle(trailerid, vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: detachTrailerFromVehicle
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_detachTrailerFromVehicle
(JNIEnv *, jclass, jint trailerid) {
DetachTrailerFromVehicle(trailerid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: isTrailerAttachedToVehicle
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isTrailerAttachedToVehicle
(JNIEnv *, jclass, jint vehicleid) {
return (jboolean) IsTrailerAttachedToVehicle(vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleTrailer
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleTrailer
(JNIEnv *, jclass, jint vehicleid) {
return GetVehicleTrailer(vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleNumberPlate
* Signature: (ILjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleNumberPlate
(JNIEnv *env, jclass, jint vehicleid, jstring numberplate) {
assertNotNull(numberplate, "numberplate", __FUNCTION__);
auto str_numberplate = env->GetStringUTFChars(numberplate, nullptr);
SetVehicleNumberPlate(vehicleid, str_numberplate);
env->ReleaseStringUTFChars(numberplate, str_numberplate);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleModel
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleModel
(JNIEnv *, jclass, jint vehicleid) {
return GetVehicleModel(vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleComponentInSlot
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleComponentInSlot
(JNIEnv *, jclass, jint vehicleid, jint slot) {
return GetVehicleComponentInSlot(vehicleid, slot);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleComponentType
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleComponentType
(JNIEnv *, jclass, jint component) {
return GetVehicleComponentType(component);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: repairVehicle
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_repairVehicle
(JNIEnv *, jclass, jint vehicleid) {
RepairVehicle(vehicleid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleVelocity
* Signature: (ILnet/gtaun/shoebill/data/Velocity;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleVelocity
(JNIEnv *env, jclass, jint vehicleid, jobject velocity) {
assertNotNull(velocity, "velocity", __FUNCTION__);
static auto cls = env->GetObjectClass(velocity);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetVehicleVelocity(vehicleid, &x, &y, &z);
env->SetFloatField(velocity, fidX, x);
env->SetFloatField(velocity, fidY, y);
env->SetFloatField(velocity, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleVelocity
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleVelocity
(JNIEnv *, jclass, jint vehicleid, jfloat x, jfloat y, jfloat z) {
SetVehicleVelocity(vehicleid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleAngularVelocity
* Signature: (IFFF)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleAngularVelocity
(JNIEnv *, jclass, jint vehicleid, jfloat x, jfloat y, jfloat z) {
SetVehicleAngularVelocity(vehicleid, x, y, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleDamageStatus
* Signature: (ILnet/gtaun/shoebill/object/impl/VehicleDamageImpl;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleDamageStatus
(JNIEnv *env, jclass, jint vehicleid, jobject damage) {
assertNotNull(damage, "damage", __FUNCTION__);
static auto cls = env->GetObjectClass(damage);
static auto fidPanels = env->GetFieldID(cls, "panels", "I");
static auto fidDoors = env->GetFieldID(cls, "doors", "I");
static auto fidLights = env->GetFieldID(cls, "lights", "I");
static auto fidTires = env->GetFieldID(cls, "tires", "I");
int panels, doors, lights, tires;
GetVehicleDamageStatus(vehicleid, &panels, &doors, &lights, &tires);
env->SetIntField(damage, fidPanels, panels);
env->SetIntField(damage, fidDoors, doors);
env->SetIntField(damage, fidLights, lights);
env->SetIntField(damage, fidTires, tires);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: updateVehicleDamageStatus
* Signature: (IIIII)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_updateVehicleDamageStatus
(JNIEnv *, jclass, jint vehicleid, jint panels, jint doors, jint lights, jint tires) {
UpdateVehicleDamageStatus(vehicleid, panels, doors, lights, tires);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleModelInfo
* Signature: (IILnet/gtaun/shoebill/data/Vector3D;)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleModelInfo
(JNIEnv *env, jclass, jint vehiclemodel, jint infotype, jobject vector3d) {
assertNotNull(vector3d, "vector3d", __FUNCTION__);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetVehicleModelInfo(vehiclemodel, infotype, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: setVehicleVirtualWorld
* Signature: (II)V
*/
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleVirtualWorld
(JNIEnv *, jclass, jint vehicleid, jint worldid) {
SetVehicleVirtualWorld(vehicleid, worldid);
}
/*
* Class: net_gtaun_shoebill_samp_SampNativeFunction
* Method: getVehicleVirtualWorld
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleVirtualWorld
(JNIEnv *, jclass, jint vehicleid) {
return GetVehicleVirtualWorld(vehicleid);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPublic
(JNIEnv *env, jclass, jint pAmx, jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto amx = reinterpret_cast<AMX *>(pAmx);
int index;
auto functionName = env->GetStringUTFChars(name, nullptr);
amx_FindPublic(amx, functionName, &index);
env->ReleaseStringUTFChars(name, functionName);
return index;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getNative
(JNIEnv *env, jclass, jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto functionName = env->GetStringUTFChars(name, nullptr);
auto native = sampgdk_FindNative(functionName);
env->ReleaseStringUTFChars(name, functionName);
return reinterpret_cast<int>(native);
}
JNIEXPORT jobject JNICALL Java_net_gtaun_shoebill_SampNativeFunction_callFunction(JNIEnv *env, jclass, jint pAmx,
jint index, jint returnType,
jobjectArray args,
jobjectArray types) {
assertNotNullReturn(args, "args", __FUNCTION__, NULL); assertNotNullReturn(types, "txdname", __FUNCTION__, NULL);
auto amx = (AMX *) pAmx;
cell retval;
int arrayLength = env->GetArrayLength(args);
auto native = reinterpret_cast<AMX_NATIVE>(index);
cell params[33];
std::vector<cell> stringCells;
std::map<std::pair<jobject, std::string>, std::pair<cell *, cell>> references;
params[0] = (cell) (arrayLength * sizeof(cell));
for (auto i = 0; i < arrayLength; i++) {
auto object = env->GetObjectArrayElement(args, i);
auto objectClass = env->GetObjectClass(object);
auto mid = env->GetMethodID(objectClass, "toString", "()Ljava/lang/String;");
if (!mid) {
sampgdk_logprintf("[Shoebill] Error while getting toString() method.");
return nullptr;
}
auto classNameString = static_cast<jstring>(env->CallObjectMethod(objectClass, mid));
auto cstr = env->GetStringUTFChars(classNameString, nullptr);
auto className = std::string(cstr);
if (className == "class java.lang.String") {
auto javaString = static_cast<jstring>(object);
auto wmsg = env->GetStringChars(javaString, nullptr);
auto len = env->GetStringLength(javaString);
char str[1024];
wcs2mbs(Shoebill::GetInstance().getServerCodepage(), wmsg, len, str, sizeof(str));
env->ReleaseStringChars(javaString, wmsg);
cell strCel;
amx_PushString(amx, &strCel, nullptr, str, 0, 0);
params[i + 1] = strCel;
stringCells.push_back(strCel);
} else if (className == "class java.lang.Integer") {
auto ajf = env->GetMethodID(objectClass, "intValue", "()I");
int integer = env->CallIntMethod(object, ajf);
params[i + 1] = integer;
} else if (className == "class java.lang.Float") {
auto bjf = env->GetMethodID(objectClass, "floatValue", "()F");
auto ffloat = env->CallFloatMethod(object, bjf);
params[i + 1] = amx_ftoc(ffloat);
} else if (className == "class net.gtaun.Shoebill::GetInstance().amx.types.ReferenceInt" ||
className == "class net.gtaun.Shoebill::GetInstance().amx.types.ReferenceFloat") {
cell amx_addr, *phys_addr;
amx_Allot(amx, 1, &amx_addr, &phys_addr);
params[i + 1] = amx_addr;
references[std::pair<jobject, std::string>(object, className)] = std::pair<cell *, cell>(
phys_addr, amx_addr);
} else if (className == "class net.gtaun.Shoebill::GetInstance().amx.types.ReferenceString") {
auto lengthMethodId = env->GetMethodID(objectClass, "getLength", "()I");
auto length = env->CallIntMethod(object, lengthMethodId);
cell amx_str, *amx_str_phys;
amx_Allot(amx, length, &amx_str, &amx_str_phys);
params[i + 1] = amx_str;
references[std::pair<jobject, std::string>(object, className)] = std::pair<cell *, cell>(
amx_str_phys, amx_str);
}
env->ReleaseStringUTFChars(classNameString, cstr);
}
retval = native(amx, params);
auto iterator = references.begin();
while (iterator != references.end()) {
auto className = iterator->first.second;
auto object = iterator->first.first;
auto type = env->GetObjectClass(object);
if (className == "class net.gtaun.Shoebill::GetInstance().amx.types.ReferenceInt") {
auto methodId = env->GetMethodID(type, "setValue", "(I)V");
env->CallVoidMethod(object, methodId, *iterator->second.first);
} else if (className == "class net.gtaun.Shoebill::GetInstance().amx.types.ReferenceFloat") {
auto methodId = env->GetMethodID(type, "setValue", "(F)V");
auto result = amx_ctof(*iterator->second.first);
env->CallVoidMethod(object, methodId, result);
} else if (className == "class net.gtaun.Shoebill::GetInstance().amx.types.ReferenceString") {
auto methodId = env->GetMethodID(type, "setValue", "(Ljava/lang/String;)V");
char *text = nullptr;
amx_StrParam(amx, iterator->second.second, text);
jchar wstr[1024];
auto len = mbs2wcs(Shoebill::GetInstance().getServerCodepage(), text, -1, wstr,
sizeof(wstr) / sizeof(wstr[0]));
auto newText = env->NewString(wstr, len);
env->CallVoidMethod(object, methodId, newText);
}
amx_Release(amx, iterator->second.second);
++iterator;
}
for (auto str : stringCells) amx_Release(amx, str);
stringCells.clear();
references.clear();
return makeObjectFromReturnType(env, returnType, amx, retval);
}
JNIEXPORT jobject JNICALL Java_net_gtaun_shoebill_SampNativeFunction_callPublic
(JNIEnv *env, jclass, jint pAmx, jint idx, jint returnType, jobjectArray args, jobjectArray types) {
assertNotNullReturn(args, "args", __FUNCTION__, NULL); assertNotNullReturn(types, "types", __FUNCTION__, NULL);
auto amx = reinterpret_cast<AMX *>(pAmx);
auto shoebill = Shoebill::GetInstance();
cell retval;
std::vector<std::pair<cell, char *>> stringCells;
std::vector<std::pair<cell *, int>> cellArrays;
std::map<std::pair<int, char *>, std::pair<cell *, cell>> references;
int arrayLength = env->GetArrayLength(args);
amx->paramcount = 0;
for (auto i = arrayLength - 1; i >= 0; i--) {
auto str_type = wcs2mbs(env, shoebill.getServerCodepage(), (jstring) env->GetObjectArrayElement(types, i), 8);
auto type = std::string(str_type);
auto object = env->GetObjectArrayElement(args, i);
if (type == "s") {
cell strCell;
auto content = wcs2mbs(env, shoebill.getServerCodepage(), (jstring) object, 1024);
amx_PushString(amx, &strCell, nullptr, content, 0, 0);
stringCells.push_back(std::pair<cell, char *>(strCell, content));
} else if (type == "i") {
auto value = getIntegerFromObject(env, object);
amx_Push(amx, value);
} else if (type == "f") {
auto value = getFloatFromObject(env, object);
amx_Push(amx, amx_ftoc(value));
} else if (type == "ri" || type == "rf") {
cell amx_addr, *phys_addr;
amx_Allot(amx, 1, &amx_addr, &phys_addr);
amx_Push(amx, amx_addr);
references[std::pair<int, char *>(i, str_type)] = std::pair<cell *, cell>(phys_addr, amx_addr);
} else if (type == "rs") {
auto objectClass = env->GetObjectClass(object);
auto lengthMethodId = env->GetMethodID(objectClass, "getLength", "()I");
auto length = env->CallIntMethod(object, lengthMethodId);
cell amx_str, *amx_str_phys;
amx_Allot(amx, length, &amx_str, &amx_str_phys);
amx_Push(amx, amx_str);
references[std::pair<int, char *>(i, str_type)] = std::pair<cell *, cell>(amx_str_phys, amx_str);
} else if (type.find("[]") != std::string::npos) {
auto javaArray = (jobjectArray) object;
int javaArrayLength = env->GetArrayLength(javaArray);
auto array = new cell[javaArrayLength];
if (type == "i[]") {
for (auto a = 0; a < javaArrayLength; a++) {
cell amx_addr, *phys_addr;
amx_Allot(amx, 1, &amx_addr, &phys_addr);
array[a] = amx_addr;
*phys_addr = getIntegerFromObject(env, env->GetObjectArrayElement(javaArray, a));
}
} else if (type == "f[]") {
for (auto a = 0; a < javaArrayLength; a++) {
auto value = getFloatFromObject(env, env->GetObjectArrayElement(javaArray, a));
array[a] = amx_ftoc(value);
}
} else if (type == "s[]") {
for (auto a = 0; a < javaArrayLength; a++) {
auto text = wcs2mbs(env, shoebill.getServerCodepage(),
(jstring) env->GetObjectArrayElement(javaArray, a), 1024);
auto amxString = amx_NewString(amx, text);
array[a] = amxString;
stringCells.push_back(std::pair<cell, char *>(amxString, text));
}
}
references[std::pair<int, char *>(i, str_type)] = std::pair<cell *, cell>(array, javaArrayLength);
cellArrays.push_back(std::pair<cell *, int>(array, javaArrayLength));
cell tmpAddress;
amx_Push(amx, javaArrayLength);
amx_PushArray(amx, &tmpAddress, nullptr, array, javaArrayLength);
}
}
amx_Exec(amx, &retval, idx);
for (auto iterator : references) {
auto str_type = iterator.first.second;
auto type = std::string(str_type);
auto object = env->GetObjectArrayElement(args, iterator.first.first);
auto objectClass = env->GetObjectClass(object);
if (type == "ri") {
auto methodId = env->GetMethodID(objectClass, "setValue", "(I)V");
env->CallVoidMethod(object, methodId, *iterator.second.first);
} else if (type == "rf") {
auto methodId = env->GetMethodID(objectClass, "setValue", "(F)V");
auto result = amx_ctof(*iterator.second.first);
env->CallVoidMethod(object, methodId, result);
} else if (type == "rs") {
auto methodId = env->GetMethodID(objectClass, "setValue", "(Ljava/lang/String;)V");
char text[1024];
amx_GetString(amx, iterator.second.second, text, 1024);
env->CallVoidMethod(object, methodId, mbs2wcs(env, shoebill.getServerCodepage(), text, 1024));
} else if (type == "i[]") {
auto javaArrayLength = iterator.second.second; //iterator.second.second will return the array length for array refs.
auto javaIntegerArray = (jobjectArray) env->GetObjectArrayElement(args, iterator.first.first);
for (auto i = 0; i < javaArrayLength; i++) {
env->SetObjectArrayElement(javaIntegerArray, i, makeJavaInteger(env, *iterator.second.first));
}
} else if (type == "f[]") {
auto javaArrayLength = iterator.second.second;
auto javaFloatArray = (jobjectArray) env->GetObjectArrayElement(args, iterator.first.first);
for (auto i = 0; i < javaArrayLength; i++) {
auto value = amx_ctof(*(iterator.second.first + i));
sampgdk_logprintf("Val: %f", value);
env->SetObjectArrayElement(javaFloatArray, i, makeJavaFloat(env, value));
}
}
delete[] str_type;
amx_Release(amx, iterator.second.second);
}
for (auto it : stringCells) {
amx_Release(amx, it.first);
delete[] it.second;
}
for (auto it : cellArrays) delete[] it.first;
return makeObjectFromReturnType(env, returnType, amx, retval);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_restartShoebill
(JNIEnv *, jclass) {
Shoebill::GetInstance().Restart();
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: HookCallback
* Signature: (Ljava/lang/String;Ljava/lang/String)
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_hookCallback
(JNIEnv *env, jclass, jstring name, jobjectArray types) {
assertNotNullReturn(name, "name", __FUNCTION__, false); assertNotNullReturn(types, "types", __FUNCTION__, false);
static auto validClasses = {"s", "i", "f", "f[]", "i[]"};
auto callbackName = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, 64);
std::vector<std::string> classTypes;
int arrayLength = env->GetArrayLength(types);
for (auto i = 0; i < arrayLength; i++) {
auto string = (jstring) env->GetObjectArrayElement(types, i);
auto type = env->GetStringUTFChars(string, nullptr);
if (std::find(validClasses.begin(), validClasses.end(), type) == validClasses.end()) {
sampgdk_logprintf("[SHOEBILL] %s is not a valid type for hooking a callback (%s).", type, callbackName);
env->ReleaseStringUTFChars(string, type);
return (jboolean) false;
}
classTypes.push_back(std::string(type));
env->ReleaseStringUTFChars(string, type);
}
auto success = HookCallback(std::string(callbackName), classTypes);
env->ReleaseStringUTFChars(name, callbackName);
return (jboolean) success;
}
/*
* Class: net_gtaun_shoebill_SampNativeFunction
* Method: UnhookCallback
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_unhookCallback
(JNIEnv *env, jclass, jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, false);
auto callbackName = env->GetStringUTFChars(name, nullptr);
auto success = UnhookCallback(std::string(callbackName));
env->ReleaseStringUTFChars(name, callbackName);
return (jboolean) success;
}
JNIEXPORT jint JNICALL
Java_net_gtaun_shoebill_SampNativeFunction_applyActorAnimation(JNIEnv *env, jclass, jint actor, jstring animLib,
jstring animName,
jfloat fDelta, jint loop, jint lockX, jint lockY,
jint freeze, jint time) {
assertNotNullReturn(animLib, "animLib", __FUNCTION__, 0); assertNotNullReturn(animName, "animName", __FUNCTION__, 0);
auto animLibStr = env->GetStringUTFChars(animLib, nullptr);
auto animNameStr = env->GetStringUTFChars(animName, nullptr);
auto ret = ApplyActorAnimation(actor, animLibStr, animNameStr, fDelta, (bool) loop, (bool) lockX, (bool) lockY,
(bool) freeze, time);
env->ReleaseStringUTFChars(animLib, animLibStr);
env->ReleaseStringUTFChars(animName, animNameStr);
return ret;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_clearActorAnimations(JNIEnv *, jclass, jint actor) {
return ClearActorAnimations(actor);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_destroyActor(JNIEnv *, jclass, jint actor) {
return DestroyActor(actor);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_disableRemoteVehicleCollisions(JNIEnv *, jclass,
jint playerid,
jint disable) {
DisableRemoteVehicleCollisions(playerid, (bool) disable);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_enablePlayerCameraTarget(JNIEnv *, jclass,
jint playerid, jint enable) {
return EnablePlayerCameraTarget(playerid, (bool) enable);
}
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getActorFacingAngle(JNIEnv *, jclass, jint actor) {
float angle;
GetActorFacingAngle(actor, &angle);
return angle;
}
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getActorHealth(JNIEnv *, jclass, jint actor) {
float health;
GetActorHealth(actor, &health);
return health;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getActorPoolSize(JNIEnv *, jclass) {
return GetActorPoolSize();
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getActorPos(JNIEnv *env, jclass, jint actor,
jobject vector3d) {
assertNotNullReturn(vector3d, "vector3d", __FUNCTION__, 0);
static auto cls = env->GetObjectClass(vector3d);
static auto fidX = env->GetFieldID(cls, "x", "F");
static auto fidY = env->GetFieldID(cls, "y", "F");
static auto fidZ = env->GetFieldID(cls, "z", "F");
float x, y, z;
GetActorPos(actor, &x, &y, &z);
env->SetFloatField(vector3d, fidX, x);
env->SetFloatField(vector3d, fidY, y);
env->SetFloatField(vector3d, fidZ, z);
return 1;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getActorVirtualWorld(JNIEnv *, jclass, jint actor) {
return GetActorVirtualWorld(actor);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getObjectModel(JNIEnv *, jclass, jint objectId) {
return GetObjectModel(objectId);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraTargetActor(JNIEnv *, jclass,
jint player) {
return GetPlayerCameraTargetActor(player);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraTargetObject(JNIEnv *, jclass,
jint player) {
return GetPlayerCameraTargetObject(player);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraTargetPlayer(JNIEnv *, jclass,
jint player) {
return GetPlayerCameraTargetPlayer(player);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerCameraTargetVehicle(JNIEnv *, jclass,
jint player) {
return GetPlayerCameraTargetVehicle(player);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerObjectModel(JNIEnv *, jclass, jint player,
jint objectid) {
return GetPlayerObjectModel(player, objectid);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerTargetActor(JNIEnv *, jclass, jint player) {
return GetPlayerTargetActor(player);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleParamsCarDoors(JNIEnv *env, jclass,
jint vehicle,
jobject vehicleParams) {
assertNotNull(vehicleParams, "vehicleParams", __FUNCTION__);
static auto cls = env->GetObjectClass(vehicleParams);
static auto fidDriver = env->GetFieldID(cls, "driver", "I");
static auto fidPassenger = env->GetFieldID(cls, "passenger", "I");
static auto fidBackLeft = env->GetFieldID(cls, "backLeft", "I");
static auto fidBackRight = env->GetFieldID(cls, "backRight", "I");
int driver, passenger, backleft, backright;
GetVehicleParamsCarDoors(vehicle, &driver, &passenger, &backleft, &backright);
env->SetIntField(vehicleParams, fidDriver, driver);
env->SetIntField(vehicleParams, fidPassenger, passenger);
env->SetIntField(vehicleParams, fidBackLeft, backleft);
env->SetIntField(vehicleParams, fidBackRight, backright);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleParamsCarWindows(JNIEnv *env, jclass,
jint vehicle,
jobject vehicleParams) {
assertNotNull(vehicleParams, "vehicleParams", __FUNCTION__);
static auto cls = env->GetObjectClass(vehicleParams);
static auto fidDriver = env->GetFieldID(cls, "driver", "I");
static auto fidPassenger = env->GetFieldID(cls, "passenger", "I");
static auto fidBackLeft = env->GetFieldID(cls, "backLeft", "I");
static auto fidBackRight = env->GetFieldID(cls, "backRight", "I");
int driver, passenger, backleft, backright;
GetVehicleParamsCarWindows(vehicle, &driver, &passenger, &backleft, &backright);
env->SetIntField(vehicleParams, fidDriver, driver);
env->SetIntField(vehicleParams, fidPassenger, passenger);
env->SetIntField(vehicleParams, fidBackLeft, backleft);
env->SetIntField(vehicleParams, fidBackRight, backright);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehicleParamsSirenState(JNIEnv *, jclass,
jint vehicle) {
return GetVehicleParamsSirenState(vehicle);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getVehiclePoolSize(JNIEnv *, jclass) {
return GetVehiclePoolSize();
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isActorInvulnerable(JNIEnv *, jclass, jint actor) {
return IsActorInvulnerable(actor);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isActorStreamedIn(JNIEnv *, jclass, jint actor,
jint player) {
return IsActorStreamedIn(actor, player);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_isValidActor(JNIEnv *, jclass, jint actor) {
return IsValidActor(actor);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setActorFacingAngle(JNIEnv *, jclass, jint actor,
jfloat angle) {
return SetActorFacingAngle(actor, angle);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setActorHealth(JNIEnv *, jclass, jint actor,
jfloat health) {
return SetActorHealth(actor, health);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setActorInvulnerable(JNIEnv *, jclass, jint actor,
jboolean invulnerable) {
return SetActorInvulnerable(actor, invulnerable);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setActorPos(JNIEnv *, jclass, jint actor, jfloat x,
jfloat y, jfloat z) {
return SetActorPos(actor, x, y, z);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setActorVirtualWorld(JNIEnv *, jclass, jint actor,
jint virtualworld) {
return SetActorVirtualWorld(actor, virtualworld);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setObjectNoCameraCol(JNIEnv *, jclass, jint object) {
return SetObjectNoCameraCol(object);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setObjectsDefaultCameraCol(JNIEnv *, jclass,
jint disable) {
SetObjectsDefaultCameraCol((bool) disable);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPlayerObjectNoCameraCol(JNIEnv *, jclass,
jint playerid,
jint object) {
return SetPlayerObjectNoCameraCol(playerid, object);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleParamsCarDoors(JNIEnv *, jclass,
jint vehicle, jint driver,
jint passenger,
jint backleft,
jint backright) {
SetVehicleParamsCarDoors(vehicle, (bool) driver, (bool) passenger, (bool) backleft, (bool) backright);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setVehicleParamsCarWindows(JNIEnv *, jclass,
jint vehicle, jint driver,
jint passenger,
jint backleft,
jint backright) {
SetVehicleParamsCarWindows(vehicle, (bool) driver, (bool) passenger, (bool) backleft, (bool) backright);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_createActor(JNIEnv *, jclass, jint modelid, jfloat x,
jfloat y, jfloat z, jfloat rotation) {
return CreateActor(modelid, x, y, z, rotation);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPlayerPoolSize(JNIEnv *, jclass) {
return GetPlayerPoolSize();
}
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_unregisterFunction(JNIEnv *env, jclass,
jint amxHandle, jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, false);
auto amx = (AMX *) amxHandle;
auto functionName = env->GetStringUTFChars(name, nullptr);
auto functionString = std::string(functionName);
env->ReleaseStringUTFChars(name, functionName);
return (jboolean) AmxInstanceManager::GetInstance().UnregisterFunction(amx, functionString);
}
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_registerFunction(JNIEnv *env, jclass,
jint amxHandle, jstring name,
jobjectArray classes) {
assertNotNullReturn(name, "name", __FUNCTION__, false); assertNotNullReturn(classes, "classes", __FUNCTION__, false);
static auto validClasses = {"s", "i", "f", "f[]", "i[]"};
auto amx = (AMX *) amxHandle;
auto functionName = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, 64);
auto functionString = std::string(functionName);
delete[] functionName;
if (AmxInstanceManager::GetInstance().RegisteredFunctionExists(amx, functionString))
return (jboolean) false;
const int arrayLength = env->GetArrayLength(classes);
std::vector<std::string> classNames;
for (auto i = 0; i < arrayLength; i++) {
auto string = (jstring) env->GetObjectArrayElement(classes, i);
auto str_className = env->GetStringUTFChars((jstring) string, nullptr);
auto className = std::string(str_className);
if (std::find(validClasses.begin(), validClasses.end(), className) == validClasses.end()) {
sampgdk_logprintf("[SHOEBILL] %s is not a valid class type for registering a function (%s).", str_className,
functionString.c_str());
env->ReleaseStringUTFChars(string, str_className);
return (jboolean) false;
}
classNames.push_back(className);
env->ReleaseStringUTFChars(string, str_className);
}
AmxInstanceManager::GetInstance().RegisterFunction(amx, functionString, classNames);
return (jboolean) true;
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPVarInt(JNIEnv *env, jclass, jint playerid,
jstring name, jint value) {
assertNotNull(name, "name", __FUNCTION__);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), name, 64);
SetPVarInt(playerid, str_varname, value);
delete[] str_varname;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPVarInt(JNIEnv *env, jclass, jint playerid,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), name, 64);
auto result = GetPVarInt(playerid, str_varname);
delete[] str_varname;
return result;
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPVarString(JNIEnv *env, jclass,
jint playerid, jstring name,
jstring value) {
assertNotNull(name, "name", __FUNCTION__); assertNotNull(value, "value", __FUNCTION__);
auto codepage = Shoebill::GetInstance().getPlayerCodepage(playerid);
auto str_varname = wcs2mbs(env, codepage, name, 64);
auto str_value = wcs2mbs(env, codepage, value, 1024);
SetPVarString(playerid, str_varname, str_value);
delete[] str_varname;
delete[] str_value;
}
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPVarString(JNIEnv *env, jclass,
jint playerid,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, NULL);
auto codepage = Shoebill::GetInstance().getPlayerCodepage(playerid);
auto str_varname = wcs2mbs(env, codepage, name, 64);
char value[1024];
GetPVarString(playerid, str_varname, value, 1024);
delete[](str_varname);
return mbs2wcs(env, codepage, value, 1024);
}
JNIEXPORT void JNICALL Java_net_gtaun_shoebill_SampNativeFunction_setPVarFloat(JNIEnv *env, jclass,
jint playerid, jstring name,
jfloat value) {
assertNotNull(name, "name", __FUNCTION__);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), name, 64);
SetPVarFloat(playerid, str_varname, value);
delete[] str_varname;
}
JNIEXPORT jfloat JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPVarFloat(JNIEnv *env, jclass,
jint playerid,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), name, 64);
auto result = GetPVarFloat(playerid, str_varname);
delete[] str_varname;
return result;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_deletePVar(JNIEnv *env, jclass, jint playerid,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), name, 64);
auto result = DeletePVar(playerid, str_varname);
delete[] str_varname;
return result;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPVarsUpperIndex(JNIEnv *, jclass,
jint playerid) {
return GetPVarsUpperIndex(playerid);
}
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPVarNameAtIndex(JNIEnv *env, jclass,
jint playerid,
jint index) {
char varName[1024];
GetPVarNameAtIndex(playerid, index, varName, 1024);
return mbs2wcs(env, Shoebill::GetInstance().getPlayerCodepage(playerid), varName, 1024);
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getPVarType(JNIEnv *env, jclass,
jint playerid, jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, 64);
auto result = GetPVarType(playerid, str_varname);
delete[] str_varname;
return result;
}
JNIEXPORT jint JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getConsoleVarAsInt(JNIEnv *env, jclass,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, 0);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, 64);
auto result = GetServerVarAsInt(str_varname);
delete[] str_varname;
return result;
}
JNIEXPORT jboolean JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getConsoleVarAsBool(JNIEnv *env, jclass,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, false);
auto str_varname = wcs2mbs(env, Shoebill::GetInstance().getServerCodepage(), name, 64);
auto result = GetServerVarAsBool(str_varname);
delete[] str_varname;
return (jboolean) result;
}
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_getConsoleVarAsString(JNIEnv *env, jclass,
jstring name) {
assertNotNullReturn(name, "name", __FUNCTION__, NULL);
auto codepage = Shoebill::GetInstance().getServerCodepage();
auto str_name = wcs2mbs(env, codepage, name, 64);
char result[1024];
GetServerVarAsString(str_name, result, 1024);
delete[] str_name;
return mbs2wcs(env, codepage, result, 1024);
}
JNIEXPORT jstring JNICALL Java_net_gtaun_shoebill_SampNativeFunction_sha256Hash(JNIEnv *env, jclass, jstring jPassword,
jstring jSalt) {
assertNotNullReturn(jPassword, "jPassword", __FUNCTION__, NULL); assertNotNullReturn(jSalt, "jSalt", __FUNCTION__, NULL);
auto codepage = Shoebill::GetInstance().getServerCodepage();
auto str_password = wcs2mbs(env, codepage, jPassword, 1024);
auto str_salt = wcs2mbs(env, codepage, jSalt, 1024);
char hash[1024];
auto hash_len = 0;
SHA256_PassHash(str_password, str_salt, hash, hash_len);
delete[] str_password;
delete[] str_salt;
return mbs2wcs(env, codepage, hash, 1024);
} | 37.097189 | 129 | 0.694764 | [
"object",
"vector",
"model"
] |
008b0e18a4ce08d856e2a236f648079bce722fc1 | 941 | hpp | C++ | examples/tetris/lib/Moon/include/cmp/cmp_base.hpp | reitmas32/Moon | 02790eb476f039b44664e7d8f24fa2839187e4fc | [
"MIT"
] | 2 | 2021-05-20T06:55:38.000Z | 2021-05-23T05:09:06.000Z | examples/tetris/lib/Moon/include/cmp/cmp_base.hpp | reitmas32/Moon | 02790eb476f039b44664e7d8f24fa2839187e4fc | [
"MIT"
] | 15 | 2021-04-21T05:26:39.000Z | 2021-07-06T07:07:28.000Z | examples/tetris/lib/Moon/include/cmp/cmp_base.hpp | reitmas32/Moon | 02790eb476f039b44664e7d8f24fa2839187e4fc | [
"MIT"
] | null | null | null | /**
* @file component_base.hpp
* @author Oswaldo Rafael Zamora Ramirez (rafa.zamo.rals@comunidad.unam.mx)
* @brief Clase de la que heredan todos los components del Motor
* @version 0.1
* @date 2021-03-03
*
* @copyright Copyright (c) Moon 2020-2021 Oswaldo Rafael Zamora Ramírez
*
*/
#pragma once
// Alias
#include "../alias.hpp"
/**
* @brief Namespace del core del Motor
*
*/
namespace Moon::Core {
/**
* @brief Clase de la que heredan todos los components del Motor
*
*/
struct ComponentBase_t
{
/**Identificador del siguiente tipo de Componet*/
inline static Moon::Alias::ComponentType nextType = 0;
/**
* @brief Construct a new ComponentBase_t object
*
*/
ComponentBase_t();
/**
* @brief Destroy the ComponentBase_t object
*
*/
virtual ~ComponentBase_t() = 0;
};
} // namespace Moon::Core | 21.883721 | 75 | 0.60255 | [
"object"
] |
008c53fcd1e7544739250808b22674966bd54aee | 2,968 | cpp | C++ | ProgramStudy/Source/Systems/SceneMng.cpp | trinhlehainam/ASO_3rd_year_StudyProject | 89c54e42e97cc47af175f61b26a5871bc2a718a0 | [
"MIT"
] | null | null | null | ProgramStudy/Source/Systems/SceneMng.cpp | trinhlehainam/ASO_3rd_year_StudyProject | 89c54e42e97cc47af175f61b26a5871bc2a718a0 | [
"MIT"
] | null | null | null | ProgramStudy/Source/Systems/SceneMng.cpp | trinhlehainam/ASO_3rd_year_StudyProject | 89c54e42e97cc47af175f61b26a5871bc2a718a0 | [
"MIT"
] | null | null | null | #include "SceneMng.h"
#include <chrono>
#include <DxLib.h>
#include "../_debug/_DebugDispOut.h"
#include "../Math/MathHelper.h"
#include "../Systems/ImageMng.h"
#include "../Systems/AnimationMng.h"
#include "../Systems/AnimatorControllerMng.h"
#include "../Systems/Physics.h"
#include "../Systems/Renderer.h"
#include "../Scenes/TitleScene.h"
#include "../Scenes/GameScene.h"
namespace
{
constexpr int kScreenWidth = 1024;
constexpr int kScreenHeight = 768;
}
#pragma region Pimpl
class SceneMng::Impl
{
public:
Impl();
~Impl() = default;
void Update();
void Render();
float GetDeltaTime_s();
std::unique_ptr<IScene> scene;
std::chrono::steady_clock::time_point lastTime;
float m_deltaTime_s;
};
SceneMng::Impl::Impl() : lastTime(std::chrono::high_resolution_clock::now()), m_deltaTime_s(0.0f){}
void SceneMng::Impl::Update()
{
// Update
m_deltaTime_s = GetDeltaTime_s();
lastTime = std::chrono::high_resolution_clock::now();
scene->Update(m_deltaTime_s);
//
// Change/Move scene
if (scene->EnableChangeScene)
scene = std::move(scene->ChangeScene(std::move(scene)));
//
}
void SceneMng::Impl::Render()
{
_dbgStartDraw();
scene->RenderToOwnScreen();
// Render to screen back
SetDrawScreen(DX_SCREEN_BACK);
ClearDrawScreen();
scene->Render();
// Show FPS
#ifdef _DEBUG || DEBUG
DrawFormatString(20, 10, GetColor(255, 255, 255), "FPS : %.f", 1.0f / m_deltaTime_s);
DrawFormatString(20, 30, GetColor(255, 255, 255), "Deltatime_ms : %.2f", m_deltaTime_s / MathHelper::kMsToSecond);
_dbgDraw();
#endif
ScreenFlip();
//
}
float SceneMng::Impl::GetDeltaTime_s()
{
return std::chrono::duration<float, std::chrono::seconds::period>(std::chrono::high_resolution_clock::now() - lastTime).count();
}
#pragma endregion
SceneMng& SceneMng::Instance()
{
static SceneMng sceneMng;
return sceneMng;
}
SceneMng::SceneMng():m_impl(std::make_unique<Impl>()) {}
SceneMng::~SceneMng() {}
bool SceneMng::Init()
{
SetMainWindowText("1916021_TRINH LE HAI NAM");
ChangeWindowMode(true);
SetGraphMode(kScreenWidth, kScreenHeight, 32);
SetDrawScreen(DX_SCREEN_BACK);
if (DxLib_Init() == -1)
return false;
_dbgSetup(kScreenWidth, kScreenHeight, 255);
Renderer::Create();
Physics::Create();
ImageMng::Create();
AnimationMng::Create();
AnimatorControllerMng::Create();
m_impl->scene = std::make_unique<TitleScene>();
m_impl->scene->Init();
return true;
}
void SceneMng::Exit()
{
m_impl.release();
ImageMng::Destroy();
AnimationMng::Destroy();
AnimatorControllerMng::Destroy();
Physics::Destroy();
Renderer::Destroy();
DxLib_End();
}
void SceneMng::Run()
{
while (ProcessMessage() != -1 && CheckHitKey(KEY_INPUT_ESCAPE) == 0)
{
m_impl->Update();
m_impl->Render();
}
}
// Avoid copy and assign
SceneMng::SceneMng(const SceneMng&) {}
SceneMng::SceneMng(SceneMng&&) noexcept {}
void SceneMng::operator=(const SceneMng&) {}
void SceneMng::operator=(SceneMng&&) noexcept {}
//
| 20.755245 | 129 | 0.696092 | [
"render"
] |
0090cd160bc9a18afdaead3ae86b3c82b08bec85 | 7,287 | hpp | C++ | sdl/Hypergraph/WordToCharacters.hpp | sdl-research/hyp | d39f388f9cd283bcfa2f035f399b466407c30173 | [
"Apache-2.0"
] | 29 | 2015-01-26T21:49:51.000Z | 2021-06-18T18:09:42.000Z | sdl/Hypergraph/WordToCharacters.hpp | hypergraphs/hyp | d39f388f9cd283bcfa2f035f399b466407c30173 | [
"Apache-2.0"
] | 1 | 2015-12-08T15:03:15.000Z | 2016-01-26T14:31:06.000Z | sdl/Hypergraph/WordToCharacters.hpp | hypergraphs/hyp | d39f388f9cd283bcfa2f035f399b466407c30173 | [
"Apache-2.0"
] | 4 | 2015-11-21T14:25:38.000Z | 2017-10-30T22:22:00.000Z | // Copyright 2014-2015 SDL plc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** \file
split hypergraph labels so they're at most 1 unicode codepoint long, optionally inserting token-begin
symbols
*/
#ifndef HYP__HG_WORDTOCHARACTER
#define HYP__HG_WORDTOCHARACTER
#pragma once
#include <sdl/Hypergraph/DeferAddArcs.hpp>
#include <sdl/Hypergraph/IMutableHypergraph.hpp>
#include <sdl/Util/IntSet.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <sdl/Util/Once.hpp>
#include <sdl/Util/Utf8.hpp>
#include <sdl/Exception.hpp>
#include <sdl/SharedPtr.hpp>
#include <sdl/Syms.hpp>
#include <boost/cstdint.hpp>
#include <vector>
namespace sdl {
namespace Hypergraph {
/**
in-place add new states/arcs so every terminal token is at most one unicode
codepoint (leaving special syms and nonterms alone). no 'space' or epsilon
separators added.
expands input label and so discards output labels of modified arcs
TODO: works for graph (one lexical label per tail) only
side effect: hg->storesFirstTailOutArcs(), !hg->storesInArcs()
*/
template <class Arc>
struct WordToCharacters {
IMutableHypergraph<Arc>* hg_;
DeferAddArcs<Arc> addArcLater_;
IVocabulary* vocab_;
Sym tokenPrefixSym_ = NoSymbol;
// NoSymbol if you don't want one inserted. else you can use original weight
// (FeatureId) as a marker. new arcs get no added cost/features.
Util::FixUnicode fixUnicode_;
StateId nAddedArcsMinimum_ = 0;
std::vector<StateIdContainer> insertStatesForTail_;
/// compute (>1 char lexical state)->(char states) mapping
void splitInputLabelChars() {
bool insertingPrefix = (bool)tokenPrefixSym_;
HypergraphBase::Labels labels = hg_->copyOfLabels();
// avoid canonical-lex problem by copying (can't store ref if non-canonical, either)
StateId s = 0, N = labels.size();
SDL_TRACE(WordToCharacters, "input labels: " << printer(labels, vocab_));
insertStatesForTail_.resize(N);
for (; s < N; ++s) {
Sym wordsym = labels[s];
if (!wordsym.isLexical()) continue;
std::string const& word = vocab_->str(wordsym);
StateId nchars = word.size();
if (!nchars || nchars == 1 && !insertingPrefix) continue;
typedef std::vector<std::string> Chars;
Chars chars;
chars.reserve(nchars); // upper bound
Util::toUtf8Chs(word, chars, fixUnicode_); // assume utf8 is well-formed
SDL_TRACE(WordToCharacters, "unicode chars={ " << printer(chars) << " }");
StateId const nunicode = chars.size();
if (!nunicode) continue;
StateId const ninsert = nunicode - !insertingPrefix;
nAddedArcsMinimum_ += ninsert;
StateIdContainer& insertStates = insertStatesForTail_[s];
insertStates.resize(ninsert);
Chars::const_iterator i = chars.begin(), end = chars.end();
StateIdContainer::iterator to = insertStates.begin();
if (insertingPrefix) {
hg_->setInputLabel(s, tokenPrefixSym_);
} else {
hg_->setInputLabel(s, vocab_->addTerminal(*i));
++i;
}
SDL_DEBUG(WordToCharacters, "for input state "
<< s << " with input label: " << printer(wordsym, vocab_)
<< ": replaced => label: " << printer(hg_->inputLabel(s), vocab_));
for (; i != end; ++i) *to++ = hg_->addState(vocab_->addTerminal(*i));
assert(to == insertStates.begin() + ninsert);
SDL_DEBUG(WordToCharacters, "for input state " << s << " with input label: " << printer(wordsym, vocab_)
<< ": output: " << printer(insertStates, hg_));
}
}
void operator()(ArcBase* a) const {
Arc* arc = (Arc*)a;
StateIdContainer& tails = arc->tails_;
for (StateIdContainer::iterator i = tails.begin(), iend = tails.end(); i != iend; ++i) {
StateIdContainer const& replacelex = insertStatesForTail_[*i];
StateIdContainer::const_iterator j = replacelex.begin(), jend = replacelex.end();
if (j != jend) {
StateId lastHead = arc->head_;
StateId tail = hg_->addState();
arc->head_ = tail;
for (;;) {
assert(j < jend);
StateId symstate = *j;
if (++j == jend) {
addArcLater_(new Arc(HeadAndTail(), lastHead, tail, symstate));
return; // only one lexical sym expanded per arc (recall input is graph + one lexical per tail)
} else {
StateId const head = hg_->addState();
addArcLater_(new Arc(HeadAndTail(), head, tail, symstate));
tail = head;
}
}
}
}
}
WordToCharacters(IMutableHypergraph<Arc>* h, Sym tokenPrefixSym = NoSymbol)
: hg_(h), addArcLater_(*h), vocab_(h->vocab()), fixUnicode_(false), tokenPrefixSym_(tokenPrefixSym) {
if (!hg_->isGraph())
SDL_THROW_LOG(Hypergraph.WordToCharacters, ConfigException,
"wordToCharacters() doesn't support cfg (only fsm):\n " << hg_);
if (hg_->hasOutputLabels())
SDL_INFO(Hypergraph.WordToCharacters,
"wordToCharacters will modify input labels only but input hg_ has some output labels"
" - ignoring output labels");
splitInputLabelChars();
if (nAddedArcsMinimum_) {
hg_->reserveAdditionalStates(nAddedArcsMinimum_);
// if all labeled states were used, we add at least this many tails (could
// be more if multiple arcs per state)
hg_->clearCanonicalLexCache(); // we will be modifying some labels
hg_->forceFirstTailOutArcsOnly();
for (StateId s = 0, N = hg_->sizeForHeads(); s < N; ++s) hg_->visitOutArcs(s, *this);
addArcLater_.finish();
}
}
};
/// side effect: hg->storesFirstTailOutArcs(), !hg->storesInArcs()
template <class Arc>
void wordToCharacters(IMutableHypergraph<Arc>* hg, Sym tokenPrefixSym = NoSymbol) {
WordToCharacters<Arc>(hg, tokenPrefixSym);
}
/// side effect: hg->storesFirstTailOutArcs(), !hg->storesInArcs()
template <class Arc>
void wordToCharacters(IMutableHypergraph<Arc>& hg, Sym tokenPrefixSym = NoSymbol) {
WordToCharacters<Arc>(&hg, tokenPrefixSym);
}
struct WordToCharactersOptions {
bool tokSep = false;
std::string terminalSep;
template <class Config>
void configure(Config& config) {
config.is("WordToCharacters");
config("tok-sep", &tokSep).init(false)("add <tok> special at start of every word (of 1 char or more)");
config("string-sep", &tokSep)
.init(" ")("if nonempty, add (instead of tok-sep) this terminal at start of word");
}
template <class Arc>
void inplace(IMutableHypergraph<Arc>& hg) const {
Sym sep = terminalSep.empty() ? (tokSep ? TOK_START::ID : NoSymbol) : hg.vocab()->addTerminal(terminalSep);
wordToCharacters(&hg, sep);
}
};
}}
#endif
| 39.819672 | 111 | 0.659531 | [
"vector"
] |
0097f5d2df82326dfb7edf78969f59f94bfbaa94 | 1,835 | hpp | C++ | accumulate.hpp | YishayGarame/itertools-cfar-b | 6e90408fa5664931f25077b971aa47cb55892296 | [
"MIT"
] | null | null | null | accumulate.hpp | YishayGarame/itertools-cfar-b | 6e90408fa5664931f25077b971aa47cb55892296 | [
"MIT"
] | null | null | null | accumulate.hpp | YishayGarame/itertools-cfar-b | 6e90408fa5664931f25077b971aa47cb55892296 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
namespace itertools
{
typedef struct
{
template <typename T>
T operator()(T f1, T f2) const
{
return f1 + f2;
}
} add;
template <typename T, typename _operator = add>
class accumulate
{
public:
T _container;
_operator operat;
accumulate(T vec, _operator operat1 = add()) : _container(vec), operat(operat1) {}
class iterator
{
public:
typename T::iterator iter;
decltype(*(_container.begin())) sum;
int counter;
_operator operat;
iterator(typename T::iterator first, _operator operat1)
: iter(first), sum(*iter), counter(0), operat(operat1) {}
//-------------------------------------------------operators-------------------------------------------------
bool operator!=(const iterator &other)
{
return other.iter != iter;
}
// bool operator==(const iterator &other)
// {
// return this == other.iter;
// }
auto operator*()
{
if (counter == 0) // means its the first item
{
counter++;
return *iter;
}
sum = operat(sum, *iter);
return sum;
}
iterator &operator++()
{
++iter;
return *this;
}
};
iterator begin()
{
return iterator(_container.begin(), operat);
}
iterator end()
{
return iterator(_container.end(), operat);
}
};
} // namespace itertools | 24.797297 | 121 | 0.421798 | [
"vector"
] |
00982335edb0f5e84f210a3a2f41509d32bc2881 | 2,150 | cpp | C++ | os/kernel/testsuite/interlocked.cpp | rvedam/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 2 | 2020-11-30T18:38:20.000Z | 2021-06-07T07:44:03.000Z | os/kernel/testsuite/interlocked.cpp | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 1 | 2019-01-14T03:09:45.000Z | 2019-01-14T03:09:45.000Z | os/kernel/testsuite/interlocked.cpp | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2008, 2009 Google Inc.
* Copyright 2006 Nintendo Co., Ltd.
*
* 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 <stdlib.h>
#include <es.h>
#include <es/interlocked.h>
#include "core.h"
#define TEST(exp) \
(void) ((exp) || \
(esPanic(__FILE__, __LINE__, "\nFailed test " #exp), 0))
int main()
{
Object* nameSpace;
esInit(&nameSpace);
esReport("sizeof(char) = %u\n", sizeof(char));
esReport("sizeof(short) = %u\n", sizeof(short));
esReport("sizeof(int) = %u\n", sizeof(int));
esReport("sizeof(long) = %u\n", sizeof(long));
esReport("sizeof(long long) = %u\n", sizeof(long long));
Interlocked count(0);
esReport("count = %ld\n", static_cast<long>(count));
TEST(count == 0);
long n;
n = count.exchange(3);
esReport("count = %ld: n = %ld\n", static_cast<long>(count), n);
TEST(count == 3 && n == 0);
n = count.exchange(5);
esReport("count = %ld: n = %ld\n", static_cast<long>(count), n);
TEST(count == 5 && n == 3);
n = count.increment();
esReport("count = %ld: n = %ld\n", static_cast<long>(count), n);
TEST(count == 6 && n == 6);
n = count.decrement();
esReport("count = %ld: n = %ld\n", static_cast<long>(count), n);
TEST(count == 5 && n == 5);
n = count.compareExchange(7, 3);
esReport("count = %ld: n = %ld\n", static_cast<long>(count), n);
TEST(count == 5 && n == 5);
n = count.compareExchange(7, 5);
esReport("count = %ld: n = %ld\n", static_cast<long>(count), n);
TEST(count == 7 && n == 5);
esReport("done.\n");
}
| 31.15942 | 75 | 0.593953 | [
"object"
] |
00997327027c26dde8ae35e01bba8dad45d13c69 | 18,404 | hpp | C++ | include/System/Xml/XmlQualifiedName.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/XmlQualifiedName.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/XmlQualifiedName.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"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Xml
namespace System::Xml {
// Forward declaring type: XmlNameTable
class XmlNameTable;
// Forward declaring type: IXmlNamespaceResolver
class IXmlNamespaceResolver;
}
// Completed forward declares
// Type namespace: System.Xml
namespace System::Xml {
// Forward declaring type: XmlQualifiedName
class XmlQualifiedName;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Xml::XmlQualifiedName);
DEFINE_IL2CPP_ARG_TYPE(::System::Xml::XmlQualifiedName*, "System.Xml", "XmlQualifiedName");
// Type namespace: System.Xml
namespace System::Xml {
// Size: 0x24
#pragma pack(push, 1)
// Autogenerated type: System.Xml.XmlQualifiedName
// [TokenAttribute] Offset: FFFFFFFF
class XmlQualifiedName : public ::Il2CppObject {
public:
// Nested type: ::System::Xml::XmlQualifiedName::HashCodeOfStringDelegate
class HashCodeOfStringDelegate;
public:
// private System.String name
// Size: 0x8
// Offset: 0x10
::StringW name;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private System.String ns
// Size: 0x8
// Offset: 0x18
::StringW ns;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private System.Int32 hash
// Size: 0x4
// Offset: 0x20
int hash;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Get static field: static private System.Xml.XmlQualifiedName/System.Xml.HashCodeOfStringDelegate hashCodeDelegate
static ::System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* _get_hashCodeDelegate();
// Set static field: static private System.Xml.XmlQualifiedName/System.Xml.HashCodeOfStringDelegate hashCodeDelegate
static void _set_hashCodeDelegate(::System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* value);
// Get static field: static public readonly System.Xml.XmlQualifiedName Empty
static ::System::Xml::XmlQualifiedName* _get_Empty();
// Set static field: static public readonly System.Xml.XmlQualifiedName Empty
static void _set_Empty(::System::Xml::XmlQualifiedName* value);
// Get instance field reference: private System.String name
[[deprecated("Use field access instead!")]] ::StringW& dyn_name();
// Get instance field reference: private System.String ns
[[deprecated("Use field access instead!")]] ::StringW& dyn_ns();
// Get instance field reference: private System.Int32 hash
[[deprecated("Use field access instead!")]] int& dyn_hash();
// public System.String get_Namespace()
// Offset: 0x10244EC
::StringW get_Namespace();
// public System.String get_Name()
// Offset: 0x10244F4
::StringW get_Name();
// public System.Boolean get_IsEmpty()
// Offset: 0x102477C
bool get_IsEmpty();
// public System.Void .ctor()
// Offset: 0x1024398
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlQualifiedName* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::XmlQualifiedName::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlQualifiedName*, creationType>()));
}
// public System.Void .ctor(System.String name)
// Offset: 0x1024488
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlQualifiedName* New_ctor(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::XmlQualifiedName::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlQualifiedName*, creationType>(name)));
}
// public System.Void .ctor(System.String name, System.String ns)
// Offset: 0x10243F0
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlQualifiedName* New_ctor(::StringW name, ::StringW ns) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::XmlQualifiedName::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlQualifiedName*, creationType>(name, ns)));
}
// static private System.Void .cctor()
// Offset: 0x1024E28
static void _cctor();
// static public System.String ToString(System.String name, System.String ns)
// Offset: 0x1024A10
static ::StringW ToString(::StringW name, ::StringW ns);
// static private System.Xml.XmlQualifiedName/System.Xml.HashCodeOfStringDelegate GetHashCodeDelegate()
// Offset: 0x10245DC
static ::System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* GetHashCodeDelegate();
// static private System.Boolean IsRandomizedHashingDisabled()
// Offset: 0x1024A90
static bool IsRandomizedHashingDisabled();
// static private System.Int32 GetHashCodeOfString(System.String s, System.Int32 length, System.Int64 additionalEntropy)
// Offset: 0x1024A98
static int GetHashCodeOfString(::StringW s, int length, int64_t additionalEntropy);
// System.Void Init(System.String name, System.String ns)
// Offset: 0x1024AB4
void Init(::StringW name, ::StringW ns);
// System.Void SetNamespace(System.String ns)
// Offset: 0x1024AC0
void SetNamespace(::StringW ns);
// System.Void Verify()
// Offset: 0x1024AC8
void Verify();
// System.Void Atomize(System.Xml.XmlNameTable nameTable)
// Offset: 0x1024B80
void Atomize(::System::Xml::XmlNameTable* nameTable);
// static System.Xml.XmlQualifiedName Parse(System.String s, System.Xml.IXmlNamespaceResolver nsmgr, out System.String prefix)
// Offset: 0x1024BD8
static ::System::Xml::XmlQualifiedName* Parse(::StringW s, ::System::Xml::IXmlNamespaceResolver* nsmgr, ByRef<::StringW> prefix);
// System.Xml.XmlQualifiedName Clone()
// Offset: 0x1024DA4
::System::Xml::XmlQualifiedName* Clone();
// public override System.Int32 GetHashCode()
// Offset: 0x10244FC
// Implemented from: System.Object
// Base method: System.Int32 Object::GetHashCode()
int GetHashCode();
// public override System.String ToString()
// Offset: 0x10247BC
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::StringW ToString();
// public override System.Boolean Equals(System.Object other)
// Offset: 0x1024830
// Implemented from: System.Object
// Base method: System.Boolean Object::Equals(System.Object other)
bool Equals(::Il2CppObject* other);
}; // System.Xml.XmlQualifiedName
#pragma pack(pop)
static check_size<sizeof(XmlQualifiedName), 32 + sizeof(int)> __System_Xml_XmlQualifiedNameSizeCheck;
static_assert(sizeof(XmlQualifiedName) == 0x24);
// static public System.Boolean op_Equality(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b)
// Offset: 0x10249A4
bool operator ==(::System::Xml::XmlQualifiedName* a, ::System::Xml::XmlQualifiedName& b);
// static public System.Boolean op_Inequality(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b)
// Offset: 0x1024928
bool operator !=(::System::Xml::XmlQualifiedName* a, ::System::Xml::XmlQualifiedName& b);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::get_Namespace
// Il2CppName: get_Namespace
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::get_Namespace)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "get_Namespace", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::get_Name
// Il2CppName: get_Name
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::get_Name)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "get_Name", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::get_IsEmpty
// Il2CppName: get_IsEmpty
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::get_IsEmpty)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "get_IsEmpty", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Xml::XmlQualifiedName::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (*)(::StringW, ::StringW)>(&System::Xml::XmlQualifiedName::ToString)> {
static const MethodInfo* get() {
static auto* name = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* ns = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{name, ns});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::GetHashCodeDelegate
// Il2CppName: GetHashCodeDelegate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Xml::XmlQualifiedName::HashCodeOfStringDelegate* (*)()>(&System::Xml::XmlQualifiedName::GetHashCodeDelegate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "GetHashCodeDelegate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::IsRandomizedHashingDisabled
// Il2CppName: IsRandomizedHashingDisabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&System::Xml::XmlQualifiedName::IsRandomizedHashingDisabled)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "IsRandomizedHashingDisabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::GetHashCodeOfString
// Il2CppName: GetHashCodeOfString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::StringW, int, int64_t)>(&System::Xml::XmlQualifiedName::GetHashCodeOfString)> {
static const MethodInfo* get() {
static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* additionalEntropy = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "GetHashCodeOfString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, length, additionalEntropy});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlQualifiedName::*)(::StringW, ::StringW)>(&System::Xml::XmlQualifiedName::Init)> {
static const MethodInfo* get() {
static auto* name = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* ns = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{name, ns});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::SetNamespace
// Il2CppName: SetNamespace
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlQualifiedName::*)(::StringW)>(&System::Xml::XmlQualifiedName::SetNamespace)> {
static const MethodInfo* get() {
static auto* ns = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "SetNamespace", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ns});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::Verify
// Il2CppName: Verify
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::Verify)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "Verify", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::Atomize
// Il2CppName: Atomize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlQualifiedName::*)(::System::Xml::XmlNameTable*)>(&System::Xml::XmlQualifiedName::Atomize)> {
static const MethodInfo* get() {
static auto* nameTable = &::il2cpp_utils::GetClassFromName("System.Xml", "XmlNameTable")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "Atomize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nameTable});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::Parse
// Il2CppName: Parse
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Xml::XmlQualifiedName* (*)(::StringW, ::System::Xml::IXmlNamespaceResolver*, ByRef<::StringW>)>(&System::Xml::XmlQualifiedName::Parse)> {
static const MethodInfo* get() {
static auto* s = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* nsmgr = &::il2cpp_utils::GetClassFromName("System.Xml", "IXmlNamespaceResolver")->byval_arg;
static auto* prefix = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "Parse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{s, nsmgr, prefix});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::Clone
// Il2CppName: Clone
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Xml::XmlQualifiedName* (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::Clone)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::GetHashCode
// Il2CppName: GetHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::GetHashCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlQualifiedName::*)()>(&System::Xml::XmlQualifiedName::ToString)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::Equals
// Il2CppName: Equals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Xml::XmlQualifiedName::*)(::Il2CppObject*)>(&System::Xml::XmlQualifiedName::Equals)> {
static const MethodInfo* get() {
static auto* other = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlQualifiedName*), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other});
}
};
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::operator ==
// Il2CppName: op_Equality
// Cannot perform method pointer template specialization from operators!
// Writing MetadataGetter for method: System::Xml::XmlQualifiedName::operator !=
// Il2CppName: op_Inequality
// Cannot perform method pointer template specialization from operators!
| 55.433735 | 216 | 0.73283 | [
"object",
"vector"
] |
009bdd13978a4f692b3c6ee6d5685d3b23f36be1 | 5,867 | cpp | C++ | src/Engine/Renderer/Apis/OpenGL/OpenGLRenderer.cpp | Sausty/GameProject-1 | 0c0c13dea2b446213cea9074a02bcf588fb46559 | [
"MIT"
] | null | null | null | src/Engine/Renderer/Apis/OpenGL/OpenGLRenderer.cpp | Sausty/GameProject-1 | 0c0c13dea2b446213cea9074a02bcf588fb46559 | [
"MIT"
] | null | null | null | src/Engine/Renderer/Apis/OpenGL/OpenGLRenderer.cpp | Sausty/GameProject-1 | 0c0c13dea2b446213cea9074a02bcf588fb46559 | [
"MIT"
] | null | null | null | //
// Created by MarcasRealAccount on 31. Oct. 2020
//
#include "Engine/Renderer/Apis/OpenGL/OpenGLRenderer.h"
#include "Engine/Renderer/Apis/OpenGL/OpenGLDebugRenderer.h"
#include "Engine/Renderer/Apis/OpenGL/Mesh/OpenGLMeshData.h"
#include "Engine/Renderer/Apis/OpenGL/Mesh/OpenGLSkeletalMeshData.h"
#include "Engine/Renderer/Apis/OpenGL/Mesh/OpenGLStaticMeshData.h"
#include "Engine/Renderer/Apis/OpenGL/Mesh/OpenGLStaticVoxelMeshData.h"
#include "Engine/Renderer/Apis/OpenGL/Shader/OpenGLMaterialData.h"
#include "Engine/Renderer/Apis/OpenGL/Shader/OpenGLShaderData.h"
#include "Engine/Scene/Scene.h"
#include "Engine/Scene/Entity.h"
#include "Engine/Scene/Camera.h"
#include <stdint.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <glad/glad.h>
namespace gp1 {
OpenGLRenderer::OpenGLRenderer(Window* window)
: Renderer(window) {}
RendererType OpenGLRenderer::GetRendererType() const {
return RendererType::OPENGL;
}
DebugRenderer* OpenGLRenderer::CreateDebugRenderer() {
return new OpenGLDebugRenderer(this);
}
MeshData* OpenGLRenderer::CreateSkeletalMeshData(Mesh* mesh) {
return new OpenGLSkeletalMeshData(mesh);
}
MeshData* OpenGLRenderer::CreateStaticMeshData(Mesh* mesh) {
return new OpenGLStaticMeshData(mesh);
}
MeshData* OpenGLRenderer::CreateStaticVoxelMeshData(Mesh* mesh) {
return new OpenGLStaticVoxelMeshData(mesh);
}
ShaderData* OpenGLRenderer::CreateShaderData(Shader* shader) {
return new OpenGLShaderData(shader);
}
MaterialData* OpenGLRenderer::CreateMaterialData(Material* material) {
return new OpenGLMaterialData(material);
}
void OpenGLRenderer::InitRenderer() {
}
void OpenGLRenderer::DeInitRenderer() {
}
void OpenGLRenderer::RenderScene(Scene* scene, uint32_t width, uint32_t height) {
Camera* mainCamera = scene->GetMainCamera();
if (mainCamera) {
glViewport(0, 0, width, height);
glClearColor(mainCamera->m_ClearColor.r, mainCamera->m_ClearColor.g, mainCamera->m_ClearColor.b, mainCamera->m_ClearColor.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
for (auto entity : scene->GetEntities()) {
RenderEntity(entity);
}
// Render Debug Objects:
OpenGLDebugRenderer* debugRenderer = reinterpret_cast<OpenGLDebugRenderer*>(GetDebugRenderer());
if (debugRenderer) {
std::vector<OpenGLDebugObject*>& entities = debugRenderer->m_Entities;
auto itr = entities.begin();
while (itr != entities.end()) {
OpenGLDebugObject* obj = *itr;
if (obj->m_Lifetime > 0.0f) {
if (glfwGetTime() - obj->m_SpawnTime > obj->m_Lifetime) {
delete obj;
itr = entities.erase(itr);
continue;
}
obj->m_Scene = scene;
RenderEntity(obj);
itr++;
} else {
RenderEntity(obj);
delete obj;
itr = entities.erase(itr);
continue;
}
}
}
glfwSwapBuffers(GetNativeWindowHandle());
}
}
void OpenGLRenderer::RenderEntity(Entity* entity) {
Scene* scene = entity->GetScene();
if (!scene) return;
Camera* cam = scene->GetMainCamera();
if (!cam) return;
Mesh* mesh = entity->GetMesh();
Material* material = entity->GetMaterial();
if (material) {
if (mesh) {
Uniform<glm::fmat4>* transformationMatrix = material->GetUniform<glm::fmat4>("transformationMatrix");
if (transformationMatrix) transformationMatrix->m_Value = entity->GetTransformationMatrix();
Uniform<glm::fmat4>* projectionViewMatrix = material->GetUniform<glm::fmat4>("projectionViewMatrix");
if (projectionViewMatrix) projectionViewMatrix->m_Value = cam->GetProjectionViewMatrix();
Uniform<glm::fvec3>* lightDirection = material->GetUniform<glm::fvec3>("lightDirection");
if (lightDirection) lightDirection->m_Value = { 0, 0, 1 };
RenderMeshWithMaterial(GetMeshData<OpenGLMeshData>(mesh), GetMaterialData<OpenGLMaterialData>(material));
}
} else if (mesh) {
RenderMesh(GetMeshData<OpenGLMeshData>(mesh));
}
}
void OpenGLRenderer::RenderMeshWithMaterial(OpenGLMeshData* mesh, OpenGLMaterialData* material) {
PreMaterial(material);
RenderMesh(mesh);
PostMaterial(material);
}
void OpenGLRenderer::RenderMesh(OpenGLMeshData* mesh) {
if (mesh->GetMesh<Mesh>()->m_RenderMode == RenderMode::POINTS)
glPointSize(mesh->GetMesh<Mesh>()->m_LineWidth);
else
glLineWidth(mesh->GetMesh<Mesh>()->m_LineWidth);
glBindVertexArray(mesh->GetVAO());
for (uint8_t i = 0; i < mesh->m_NumAttribs; i++)
glEnableVertexAttribArray(mesh->m_EnabledAttribs[i]);
if (mesh->HasIndices())
glDrawElements(mesh->GetRenderMode(), mesh->m_BufferSize, GL_UNSIGNED_INT, 0);
else
glDrawArrays(mesh->GetRenderMode(), 0, mesh->m_BufferSize);
for (uint8_t i = mesh->m_NumAttribs; i > 0; i--)
glDisableVertexAttribArray(mesh->m_EnabledAttribs[i - 1]);
glBindVertexArray(0);
glPointSize(1);
glLineWidth(1);
}
void OpenGLRenderer::PreMaterial(OpenGLMaterialData* material) {
if (material->GetMaterial<Material>()->m_CullMode.m_Enabled) {
glEnable(GL_CULL_FACE);
glCullFace(material->GetCullFace());
}
if (material->GetMaterial<Material>()->m_DepthTest) {
glEnable(GL_DEPTH_TEST);
}
if (material->GetMaterial<Material>()->m_BlendFunc.m_Enabled) {
glEnable(GL_BLEND);
glBlendFunc(material->GetSrcBlendFunc(), material->GetDstBlendFunc());
}
glPolygonMode(material->GetPolygonModeFace(), material->GetPolygonMode());
OpenGLShaderData* shader = GetShaderData<OpenGLShaderData>(material);
if (shader) {
shader->Start();
material->SetAllUniforms();
}
}
void OpenGLRenderer::PostMaterial(OpenGLMaterialData* material) {
OpenGLShaderData* shader = GetShaderData<OpenGLShaderData>(material);
if (shader) {
shader->Stop();
}
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
} // namespace gp1
| 30.087179 | 128 | 0.726436 | [
"mesh",
"render",
"vector"
] |
00a1dba5b6680e5ffd4f5db7fa07f31852b9eab7 | 35,113 | cpp | C++ | tms_rc/tms_rc_katana/KNI_4.3.0/lib/kinematics/kinematics.cpp | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 54 | 2015-01-06T06:58:28.000Z | 2021-05-02T07:49:37.000Z | tms_rc/tms_rc_katana/KNI_4.3.0/lib/kinematics/kinematics.cpp | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 114 | 2015-01-07T06:42:21.000Z | 2022-02-12T05:54:04.000Z | tms_rc/tms_rc_katana/KNI_4.3.0/lib/kinematics/kinematics.cpp | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 24 | 2015-03-27T08:35:59.000Z | 2020-06-08T13:05:31.000Z | /**************************************************************************
* kinematics.cpp -
* Kinematics class for Katana4XX Robots using kinematics lib
* Copyright (C) 2007-2008 Neuronics AG
* PKE/UKE 2007, JHA 2008
**************************************************************************/
#include "kinematics.h"
///////////////////////////////////////////////////////////////////////
KinematicsLib::KinematicsLib()
{
initializeMembers();
}
///////////////////////////////////////////////////////////////////////
KinematicsLib::KinematicsLib(int type)
{
initializeMembers();
setType(type);
init();
}
///////////////////////////////////////////////////////////////////////
KinematicsLib::~KinematicsLib()
{
delete _anaGuess;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::sign(int value)
{
return (value > 0) - (value < 0);
}
int KinematicsLib::sign(double value)
{
return (value > 0) - (value < 0);
}
#ifdef WIN32
double KinematicsLib::round(double x)
// Copyright (C) 2001 Tor M. Aamodt, University of Toronto
// Permisssion to use for all purposes commercial and otherwise granted.
// THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY, OR ANY CONDITION OR
// OTHER TERM OF ANY KIND INCLUDING, WITHOUT LIMITATION, ANY WARRANTY
// OF MERCHANTABILITY, SATISFACTORY QUALITY, OR FITNESS FOR A PARTICULAR
// PURPOSE.
{
if (x > 0)
{
__int64 xint = (__int64)(x + 0.5);
if (xint % 2)
{
// then we might have an even number...
double diff = x - (double)xint;
if (diff == -0.5)
return double(xint - 1);
}
return double(xint);
}
else
{
__int64 xint = (__int64)(x - 0.5);
if (xint % 2)
{
// then we might have an even number...
double diff = x - (double)xint;
if (diff == 0.5)
return double(xint + 1);
}
return double(xint);
}
}
#endif // ifdef WIN32
int KinematicsLib::initializeMembers()
{
_type = -1;
_matrixInit = false;
_dof = -1;
_dom = -1;
_angOffInit = false;
_angRanInit = false;
_immobile = 0;
_thetaimmobile = 0.0;
_initialized = false;
for (int i = 0; i < 4; ++i)
{
_tcpOffset[i] = 0.0;
}
return 1;
}
int KinematicsLib::setAngleMinMax()
{
int dir;
for (int i = 0; i < _dof; i++)
{
dir = sign(_encoderOffset[i]) * _rotDir[i];
if (dir < 0)
{
_angleMin[i] = _angleOffset[i];
_angleMax[i] = _angleOffset[i] + _angleRange[i];
}
else
{
_angleMax[i] = _angleOffset[i];
_angleMin[i] = _angleOffset[i] - _angleRange[i];
}
_data(i + 1, 6) = _angleMin[i];
_data(i + 1, 7) = _angleMax[i];
}
return 1;
}
int KinematicsLib::initDofMat(int dof)
{
_dof = dof;
_dom = _dof;
_data = Matrix(_dof, 23);
_data = 0.0;
_matrixInit = true;
return 1;
}
int KinematicsLib::angleArrMDH2vecK4D(const double arr[], std::vector< double >* angleK4D)
{
if (_type < 0)
return -1;
std::vector< double > angleMDH;
for (int i = 0; i < _dom; ++i)
{
angleMDH.push_back(arr[i]);
}
angleK4D->clear();
mDH2K4DAng(angleMDH, *angleK4D);
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setType(int type)
{
std::vector< double > angOff;
double angStopArr[MaxDof];
std::vector< double > angStop;
std::vector< double > lengths;
switch (type)
{
case K_6M90A_F: // 0
_type = type;
initDofMat(Dof_90);
_data << Katana6M90A_F_data;
for (int i = 0; i < _dof; i++)
{
_data(i + 1, 3) *= LENGTH_MULTIPLIER;
_data(i + 1, 4) *= LENGTH_MULTIPLIER;
}
for (int i = 0; i < _dof; i++)
{
_epc[i] = Encoder_per_cycle[i];
_encoderOffset[i] = Encoder_offset[i];
_rotDir[i] = Rotation_direction[i];
_angleOffset[i] = Angle_offset_90A_F[i];
_angleRange[i] = Angle_range_90A_F[i];
}
_angOffInit = true;
_angRanInit = true;
setAngleMinMax();
for (int i = 0; i < 4; i++)
{
_linkLength[i] = Link_length_90A_F[i];
}
// analytical guess
_anaGuess = (AnaGuess::Kinematics*)new AnaGuess::Kinematics6M90T();
angleArrMDH2vecK4D(_angleOffset, &angOff);
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
_anaGuess->setAngStop(angStop);
for (int i = 0; i < 4; ++i)
{
lengths.push_back(_linkLength[i] * 1000);
}
_anaGuess->setLinkLength(lengths);
break;
case K_6M90A_G: // 1
_type = type;
initDofMat(Dof_90);
_data << Katana6M90A_G_data;
for (int i = 0; i < _dof; i++)
{
_data(i + 1, 3) *= LENGTH_MULTIPLIER;
_data(i + 1, 4) *= LENGTH_MULTIPLIER;
}
_dom = Dof_90 - 1;
_immobile = true;
_thetaimmobile = _data(_dof, 2);
for (int i = 0; i < _dof; i++)
{
_epc[i] = Encoder_per_cycle[i];
_encoderOffset[i] = Encoder_offset[i];
_rotDir[i] = Rotation_direction[i];
_angleOffset[i] = Angle_offset_90A_G[i];
_angleRange[i] = Angle_range_90A_G[i];
}
_angOffInit = true;
_angRanInit = true;
setAngleMinMax();
for (int i = 0; i < 4; i++)
{
_linkLength[i] = Link_length_90A_G[i];
}
// analytical guess
_anaGuess = (AnaGuess::Kinematics*)new AnaGuess::Kinematics6M90G();
angleArrMDH2vecK4D(_angleOffset, &angOff);
angOff.push_back(-2.150246); // immobile angle in mDH
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // immobile angle in mDH
_anaGuess->setAngStop(angStop);
for (int i = 0; i < 4; ++i)
{
lengths.push_back(_linkLength[i] * 1000);
}
_anaGuess->setLinkLength(lengths);
break;
case K_6M180: // 2
_type = type;
initDofMat(Dof_180);
_data << Katana6M180_data;
for (int i = 0; i < _dof; i++)
{
_data(i + 1, 3) *= LENGTH_MULTIPLIER;
_data(i + 1, 4) *= LENGTH_MULTIPLIER;
}
for (int i = 0; i < _dof; i++)
{
_epc[i] = Encoder_per_cycle[i];
_encoderOffset[i] = Encoder_offset[i];
_rotDir[i] = Rotation_direction[i];
_angleOffset[i] = Angle_offset_180[i];
_angleRange[i] = Angle_range_180[i];
}
_angOffInit = true;
_angRanInit = true;
setAngleMinMax();
for (int i = 0; i < 4; i++)
{
_linkLength[i] = Link_length_180[i];
}
// analytical guess
_anaGuess = (AnaGuess::Kinematics*)new AnaGuess::Kinematics6M180();
angleArrMDH2vecK4D(_angleOffset, &angOff);
angOff.push_back(-2.150246); // angle not present in mDH
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // angle not present in mDH
_anaGuess->setAngStop(angStop);
for (int i = 0; i < 4; ++i)
{
lengths.push_back(_linkLength[i] * 1000);
}
_anaGuess->setLinkLength(lengths);
break;
case K_6M90B_F: // 3
_type = type;
initDofMat(Dof_90);
_data << Katana6M90B_F_data;
for (int i = 0; i < _dof; i++)
{
_data(i + 1, 3) *= LENGTH_MULTIPLIER;
_data(i + 1, 4) *= LENGTH_MULTIPLIER;
}
for (int i = 0; i < _dof; i++)
{
_epc[i] = Encoder_per_cycle[i];
_encoderOffset[i] = Encoder_offset[i];
_rotDir[i] = Rotation_direction[i];
_angleOffset[i] = Angle_offset_90B_F[i];
_angleRange[i] = Angle_range_90B_F[i];
}
_angOffInit = true;
_angRanInit = true;
setAngleMinMax();
for (int i = 0; i < 4; i++)
{
_linkLength[i] = Link_length_90B_F[i];
}
// analytical guess
_anaGuess = (AnaGuess::Kinematics*)new AnaGuess::Kinematics6M90T();
angleArrMDH2vecK4D(_angleOffset, &angOff);
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
_anaGuess->setAngStop(angStop);
for (int i = 0; i < 4; ++i)
{
lengths.push_back(_linkLength[i] * 1000);
}
_anaGuess->setLinkLength(lengths);
break;
case K_6M90B_G: // 4
_type = type;
initDofMat(Dof_90);
_data << Katana6M90B_G_data;
for (int i = 0; i < _dof; i++)
{
_data(i + 1, 3) *= LENGTH_MULTIPLIER;
_data(i + 1, 4) *= LENGTH_MULTIPLIER;
}
_dom = Dof_90 - 1;
_immobile = true;
_thetaimmobile = _data(_dof, 2);
for (int i = 0; i < _dof; i++)
{
_epc[i] = Encoder_per_cycle[i];
_encoderOffset[i] = Encoder_offset[i];
_rotDir[i] = Rotation_direction[i];
_angleOffset[i] = Angle_offset_90B_G[i];
_angleRange[i] = Angle_range_90B_G[i];
}
_angOffInit = true;
_angRanInit = true;
setAngleMinMax();
for (int i = 0; i < 4; i++)
{
_linkLength[i] = Link_length_90B_G[i];
}
// analytical guess
_anaGuess = (AnaGuess::Kinematics*)new AnaGuess::Kinematics6M90G();
angleArrMDH2vecK4D(_angleOffset, &angOff);
angOff.push_back(-2.150246); // immobile angle in mDH
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // immobile angle in mDH
_anaGuess->setAngStop(angStop);
for (int i = 0; i < 4; ++i)
{
lengths.push_back(_linkLength[i] * 1000);
}
_anaGuess->setLinkLength(lengths);
break;
default:
return -1;
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setMDH(std::vector< double > theta, std::vector< double > d, std::vector< double > a,
std::vector< double > alpha, int typeNr)
{
// check vector sizes
if (_dof == -1)
{
if ((int)theta.size() > MaxDof)
return -1;
initDofMat(theta.size());
}
if ((int)theta.size() != _dof || (int)d.size() != _dof || (int)a.size() != _dof || (int)alpha.size() != _dof)
{
return -1;
}
if (typeNr >= 0)
typeNr = -2;
for (int i = 0; i < _dof; ++i)
{
_data(i + 1, 2) = theta.at(i);
_data(i + 1, 3) = d.at(i) * LENGTH_MULTIPLIER;
_data(i + 1, 4) = a.at(i) * LENGTH_MULTIPLIER;
_data(i + 1, 5) = alpha.at(i);
_data(i + 1, 23) = 0;
}
_dom = _dof;
_immobile = false;
_type = typeNr;
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setLinkLen(std::vector< double > links)
{
if ((_dof == -1) || ((int)links.size() != 4))
return -1;
switch (_type)
{
case K_6M90A_F: // 0
case K_6M90A_G: // 1
case K_6M90B_F: // 3
case K_6M90B_G: // 4
_data(3, 4) = links.at(0) * LENGTH_MULTIPLIER;
_data(4, 4) = links.at(1) * LENGTH_MULTIPLIER;
_data(5, 3) = links.at(2) * LENGTH_MULTIPLIER;
_data(6, 3) = links.at(3) * LENGTH_MULTIPLIER;
break;
case K_6M180: // 2
_data(3, 4) = links.at(0) * LENGTH_MULTIPLIER;
_data(4, 4) = links.at(1) * LENGTH_MULTIPLIER;
_data(5, 3) = (links.at(2) + links.at(3)) * LENGTH_MULTIPLIER;
break;
default:
return -1;
}
// store in _linkLength
for (int i = 0; i < 4; ++i)
{
_linkLength[i] = links.at(i);
}
// set in AnalyticalGuess
std::vector< double > lengths;
for (int i = 0; i < 4; ++i)
{
lengths.push_back(_linkLength[i] * 1000);
}
_anaGuess->setLinkLength(lengths);
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setImmob(int immob)
{
if (_dof == -1 || immob < 0 || immob > 1)
{
return -1;
}
_data(_dof, 23) = immob;
_immobile = immob;
if (immob)
{
_dom = _dof - 1;
_thetaimmobile = _data(_dof, 2);
}
else
{
_dom = _dof;
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setEPC(std::vector< int > epc)
{
if ((int)epc.size() < _dom)
{
return -1;
}
for (int i = 0; i < _dom; ++i)
{
_epc[i] = epc.at(i);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setEncOff(std::vector< int > encOffset)
{
if ((int)encOffset.size() < _dom)
{
return -1;
}
for (int i = 0; i < _dom; ++i)
{
_encoderOffset[i] = encOffset.at(i);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setRotDir(std::vector< int > rotDir)
{
if ((int)rotDir.size() < _dom)
{
return -1;
}
for (int i = 0; i < _dom; ++i)
{
if (rotDir.at(i) < 0)
{
_rotDir[i] = -1;
}
else
{
_rotDir[i] = 1;
}
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setAngOff(std::vector< double > angleOffset)
{
if ((int)angleOffset.size() < _dom)
{
return -1;
}
for (int i = 0; i < _dom; ++i)
{
_angleOffset[i] = angleOffset.at(i);
}
_angOffInit = true;
if (_angRanInit)
setAngleMinMax();
// analytical guess
std::vector< double > angOff;
double angStopArr[MaxDof];
std::vector< double > angStop;
switch (_type)
{
case K_6M90A_F: // 0
case K_6M90B_F: // 3
angleArrMDH2vecK4D(_angleOffset, &angOff);
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
_anaGuess->setAngStop(angStop);
break;
case K_6M90A_G: // 1
case K_6M90B_G: // 4
angleArrMDH2vecK4D(_angleOffset, &angOff);
angOff.push_back(-2.150246); // immobile angle in mDH
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // immobile angle in mDH
_anaGuess->setAngStop(angStop);
break;
case K_6M180: // 2
angleArrMDH2vecK4D(_angleOffset, &angOff);
angOff.push_back(-2.150246); // angle not present in mDH
_anaGuess->setAngOff(angOff);
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // angle not present in mDH
_anaGuess->setAngStop(angStop);
break;
default:
break;
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setAngRan(std::vector< double > angleRange)
{
if ((int)angleRange.size() < _dom)
{
return -1;
}
for (int i = 0; i < _dom; ++i)
{
_angleRange[i] = angleRange.at(i);
}
_angRanInit = true;
if (_angOffInit)
setAngleMinMax();
// analytical guess
double angStopArr[MaxDof];
std::vector< double > angStop;
switch (_type)
{
case K_6M90A_F: // 0
case K_6M90B_F: // 3
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
_anaGuess->setAngStop(angStop);
break;
case K_6M90A_G: // 1
case K_6M90B_G: // 4
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // immobile angle in mDH
_anaGuess->setAngStop(angStop);
break;
case K_6M180: // 2
for (int i = 0; i < _dom; ++i)
{
angStopArr[i] = _angleOffset[i] - sign(_encoderOffset[i]) * _rotDir[i] * _angleRange[i];
}
angleArrMDH2vecK4D(angStopArr, &angStop);
angStop.push_back(3.731514); // angle not present in mDH
_anaGuess->setAngStop(angStop);
break;
default:
break;
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::setTcpOff(std::vector< double > tcpOffset)
{
if ((int)tcpOffset.size() < 4)
{
return -1;
}
for (int i = 0; i < 4; ++i)
{
_tcpOffset[i] = tcpOffset.at(i);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getType()
{
return _type;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getMaxDOF()
{
return MaxDof;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getDOF()
{
return _dof;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getDOM()
{
return _dom;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getMDH(std::vector< double >& theta, std::vector< double >& d, std::vector< double >& a,
std::vector< double >& alpha)
{
if (_dof == -1)
return -1;
theta.clear();
d.clear();
a.clear();
alpha.clear();
for (int i = 0; i < _dof; ++i)
{
theta.push_back(_data(i + 1, 2));
d.push_back(_data(i + 1, 3) / LENGTH_MULTIPLIER);
a.push_back(_data(i + 1, 4) / LENGTH_MULTIPLIER);
alpha.push_back(_data(i + 1, 5));
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getImmob()
{
return _immobile;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getEPC(std::vector< int >& epc)
{
if (_dof == -1)
return -1;
epc.clear();
for (int i = 0; i < _dom; ++i)
{
epc.push_back(_epc[i]);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getEncOff(std::vector< int >& encOffset)
{
if (_dof == -1)
return -1;
encOffset.clear();
for (int i = 0; i < _dom; ++i)
{
encOffset.push_back(_encoderOffset[i]);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getRotDir(std::vector< int >& rotDir)
{
if (_dof == -1)
return -1;
rotDir.clear();
for (int i = 0; i < _dom; ++i)
{
rotDir.push_back(_rotDir[i]);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getAngOff(std::vector< double >& angleOffset)
{
if (_dof == -1)
return -1;
angleOffset.clear();
for (int i = 0; i < _dom; ++i)
{
angleOffset.push_back(_angleOffset[i]);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getAngRan(std::vector< double >& angleRange)
{
if (_dof == -1)
return -1;
angleRange.clear();
for (int i = 0; i < _dom; ++i)
{
angleRange.push_back(_angleRange[i]);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getAngStop(std::vector< double >& angleStop)
{
std::vector< double > angoff;
int okcount = getAngOff(angoff);
std::vector< int > encoff;
okcount += getEncOff(encoff);
std::vector< int > rotdir;
okcount += getRotDir(rotdir);
std::vector< double > angran;
okcount += getAngRan(angran);
angleStop.clear();
for (int i = 0; i < _dom; i++)
{
angleStop.push_back(angoff.at(i) - (sign(encoff.at(i)) * rotdir.at(i)) * (angran.at(i)));
}
int ok = (okcount == 4) ? 1 : 0;
return ok;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getAngMin(std::vector< double >& angleMin)
{
std::vector< double > angoff;
int okcount = getAngOff(angoff);
std::vector< double > angstop;
okcount += getAngStop(angstop);
angleMin.clear();
for (int i = 0; i < _dom; ++i)
{
angleMin.push_back(min(angoff.at(i), angstop.at(i)));
}
int ok = (okcount == 2) ? 1 : 0;
return ok;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getAngMax(std::vector< double >& angleMax)
{
std::vector< double > angoff;
int okcount = getAngOff(angoff);
std::vector< double > angstop;
okcount += getAngStop(angstop);
angleMax.clear();
for (int i = 0; i < _dom; ++i)
{
angleMax.push_back(max(angoff.at(i), angstop.at(i)));
}
int ok = (okcount == 2) ? 1 : 0;
return ok;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getTcpOff(std::vector< double >& tcpOffset)
{
if (_dof == -1)
return -1;
tcpOffset.clear();
for (int i = 0; i < 4; ++i)
{
tcpOffset.push_back(_tcpOffset[i]);
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::getVersion(std::vector< int >& version)
{
version.clear();
version.push_back(KINLIB_VERSION_MAJOR);
version.push_back(KINLIB_VERSION_MINOR);
version.push_back(KINLIB_VERSION_REVISION);
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::init()
{
if (!_matrixInit || !_angOffInit || !_angRanInit)
return -1;
_robot = mRobot(_data);
_initialized = true;
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::K4D2mDHAng(std::vector< double > angleK4D, std::vector< double >& angleMDH)
{
if (_type == -1)
return -1;
if ((int)angleK4D.size() < _dom)
return -1;
angleMDH.clear();
// for all models the same
angleMDH.push_back(angleK4D.at(0) - mPi);
angleMDH.push_back(angleK4D.at(1));
angleMDH.push_back(angleK4D.at(2) - mPi);
angleMDH.push_back(mPi / 2.0 - angleK4D.at(3));
// model specific
switch (_type)
{
case K_6M90A_F: // 0
case K_6M90B_F: // 3
angleMDH.push_back(mPi / 2.0 - angleK4D.at(4));
angleMDH.push_back(mPi / 2.0 - angleK4D.at(5));
break;
case K_6M90A_G: // 1
case K_6M90B_G: // 4
angleMDH.push_back(mPi / 2.0 - angleK4D.at(4));
break;
case K_6M180: // 2
angleMDH.push_back(-1.0 * angleK4D.at(4) + 3.0 * mPi / 2.0);
break;
default:
return -1;
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::mDH2K4DAng(std::vector< double > angleMDH, std::vector< double >& angleK4D)
{
if (_type == -1)
return -1;
if ((int)angleMDH.size() < _dom)
return -1;
angleK4D.clear();
// for all models the same
angleK4D.push_back(angleMDH.at(0) + mPi);
angleK4D.push_back(angleMDH.at(1));
angleK4D.push_back(angleMDH.at(2) + mPi);
angleK4D.push_back(mPi / 2.0 - angleMDH.at(3));
// model specific
switch (_type)
{
case K_6M90A_F: // 0
case K_6M90B_F: // 3
angleK4D.push_back(mPi / 2.0 - angleMDH.at(4));
angleK4D.push_back(mPi / 2.0 - angleMDH.at(5));
break;
case K_6M90A_G: // 1
case K_6M90B_G: // 4
angleK4D.push_back(mPi / 2.0 - angleMDH.at(4));
break;
case K_6M180: // 2
angleK4D.push_back(-1.0 * angleMDH.at(4) + 3.0 * mPi / 2.0);
break;
default:
return -1;
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::enc2rad(std::vector< int > encoders, std::vector< double >& angles)
{
if ((int)encoders.size() < _dom)
return -1;
angles.clear();
for (int i = 0; i < _dom; ++i)
{
angles.push_back(_angleOffset[i] +
_rotDir[i] * (encoders.at(i) - _encoderOffset[i]) * 2.0 * mPi / ((double)_epc[i]));
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::rad2enc(std::vector< double > angles, std::vector< int >& encoders)
{
if ((int)angles.size() < _dom)
return -1;
encoders.clear();
for (int i = 0; i < _dom; ++i)
{
encoders.push_back(
(int)round(_encoderOffset[i] + _rotDir[i] * (angles.at(i) - _angleOffset[i]) * _epc[i] / (2 * mPi)));
}
return 1;
}
///////////////////////////////////////////////////////////////////////
int KinematicsLib::directKinematics(std::vector< double > angles, std::vector< double >& pose)
{
if (!_initialized || (int)angles.size() < _dom)
return -1;
// Angles in ColumnVector
ColumnVector qr = ColumnVector(_dof);
for (int k = 0; k < _dof; ++k)
{
if (k == _dom)
{
// immobile = 1: _dom == _dof - 1
qr(k + 1) = (float)_thetaimmobile;
}
else
{
qr(k + 1) = angles.at(k);
}
}
_robot.set_q(qr);
// Calculate kinematics
Matrix TCP_Position = _robot.kine();
TCP_Position(1, 4) /= LENGTH_MULTIPLIER;
TCP_Position(2, 4) /= LENGTH_MULTIPLIER;
TCP_Position(3, 4) /= LENGTH_MULTIPLIER;
// adjust TCP offset
// transformation from flange (kinematics tcp) to effective tcp (with offset)
Matrix TCP_Offset(4, 4);
TCP_Offset.row(1) << 1.0 << 0.0 << 0.0 << _tcpOffset[0];
TCP_Offset.row(2) << 0.0 << cos(_tcpOffset[3]) << -sin(_tcpOffset[3]) << _tcpOffset[1];
TCP_Offset.row(3) << 0.0 << sin(_tcpOffset[3]) << cos(_tcpOffset[3]) << _tcpOffset[2];
TCP_Offset.row(4) << 0.0 << 0.0 << 0.0 << 1.0;
TCP_Position = TCP_Position * TCP_Offset;
pose.clear();
// x-Position
pose.push_back(TCP_Position(1, 4));
// y-Position
pose.push_back(TCP_Position(2, 4));
// z-Position
pose.push_back(TCP_Position(3, 4));
// Calculate euler angles
ColumnVector eul = ieulzxz(TCP_Position);
// Phi
pose.push_back(eul(1));
// Theta
pose.push_back(eul(2));
// Psi
pose.push_back(eul(3));
return 1;
}
///// IK HELPER FUNCTIONS /////////////////////////////////////////////
// single inverse kinematics
int KinematicsLib::invKin(std::vector< double > pose, std::vector< double > prev, std::vector< double >& angle)
{
if ((int)pose.size() < 6 || (int)prev.size() < _dof)
return -1;
// IK algorithm type to use
const int ikalgo = 0; // based on Jacobian (faster)
// const int ikalgo = 1; // based on derivative of T (converge more often)
// ReturnMatrix eulzxz(const ColumnVector & a);
ColumnVector v(3);
v(1) = pose.at(3);
v(2) = pose.at(4);
v(3) = pose.at(5);
Matrix Pos = eulzxz(v);
Pos(1, 4) = pose.at(0) * LENGTH_MULTIPLIER;
Pos(2, 4) = pose.at(1) * LENGTH_MULTIPLIER;
Pos(3, 4) = pose.at(2) * LENGTH_MULTIPLIER;
// Set previous angles
ColumnVector qs = ColumnVector(_dof);
for (int j = 0; j < _dof; ++j)
{
qs(j + 1) = prev.at(j);
}
_robot.set_q(qs);
bool converge = false;
ColumnVector q0 = _robot.inv_kin(Pos, ikalgo, _dof, converge);
angle.clear();
for (int j = 0; j < _dom; ++j)
{
angle.push_back(q0(j + 1));
}
if (_immobile == 1)
angle.push_back(_thetaimmobile);
int ok = 1;
if (!converge)
ok = -1;
return ok;
}
// inverse kinematics using bisection if no solution found
int KinematicsLib::invKin_bisec(std::vector< double > pose, std::vector< double > prev, std::vector< double >& conf,
int maxBisection)
{
if ((int)pose.size() < 6 || (int)prev.size() < _dof || maxBisection < 0)
return -1;
int ok = invKin(pose, prev, conf);
// Orig 3D pose
// Orig JS prev angle
// Bisec 3D prev1pose prev2pose pose
// Bisec JS prev prev2conf conf
if (ok < 0 && maxBisection > 0)
{
// prev1pose
std::vector< double > prev1pose;
directKinematics(prev, prev1pose);
// prev2pose
std::vector< double > prev2pose;
for (int i = 0; i < 6; ++i)
prev2pose.push_back(prev1pose.at(i) + pose.at(i) / 2.0);
// prev2conf (IK on first part)
std::vector< double > prev2conf;
ok = inverseKinematics(prev2pose, prev, prev2conf, maxBisection - 1);
if (ok == 1)
{
// conf (IK on second part, only if first part successful)
ok = inverseKinematics(pose, prev2conf, conf, maxBisection - 1);
}
}
return ok;
}
// analytical guess
int KinematicsLib::anaGuess(std::vector< double > pose, std::vector< double > prev, std::vector< double >& angle)
{
if (_type < 0 || (int)pose.size() < 6 || (int)prev.size() < _dof)
return -1;
std::vector< double > positions;
for (int i = 0; i < 6; ++i)
{
if (i < 3)
positions.push_back(pose.at(i) * 1000);
else
positions.push_back(pose.at(i));
}
std::vector< double > previous_angles;
std::vector< double > prevK4D;
mDH2K4DAng(prev, prevK4D);
for (int i = 0; i < _dom; ++i)
{
previous_angles.push_back(prevK4D.at(i));
}
if (_dom == 5)
{
// give 6 previous angles to the analytical kinematics
previous_angles.push_back(0.0);
}
std::vector< double > anglesK4D;
int error;
try
{
error = ((int)_anaGuess->inverseKinematics(anglesK4D, positions, previous_angles)) - 1;
K4D2mDHAng(anglesK4D, angle);
if (_immobile)
angle.push_back(_thetaimmobile);
}
catch (AnaGuess::NoSolutionException nse)
{
error = -2;
}
catch (AnaGuess::Exception e)
{
error = e.errorNumber() - 2;
}
if (error != 0)
{
angle.clear();
for (int i = 0; i < _dof; ++i)
angle.push_back(prev.at(i));
}
int ok = (error == 0) ? 1 : -1;
return ok;
}
bool KinematicsLib::checkConfig(std::vector< double > config, std::vector< double > pose, double tol)
{
std::vector< double > configpose;
directKinematics(config, configpose);
double posdiff = 0.0;
for (int i = 0; i < 6; ++i)
{
posdiff += abs(pose.at(i) - configpose.at(i));
}
bool ok;
if (posdiff > tol)
ok = false;
else
ok = true;
return ok;
}
///// END IK HELPER FUNCTIONS /////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
int KinematicsLib::inverseKinematics(std::vector< double > pose, std::vector< double > prev,
std::vector< double >& angles, int maxBisection)
{
if (!_initialized || (int)pose.size() < 6 || (int)prev.size() < _dom || maxBisection < 0)
return -1;
// tolerance for configuration check (sum of 3 * meter + 3 * radian)
double tol = 0.0001;
// adjust TCP offset
// pose to matrix
ColumnVector v(3);
v(1) = pose.at(3);
v(2) = pose.at(4);
v(3) = pose.at(5);
Matrix Pos = eulzxz(v);
Pos(1, 4) = pose.at(0);
Pos(2, 4) = pose.at(1);
Pos(3, 4) = pose.at(2);
// transformation from effective tcp (with offset) to flange (kinematics tcp)
Matrix TCP_Offset(4, 4);
TCP_Offset.row(1) << 1.0 << 0.0 << 0.0 << -_tcpOffset[0];
TCP_Offset.row(2) << 0.0 << cos(_tcpOffset[3]) << sin(_tcpOffset[3])
<< (-_tcpOffset[1] * cos(_tcpOffset[3]) - _tcpOffset[2] * sin(_tcpOffset[3]));
TCP_Offset.row(3) << 0.0 << -sin(_tcpOffset[3]) << cos(_tcpOffset[3])
<< (_tcpOffset[1] * sin(_tcpOffset[3]) - _tcpOffset[2] * cos(_tcpOffset[3]));
TCP_Offset.row(4) << 0.0 << 0.0 << 0.0 << 1.0;
Pos = Pos * TCP_Offset;
// matrix to pose
std::vector< double > flangepose;
flangepose.push_back(Pos(1, 4));
flangepose.push_back(Pos(2, 4));
flangepose.push_back(Pos(3, 4));
ColumnVector eul = ieulzxz(Pos);
if (_type != K_6M180)
{
flangepose.push_back(eul(1));
}
else
{
// calculate phi from X and Y with K_6M180
// own impl. of atan w/ 2 args for K4D compatibility --JHA
double phi_calc = atan1(Pos(1, 4), Pos(2, 4)) + mPi / 2.0;
if (Pos(1, 4) * eul(1) < 0)
{
// X and given phi different sign -> tool point inwards
phi_calc += mPi;
}
// bring phi in range [-mPi,mPi)
phi_calc = fmod(phi_calc + mPi, 2.0 * mPi) - mPi;
// bring phi in range (-mPi,mPi]
if (phi_calc == -mPi)
phi_calc += 2.0 * mPi;
// store calculated phi
flangepose.push_back(phi_calc);
}
flangepose.push_back(eul(2));
flangepose.push_back(eul(3));
// Copy and complete prev
std::vector< double > prev1conf;
for (int i = 0; i < _dof; ++i)
{
if (i == _dom)
{
// immobile = 1: _dom == _dof - 1
prev1conf.push_back(_thetaimmobile);
}
else
{
prev1conf.push_back(prev.at(i));
}
}
std::vector< double > conf;
// calculate inverse kinematics (roboop)
int ok = invKin_bisec(flangepose, prev1conf, conf, maxBisection);
// on fail try turning phi about pi (switch inward / outward) with K_6M180
if (ok < 0 && _type == K_6M180)
{
if (flangepose[3] > 0)
flangepose[3] -= mPi;
else
flangepose[3] += mPi;
ok = invKin_bisec(flangepose, prev1conf, conf, maxBisection);
}
// if no solution found and type is 6M robot, get analytical guess
if (ok < 0 && _type >= 0)
{
std::vector< double > guess;
ok = anaGuess(flangepose, prev1conf, guess);
// if analytical guess found, calculate inverse kinematics using guess
if (ok == 1)
{
ok = invKin_bisec(flangepose, guess, conf, maxBisection);
// check solution
if (checkConfig(conf, pose, tol) == false) // use effective pose!
ok = -1; // wrong solution
}
// if no guess or solution found, get analytical guess of near pose
if (ok < 0)
{
std::vector< double > nearpose;
nearpose.push_back(flangepose.at(0) - sign(flangepose.at(0)) * 0.05);
nearpose.push_back(flangepose.at(1) - sign(flangepose.at(1)) * 0.05);
nearpose.push_back(flangepose.at(2) - sign(flangepose.at(2)) * 0.05);
nearpose.push_back(flangepose.at(3) - sign(flangepose.at(3)) * 0.2);
nearpose.push_back(flangepose.at(4) - sign(flangepose.at(4) - mPi / 2.0) * 0.2);
nearpose.push_back(flangepose.at(5) - sign(flangepose.at(5)) * 0.2);
ok = anaGuess(nearpose, prev1conf, guess);
// if analytical guess found, calculate inverse kinematics using guess
if (ok == 1)
{
ok = invKin_bisec(flangepose, guess, conf, maxBisection);
// check solution
if (checkConfig(conf, pose, tol) == false)
ok = -1; // wrong solution
}
}
}
// set angle if solution found
angles.clear();
if (ok == 1)
{
for (int i = 0; i < _dom; ++i)
angles.push_back(conf.at(i));
}
else
{
// set prev if no solution found
for (int i = 0; i < _dom; ++i)
angles.push_back(prev.at(i));
}
return ok;
}
| 26.803817 | 116 | 0.53812 | [
"vector",
"model",
"3d"
] |
00a5f30768a2bc55099f332b563252ceea04b3a4 | 12,491 | cpp | C++ | IniFile_Static/test/TestIniFile.cpp | CruiseYoung/IniFile | 7f0a50c0cce11e8151fbe739ee42f6c9ab9a8a47 | [
"Apache-2.0"
] | 2 | 2017-04-30T04:40:59.000Z | 2020-08-28T07:41:41.000Z | IniFile_Static/test/TestIniFile.cpp | CruiseYoung/IniFile | 7f0a50c0cce11e8151fbe739ee42f6c9ab9a8a47 | [
"Apache-2.0"
] | null | null | null | IniFile_Static/test/TestIniFile.cpp | CruiseYoung/IniFile | 7f0a50c0cce11e8151fbe739ee42f6c9ab9a8a47 | [
"Apache-2.0"
] | 6 | 2015-08-13T10:00:12.000Z | 2021-09-07T02:58:44.000Z | // TestCIniFile::cpp : Defines the entry point for the console application.
//
#include "../src/inifile.h"
#include <iostream>
using namespace std;
void Show(string const& FileName)
{
cout << endl
<< "++++++++++++++++++++++++++++++++++++++++"
<< endl
<< "+ Contents of the file are below +"
<< endl
<< "++++++++++++++++++++++++++++++++++++++++"
<< endl
<< IniFile::Content(FileName)
<< endl
<< "++++++++++++++++++++++++++++++++++++++++"
<< endl << endl;
system("PAUSE");
system("cls");
}
int main(int argc, char* argv[])
{
string str_num = "555";
cout << convert<int>(str_num) << endl;
float f_num = 666.0f;
cout << convert<string>(f_num) << endl;
system("PAUSE");
system("cls");
const string FileName = "test.ini";
// Create a new file
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to create a new file called \"test.ini\"" << endl << endl;
cout << "string FileName = \"test.ini\";" << endl;
cout << "IniFile::Create(FileName);" << endl << endl;
if (IniFile::Create(FileName)) cout << "File was successfully created" << endl << endl;
else cout << "Failed to create the file" << endl << endl;
Show(FileName);
// Create a new section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to create a new section called [MySection]" << endl << endl;
cout << "IniFile::AddSection(\"MySection\", FileName);" << endl << endl;
if (IniFile::AddSection("MySection", FileName)) cout << "Section was successfully created" << endl << endl;
else cout << "Failed to create the section" << endl << endl;
Show(FileName);
// Add a key to the section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to add a new key/value (MyKey=MyValue) to [MySection]" << endl << endl;
cout << "IniFile::SetValue(\"MyKey\",\"MyValue\",\"MySection\",FileName);" << endl << endl;
if (IniFile::SetValue("MyKey", "MyValue", "MySection", FileName)) cout << "Record was successfully created" << endl << endl;
else cout << "Failed to create the record" << endl << endl;
Show(FileName);
// Add a key and create a section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to add a new key/value (TestKey=TestValue)" << endl << "and create a new section [TestSection] at the same time" << endl << endl;
cout << "IniFile::SetValue(\"TestKey\",\"TestValue\",\"TestSection\",FileName);" << endl << endl;
if (IniFile::SetValue("TestKey", "TestValue", "TestSection", FileName)) cout << "Record and section were successfully created" << endl << endl;
else cout << "Failed to create the record and section" << endl << endl;
Show(FileName);
// Change a key value
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to change the key/value for (MyKey=MyValue) to (MyKey=YourValue)" << endl << endl;
cout << "IniFile::SetValue(\"MyKey\",\"YourValue\",\"MySection\",FileName);" << endl << endl;
if (IniFile::SetValue("MyKey", "YourValue", "MySection", FileName)) cout << "Record was successfully changed" << endl << endl;
else cout << "Failed to change the record" << endl << endl;
Show(FileName);
// Get a value
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to get the value of MyKey" << endl << endl;
cout << "IniFile::GetValue(\"MyKey\",\"MySection\",FileName);" << endl << endl;
string v = IniFile::GetValue("MyKey", "MySection", FileName);
cout << "The value of MyKey is: " << v.c_str() << endl << endl;
Show(FileName);
// Get a vector of Sections
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to get a vector of sections" << endl << endl;
cout << "IniFile::GetSectionNames(FileName);" << endl << endl;
vector<string> s = IniFile::GetSectionNames(FileName);
cout << "The sections are returned as a std::vector<std::string>\n\n";
for (vector<string>::iterator iter = s.begin(); iter != s.end(); ++iter)
cout << iter->c_str() << endl;
Show(FileName);
// Section Exists
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to verify that [MySection] exists" << endl << endl;
cout << "IniFile::SectionExists(\"MySection\",FileName);" << endl << endl;
if (IniFile::SectionExists("MySection", FileName)) cout << "Section exists" << endl << endl;
else cout << "Section does not exist" << endl << endl;
Show(FileName);
// Record Exists
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to verify that MyKey exists" << endl << endl;
cout << "IniFile::RecordExists(\"MyKey\",\"MySection\",FileName);" << endl << endl;
if (IniFile::RecordExists("MyKey", "MySection", FileName)) cout << "Record exists" << endl << endl;
else cout << "Record does not exist" << endl << endl;
Show(FileName);
// Case Sensitive
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "BE CAREFUL - functions in IniFile are CASE-SENSITIVE" << endl << endl;
cout << "IniFile::RecordExists(\"mykey\",\"MySection\",FileName);" << endl << endl;
if (IniFile::RecordExists("mykey", "MySection", FileName)) cout << "Record exists" << endl << endl;
else cout << "Record does not exist" << endl << endl;
Show(FileName);
// Add a comment to the section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to add comments to [MySection]" << endl << endl;
cout << "IniFile::SetSectionComments(\"# This Section was created by IniFile\",\"MySection\",FileName);" << endl << endl;
if (IniFile::SetSectionComments("# This Section was created by IniFile", "MySection", FileName)) cout << "Comments were successfully added" << endl << endl;
else cout << "Failed to add the comments" << endl << endl;
Show(FileName);
// Add a comment to the record
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to add comments to MyKey" << endl << endl;
cout << "IniFile::SetRecordComments(\"# This Key was created by IniFile\",\"MyKey\",\"MySection\",FileName);" << endl << endl;
if (IniFile::SetRecordComments("# This Key was created by IniFile", "MyKey", "MySection", FileName)) cout << "Comments were successfully added" << endl << endl;
else cout << "Failed to add the comments" << endl << endl;
Show(FileName);
// Rename Section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to rename [MySection] to [YourSection]" << endl << endl;
cout << "IniFile::RenameSection(\"MySection\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::RenameSection("MySection", "YourSection", FileName)) cout << "Section was successfully changed" << endl << endl;
else cout << "Failed to change the section" << endl << endl;
Show(FileName);
// Multiple comments
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Multiple comments can be added by putting \\n# in the comments string" << endl << endl;
cout << "IniFile::SetSectionComments(\"# This Section was created by IniFile\\n# Kids, don't try this at home \\n\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::SetSectionComments("# This Section was created by IniFile\n# Kids, don't try this at home", "YourSection", FileName)) cout << "Comments were successfully added" << endl << endl;
else cout << "Failed to add the comments" << endl << endl;
Show(FileName);
// Remove comments
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Comments are removed by setting them to \"\"" << endl << endl;
cout << "IniFile::SetRecordComments(\"\",\"MyKey\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::SetRecordComments("", "MyKey", "YourSection", FileName)) cout << "Comments were successfully removed" << endl << endl;
else cout << "Failed to remove the comments" << endl << endl;
Show(FileName);
// Comment entire section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to comment the entire section [YourSection]" << endl << endl;
cout << "IniFile::CommentSection(\"#\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::CommentSection('#', "YourSection", FileName)) cout << "Section was successfully commented" << endl << endl;
else cout << "Failed to comment the section" << endl << endl;
Show(FileName);
// UnComment entire section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to un-comment the entire section [YourSection]" << endl << endl;
cout << "IniFile::UnCommentSection(\"YourSection\",FileName);" << endl << endl;
if (IniFile::UnCommentSection("YourSection", FileName)) cout << "Section was successfully un-commented" << endl << endl;
else cout << "Failed to un-comment the section" << endl << endl;
Show(FileName);
// Comment a single record
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to comment the record MyKey" << endl << endl;
cout << "(Note that both # and ; are recognized as commented lines by IniFile)" << endl << endl;
cout << "IniFile::CommentRecord(IniFile::CommentChar::Pound,\"MyKey\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::CommentRecord(IniFile::Pound, "MyKey", "YourSection", FileName)) cout << "Record was successfully commented" << endl << endl;
else cout << "Failed to comment the record" << endl << endl;
Show(FileName);
// UnComment a single record
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to un-comment the record MyKey" << endl << endl;
cout << "IniFile::UnCommentRecord(\"MyKey\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::UnCommentRecord("MyKey", "YourSection", FileName)) cout << "Record was successfully un-commented" << endl << endl;
else cout << "Failed to un-comment the record" << endl << endl;
Show(FileName);
// Sort
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to sort the file - false means ASCENDING, true means DESCENDING" << endl << endl;
cout << "(Note that the comments will stay with their targets)" << endl << endl;
cout << "IniFile::Sort(FileName,false);" << endl << endl;
if (IniFile::Sort(FileName, false)) cout << "File was successfully sorted" << endl << endl;
else cout << "Failed to sort the file" << endl << endl;
Show(FileName);
// Delete entire section
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to delete the entire section [TestSection]" << endl << endl;
cout << "IniFile::DeleteSection(\"TestSection\",FileName);" << endl << endl;
if (IniFile::DeleteSection("TestSection", FileName)) cout << "Section was successfully deleted" << endl << endl;
else cout << "Failed to delete the section" << endl << endl;
Show(FileName);
// Delete record
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Attempting to delete the record <yKey" << endl << endl;
cout << "IniFile::DeleteRecord(\"MyKey\",\"YourSection\",FileName);" << endl << endl;
if (IniFile::DeleteRecord("MyKey", "YourSection", FileName)) cout << "Record was successfully deleted" << endl << endl;
else cout << "Failed to delete the record" << endl << endl;
Show(FileName);
// Content
cout << "TestIniFile - Demo program for the IniFile Class" << endl << endl;
cout << "Finally, the content of the file can be retrieved as a std::string" << endl << endl;
cout << "IniFile::Content(FileName);" << endl << endl;
cout << "The contents of the file throughout this demo have used this function to display the contents below" << endl;
Show(FileName);
return 0;
}
| 54.785088 | 194 | 0.628132 | [
"vector"
] |
00a9f31e21213084f11add2f2a420908913d98c4 | 12,192 | cpp | C++ | src/lib/motion_planning/PositionSmoothing.cpp | lgarciaos/Firmware | 26dba1407bd1fbc65c23870a22fed904afba6347 | [
"BSD-3-Clause"
] | 4,224 | 2015-01-02T11:51:02.000Z | 2020-10-27T23:42:28.000Z | src/lib/motion_planning/PositionSmoothing.cpp | lgarciaos/Firmware | 26dba1407bd1fbc65c23870a22fed904afba6347 | [
"BSD-3-Clause"
] | 11,736 | 2015-01-01T11:59:16.000Z | 2020-10-28T17:13:38.000Z | src/lib/motion_planning/PositionSmoothing.cpp | lgarciaos/Firmware | 26dba1407bd1fbc65c23870a22fed904afba6347 | [
"BSD-3-Clause"
] | 11,850 | 2015-01-02T14:54:47.000Z | 2020-10-28T16:42:47.000Z | /****************************************************************************
*
* Copyright (c) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 "PositionSmoothing.hpp"
#include "TrajectoryConstraints.hpp"
#include <mathlib/mathlib.h>
#include <matrix/matrix/math.hpp>
#include <matrix/matrix/helper_functions.hpp>
void PositionSmoothing::_generateSetpoints(
const Vector3f &position,
const Vector3f(&waypoints)[3],
bool is_single_waypoint,
const Vector3f &feedforward_velocity,
float delta_time,
bool force_zero_velocity_setpoint,
PositionSmoothingSetpoints &out_setpoints)
{
Vector3f velocity_setpoint{0.f, 0.f, 0.f};
if (!force_zero_velocity_setpoint) {
velocity_setpoint = _generateVelocitySetpoint(position, waypoints, is_single_waypoint, feedforward_velocity);
}
out_setpoints.unsmoothed_velocity = velocity_setpoint;
_generateTrajectory(
position,
velocity_setpoint,
delta_time,
out_setpoints
);
}
bool PositionSmoothing::_isTurning(const Vector3f &target) const
{
const Vector2f vel_traj(_trajectory[0].getCurrentVelocity(),
_trajectory[1].getCurrentVelocity());
const Vector2f pos_traj(_trajectory[0].getCurrentPosition(),
_trajectory[1].getCurrentPosition());
const Vector2f target_xy(target);
const Vector2f u_vel_traj = vel_traj.unit_or_zero();
const Vector2f pos_to_target = Vector2f(target_xy - pos_traj);
const float cos_align = u_vel_traj * pos_to_target.unit_or_zero();
// The vehicle is turning if the angle between the velocity vector
// and the direction to the target is greater than 10 degrees, the
// velocity is large enough and the drone isn't in the acceptance
// radius of the last WP.
return (vel_traj.longerThan(0.2f)
&& cos_align < 0.98f
&& pos_to_target.longerThan(_target_acceptance_radius));
}
/* Constrain some value vith a constrain depending on the sign of the constraint
* Example: - if the constrain is -5, the value will be constrained between -5 and 0
* - if the constrain is 5, the value will be constrained between 0 and 5
*/
inline float _constrainOneSide(float val, float constraint)
{
const float min = (constraint < FLT_EPSILON) ? constraint : 0.f;
const float max = (constraint > FLT_EPSILON) ? constraint : 0.f;
return math::constrain(val, min, max);
}
inline float _constrainAbs(float val, float max)
{
return matrix::sign(val) * math::min(fabsf(val), fabsf(max));
}
float PositionSmoothing::_getMaxXYSpeed(const Vector3f(&waypoints)[3]) const
{
Vector3f pos_traj(_trajectory[0].getCurrentPosition(),
_trajectory[1].getCurrentPosition(),
_trajectory[2].getCurrentPosition());
math::trajectory::VehicleDynamicLimits config;
config.z_accept_rad = _vertical_acceptance_radius;
config.xy_accept_rad = _target_acceptance_radius;
config.max_acc_xy = _trajectory[0].getMaxAccel();
config.max_jerk = _trajectory[0].getMaxJerk();
config.max_speed_xy = _cruise_speed;
config.max_acc_xy_radius_scale = _horizontal_trajectory_gain;
// constrain velocity to go to the position setpoint first if the position setpoint has been modified by an external source
// (eg. Obstacle Avoidance)
Vector3f pos_to_waypoints[3] = {pos_traj, waypoints[1], waypoints[2]};
return math::trajectory::computeXYSpeedFromWaypoints<3>(pos_to_waypoints, config);
}
float PositionSmoothing::_getMaxZSpeed(const Vector3f(&waypoints)[3]) const
{
const auto &target = waypoints[1];
Vector3f pos_traj(_trajectory[0].getCurrentPosition(),
_trajectory[1].getCurrentPosition(),
_trajectory[2].getCurrentPosition());
const float distance_start_target = fabs(target(2) - pos_traj(2));
const float arrival_z_speed = 0.f;
float max_speed = math::min(_trajectory[2].getMaxVel(), math::trajectory::computeMaxSpeedFromDistance(
_trajectory[2].getMaxJerk(), _trajectory[2].getMaxAccel(),
distance_start_target, arrival_z_speed));
return max_speed;
}
const Vector3f PositionSmoothing::_getCrossingPoint(const Vector3f &position, const Vector3f(&waypoints)[3]) const
{
const auto &target = waypoints[1];
if (!_isTurning(target)) {
return target;
}
// Get the crossing point using L1-style guidance
auto l1_point = _getL1Point(position, waypoints);
return {l1_point(0), l1_point(1), target(2)};
}
const Vector2f PositionSmoothing::_getL1Point(const Vector3f &position, const Vector3f(&waypoints)[3]) const
{
const Vector2f pos_traj(_trajectory[0].getCurrentPosition(),
_trajectory[1].getCurrentPosition());
const Vector2f u_prev_to_target = Vector2f(waypoints[1] - waypoints[0]).unit_or_zero();
const Vector2f prev_to_pos(pos_traj - Vector2f(waypoints[0]));
const Vector2f prev_to_closest(u_prev_to_target * (prev_to_pos * u_prev_to_target));
const Vector2f closest_pt = Vector2f(waypoints[0]) + prev_to_closest;
// Compute along-track error using L1 distance and cross-track error
const float crosstrack_error = Vector2f(closest_pt - pos_traj).length();
const float l1 = math::max(_target_acceptance_radius, 5.f);
float alongtrack_error = 0.f;
// Protect against sqrt of a negative number
if (l1 > crosstrack_error) {
alongtrack_error = sqrtf(l1 * l1 - crosstrack_error * crosstrack_error);
}
// Position of the point on the line where L1 intersect the line between the two waypoints
const Vector2f l1_point = closest_pt + alongtrack_error * u_prev_to_target;
return l1_point;
}
const Vector3f PositionSmoothing::_generateVelocitySetpoint(const Vector3f &position, const Vector3f(&waypoints)[3],
bool is_single_waypoint,
const Vector3f &feedforward_velocity_setpoint)
{
// Interface: A valid position setpoint generates a velocity target using conservative motion constraints.
// If a velocity is specified, that is used as a feedforward to track the position setpoint
// (ie. it assumes the position setpoint is moving at the specified velocity)
// If the position setpoints are set to NAN, the values in the velocity setpoints are used as velocity targets: nothing to do here.
auto &target = waypoints[1];
const bool xy_target_valid = PX4_ISFINITE(target(0)) && PX4_ISFINITE(target(1));
const bool z_target_valid = PX4_ISFINITE(target(2));
Vector3f velocity_setpoint = feedforward_velocity_setpoint;
if (xy_target_valid && z_target_valid) {
// Use 3D position setpoint to generate a 3D velocity setpoint
Vector3f pos_traj(_trajectory[0].getCurrentPosition(),
_trajectory[1].getCurrentPosition(),
_trajectory[2].getCurrentPosition());
const Vector3f crossing_point = is_single_waypoint ? target : _getCrossingPoint(position, waypoints);
const Vector3f u_pos_traj_to_dest{(crossing_point - pos_traj).unit_or_zero()};
float xy_speed = _getMaxXYSpeed(waypoints);
const float z_speed = _getMaxZSpeed(waypoints);
if (!is_single_waypoint && _isTurning(target)) {
// Limit speed during a turn
xy_speed = math::min(_max_speed_previous, xy_speed);
} else {
_max_speed_previous = xy_speed;
}
Vector3f vel_sp_constrained = u_pos_traj_to_dest * sqrtf(xy_speed * xy_speed + z_speed * z_speed);
math::trajectory::clampToXYNorm(vel_sp_constrained, xy_speed, 0.5f);
math::trajectory::clampToZNorm(vel_sp_constrained, z_speed, 0.5f);
for (int i = 0; i < 3; i++) {
// If available, use the existing velocity as a feedforward, otherwise replace it
if (PX4_ISFINITE(velocity_setpoint(i))) {
velocity_setpoint(i) += vel_sp_constrained(i);
} else {
velocity_setpoint(i) = vel_sp_constrained(i);
}
}
}
else if (xy_target_valid) {
// Use 2D position setpoint to generate a 2D velocity setpoint
// Get various path specific vectors
Vector2f pos_traj(_trajectory[0].getCurrentPosition(), _trajectory[1].getCurrentPosition());
Vector2f crossing_point = is_single_waypoint ? Vector2f(target) : Vector2f(_getCrossingPoint(position, waypoints));
Vector2f pos_traj_to_dest_xy = crossing_point - pos_traj;
Vector2f u_pos_traj_to_dest_xy(pos_traj_to_dest_xy.unit_or_zero());
float xy_speed = _getMaxXYSpeed(waypoints);
if (_isTurning(target)) {
// Lock speed during turn
xy_speed = math::min(_max_speed_previous, xy_speed);
} else {
_max_speed_previous = xy_speed;
}
Vector2f vel_sp_constrained_xy = u_pos_traj_to_dest_xy * xy_speed;
for (int i = 0; i < 2; i++) {
// If available, use the existing velocity as a feedforward, otherwise replace it
if (PX4_ISFINITE(velocity_setpoint(i))) {
velocity_setpoint(i) += vel_sp_constrained_xy(i);
} else {
velocity_setpoint(i) = vel_sp_constrained_xy(i);
}
}
}
else if (z_target_valid) {
// Use Z position setpoint to generate a Z velocity setpoint
const float z_dir = matrix::sign(target(2) - _trajectory[2].getCurrentPosition());
const float vel_sp_z = z_dir * _getMaxZSpeed(waypoints);
// If available, use the existing velocity as a feedforward, otherwise replace it
if (PX4_ISFINITE(velocity_setpoint(2))) {
velocity_setpoint(2) += vel_sp_z;
} else {
velocity_setpoint(2) = vel_sp_z;
}
}
return velocity_setpoint;
}
void PositionSmoothing::_generateTrajectory(
const Vector3f &position,
const Vector3f &velocity_setpoint,
float delta_time,
PositionSmoothingSetpoints &out_setpoints)
{
if (!PX4_ISFINITE(velocity_setpoint(0)) || !PX4_ISFINITE(velocity_setpoint(1))
|| !PX4_ISFINITE(velocity_setpoint(2))) {
return;
}
/* Slow down the trajectory by decreasing the integration time based on the position error.
* This is only performed when the drone is behind the trajectory
*/
Vector2f position_trajectory_xy(_trajectory[0].getCurrentPosition(), _trajectory[1].getCurrentPosition());
Vector2f position_xy(position);
Vector2f vel_traj_xy(_trajectory[0].getCurrentVelocity(), _trajectory[1].getCurrentVelocity());
Vector2f drone_to_trajectory_xy(position_trajectory_xy - position_xy);
float position_error = drone_to_trajectory_xy.length();
float time_stretch = 1.f - math::constrain(position_error / _max_allowed_horizontal_error, 0.f, 1.f);
// Don't stretch time if the drone is ahead of the position setpoint
if (drone_to_trajectory_xy.dot(vel_traj_xy) < 0.f) {
time_stretch = 1.f;
}
for (int i = 0; i < 3; ++i) {
_trajectory[i].updateTraj(delta_time, time_stretch);
out_setpoints.jerk(i) = _trajectory[i].getCurrentJerk();
out_setpoints.acceleration(i) = _trajectory[i].getCurrentAcceleration();
out_setpoints.velocity(i) = _trajectory[i].getCurrentVelocity();
out_setpoints.position(i) = _trajectory[i].getCurrentPosition();
}
for (int i = 0; i < 3; ++i) {
_trajectory[i].updateDurations(velocity_setpoint(i));
}
VelocitySmoothing::timeSynchronization(_trajectory, 3);
}
| 37.284404 | 132 | 0.749918 | [
"vector",
"3d"
] |
00acdb2279638fe5153fc9c186ba4938675c9ad1 | 835 | hpp | C++ | test/list.hpp | marcodlk/cc | b97c635c08aca3346f315fc9e943d7965a067146 | [
"BSD-2-Clause"
] | 1 | 2021-01-20T04:45:59.000Z | 2021-01-20T04:45:59.000Z | test/list.hpp | marcodlk/cc | b97c635c08aca3346f315fc9e943d7965a067146 | [
"BSD-2-Clause"
] | null | null | null | test/list.hpp | marcodlk/cc | b97c635c08aca3346f315fc9e943d7965a067146 | [
"BSD-2-Clause"
] | 1 | 2021-01-20T04:50:52.000Z | 2021-01-20T04:50:52.000Z | /*
* cc - C Containers library
*
* cc is, per 17 USC § 101, a work of the U.S. Government and is not subject to
* copyright protection in the United States.
*
* DISTRIBUTION STATEMENT A. Approved for public release; distribution is
* unlimited. Granted clearance per 88ABW-2020-3430.
*/
#ifndef CC_TEST_LIST_HPP
#define CC_TEST_LIST_HPP
#include <functional>
#include <vector>
#include "cc_list.h"
template <class T>
void
check_list(cc_list_t actual, const std::vector<T>& expected)
{
const T* x;
auto eq = std::equal_to<T>();
REQUIRE(cc_list_size(actual) == expected.size());
const struct cc_list_node* node = actual->front;
for (size_t n = 0; n < expected.size(); ++n)
{
x = static_cast<const T*>(node->data);
CHECK(eq(*x, expected[n]));
node = node->next;
}
}
#endif // CC_TEST_LIST_HPP
| 23.857143 | 80 | 0.679042 | [
"vector"
] |
00aefa1db900d66a9b841b1c0c7ec26122f86a1a | 2,178 | cpp | C++ | 201922/dec201922_1.cpp | jibsen/aocpp2019 | 99cda72f6477bde0731c5fc958eebbc2219d6fb3 | [
"MIT"
] | 2 | 2020-04-26T17:31:31.000Z | 2020-10-03T00:54:16.000Z | 201922/dec201922_1.cpp | jibsen/aocpp2019 | 99cda72f6477bde0731c5fc958eebbc2219d6fb3 | [
"MIT"
] | null | null | null | 201922/dec201922_1.cpp | jibsen/aocpp2019 | 99cda72f6477bde0731c5fc958eebbc2219d6fb3 | [
"MIT"
] | null | null | null | //
// Advent of Code 2019, day 22, part one
//
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
#include <vector>
enum class Shuffle {
cut, increment, stack
};
std::vector<std::pair<Shuffle, int>> read_instructions(const char *filename)
{
std::ifstream infile(filename);
std::string line;
std::vector<std::pair<Shuffle, int>> instructions;
while (std::getline(infile, line)) {
if (line.size() > 4 && line.substr(0, 3) == "cut") {
instructions.push_back({Shuffle::cut, std::stoi(line.substr(4))});
}
else if (line.size() > 20 && line.substr(5, 4) == "with") {
instructions.push_back({Shuffle::increment, std::stoi(line.substr(20))});
}
else if (line.size() > 9 && line.substr(5, 4) == "into") {
instructions.push_back({Shuffle::stack, 0});
}
else {
std::cout << "unable to parse " << line << '\n';
}
}
return instructions;
}
void cut(std::vector<int> &cards, int n) {
if (n > 0) {
std::rotate(cards.begin(), cards.begin() + n, cards.end());
}
else if (n < 0) {
std::rotate(cards.begin(), cards.end() - std::abs(n), cards.end());
}
}
void deal_with_increment(std::vector<int> &cards, int n) {
std::vector<int> table(cards.size());
int i = 0;
for (auto c : cards) {
table[i] = c;
i = (i + n) % cards.size();
}
cards.swap(table);
}
void deal_into_new_stack(std::vector<int> &cards) {
std::reverse(cards.begin(), cards.end());
}
int main(int argc, char *argv[])
{
if (argc != 2) {
std::cerr << "no program file\n";
exit(1);
}
auto instructions = read_instructions(argv[1]);
std::cout << instructions.size() << '\n';
std::vector<int> cards(10007);
std::iota(cards.begin(), cards.end(), 0);
for (auto [type, arg] : instructions) {
switch (type) {
case Shuffle::cut:
cut(cards, arg);
break;
case Shuffle::increment:
deal_with_increment(cards, arg);
break;
case Shuffle::stack:
deal_into_new_stack(cards);
break;
default:
std::cerr << "unknown shuffle method\n";
exit(1);
}
}
for (int i = 0; i < cards.size(); ++i) {
if (cards[i] == 2019) {
std::cout << i << '\n';
break;
}
}
return 0;
}
| 20.54717 | 76 | 0.608815 | [
"vector"
] |
00b16933b232fc3385e9e3f3f1f3472baeef5f2c | 16,782 | cpp | C++ | enduser/netmeeting/av/codecs/intel/h263/d3bvriq.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/netmeeting/av/codecs/intel/h263/d3bvriq.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/netmeeting/av/codecs/intel/h263/d3bvriq.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /* *************************************************************************
** INTEL Corporation Proprietary Information
**
** This listing is supplied under the terms of a license
** agreement with INTEL Corporation and may not be copied
** nor disclosed except in accordance with the terms of
** that agreement.
**
** Copyright (c) 1995 Intel Corporation.
** All Rights Reserved.
**
** *************************************************************************
*/
//////////////////////////////////////////////////////////////////////////
// $Author: AGUPTA2 $
// $Date: 22 Mar 1996 17:23:16 $
// $Archive: S:\h26x\src\dec\d3bvriq.cpv $
// $Header: S:\h26x\src\dec\d3bvriq.cpv 1.7 22 Mar 1996 17:23:16 AGUPTA2 $
// $Log: S:\h26x\src\dec\d3bvriq.cpv $
//
// Rev 1.7 22 Mar 1996 17:23:16 AGUPTA2
// Minor interface change to accomodate MMX rtns. Now the interface is the
// same for MMX and IA.
//
// Rev 1.6 08 Mar 1996 16:46:10 AGUPTA2
// Added pragma code_seg.
//
//
// Rev 1.5 15 Feb 1996 14:54:08 RMCKENZX
// Gutted and re-wrote routine, optimizing for performance
// for the p5. Added clamping to -2048...+2047 to escape code
// portion.
//
// Rev 1.4 27 Dec 1995 14:36:00 RMCKENZX
// Added copyright notice
//
// Rev 1.3 09 Dec 1995 17:35:20 RMCKENZX
// Re-checked in module to support decoder re-architecture (thru PB frames)
//
// Rev 1.0 27 Nov 1995 14:36:46 CZHU
// Initial revision.
//
// Rev 1.28 03 Nov 1995 16:28:50 CZHU
// Cleaning up and added more comments
//
// Rev 1.27 31 Oct 1995 10:27:20 CZHU
// Added error checking for total run value.
//
// Rev 1.26 19 Sep 1995 10:45:12 CZHU
//
// Improved pairing and cleaned up
//
// Rev 1.25 18 Sep 1995 10:20:28 CZHU
// Fixed bugs in handling escape codes for INTER blocks w.r.t. run.
//
// Rev 1.24 15 Sep 1995 09:35:30 CZHU
// fixed bugs in run cumulation for inter
//
// Rev 1.23 14 Sep 1995 10:13:32 CZHU
//
// Initialize cumulated run for the INTER blocks.
//
// Rev 1.22 12 Sep 1995 17:36:06 AKASAI
//
// Fixed bug in addressing to Intermediate when changed from writing
// BYTES to DWORDS. Inter Butterfly only had the problem.
//
// Rev 1.21 12 Sep 1995 13:37:58 AKASAI
// Added Butterfly Inter code. Also added optimizations to pre-fetch
// accumulators and "output" cache lines.
//
// Rev 1.20 11 Sep 1995 16:41:32 CZHU
// Adjust target block address: write to Target if INTRA, write to tempory sto
//
// Rev 1.19 11 Sep 1995 14:30:32 CZHU
// Seperate Butterfly for inter and intra, put place holder for inter blocks
//
// Rev 1.18 08 Sep 1995 11:49:00 CZHU
// Added support for P frames, fixed bugs related to INTRADC's presence.
//
// Rev 1.17 28 Aug 1995 14:51:22 CZHU
// Improve pairing and clean up
//
// Rev 1.16 24 Aug 1995 15:36:24 CZHU
//
// Fixed bugs handling the escape code followed by 22bits fixed length code
//
// Rev 1.15 23 Aug 1995 14:53:32 AKASAI
// Changed butterfly writes to increment by bytes and take a PITCH.
//
// Rev 1.14 23 Aug 1995 11:58:46 CZHU
// Added signed extended inverse quant before calling idct. and others
//
// Rev 1.13 22 Aug 1995 17:38:28 CZHU
// Calls the idct accumulation for each symbol and butterfly at the end.
//
// Rev 1.12 21 Aug 1995 14:39:58 CZHU
//
// Added IDCT initialization code and stubs for accumulation and butterfly.
// Also added register saving and restoration before and after accumulation
//
// Rev 1.11 18 Aug 1995 17:03:32 CZHU
// Added comments and clean up for integration with IDCT
//
// Rev 1.10 18 Aug 1995 15:01:52 CZHU
// Fixed bugs in handling escape codes using byte oriented reading approach
//
// Rev 1.9 16 Aug 1995 14:24:22 CZHU
// Bug fixes for the integration with bitstream parsing. Also changed from DWO
// reading to byte oriented reading.
//
// Rev 1.8 15 Aug 1995 15:07:42 CZHU
// Fixed the stack so that the parameters have been passed in correctly.
//
// Rev 1.7 14 Aug 1995 16:39:02 DBRUCKS
// changed pPBlock to pCurBlock
//
// Rev 1.6 11 Aug 1995 16:08:12 CZHU
// removed local varables in C
//
// Rev 1.5 11 Aug 1995 15:51:26 CZHU
//
// Readjust local varables on the stack. Clear ECX upfront.
//
// Rev 1.4 11 Aug 1995 15:14:32 DBRUCKS
// variable name changes
//
// Rev 1.3 11 Aug 1995 13:37:26 CZHU
//
// Adjust to the joint optimation of IDCT, IQ, RLE, and ZZ.
// Also added place holders for IDCT.
//
// Rev 1.2 11 Aug 1995 10:30:26 CZHU
// Changed the functions parameters, and added codes to short-curcuit IDCT bef
//
// Rev 1.1 03 Aug 1995 14:39:04 CZHU
//
// further optimization.
//
// Rev 1.0 02 Aug 1995 15:20:02 CZHU
// Initial revision.
//
// Rev 1.1 02 Aug 1995 10:21:12 CZHU
// Added asm codes for VLD of TCOEFF, inverse quantization, run-length decode.
//
//--------------------------------------------------------------------------
//
// d3xbvriq.cpp
//
// Description:
// This routine performs run length decoding and inverse quantization
// of transform coefficients for one block.
// MMx version.
//
// Routines:
// VLD_RLD_IQ_Block
//
// Inputs (dwords pushed onto stack by caller):
// lpBlockAction pointer to Block action stream for current blk.
//
// lpSrc The input bitstream.
//
// uBitsInOut Number of bits already read.
//
// pIQ_INDEX Pointer to coefficients and indices.
//
// pN Pointer to number of coefficients read.
//
// Returns:
// 0 on bit stream error, otherwise total number of bits read
// (including number read prior to call).
//
// Note:
// The structure of gTAB_TCOEFF_MAJOR is as follows:
// bits name: description
// ---- ----- -----------
// 25-18 bits: number of bitstream bits used
// 17 last: flag for last coefficient
// 16-9 run: number of preceeding 0 coefficients plus 1
// 8-2 level: absolute value of coefficient
// 1 sign: sign of coefficient
// 0 hit: 1 = major table miss, 0 = major table hit
//
// The structure of gTAB_TCOEFF_MINOR is the same, right shifted by 1 bit.
// A gTAB_TCOEFF_MAJOR value of 00000001h indicates the escape code.
//
//--------------------------------------------------------------------------
#include "precomp.h"
// local variable definitions
#define L_Quantizer esp+20 // quantizer P_BlockAction
#define L_Quantizer64 esp+24 // 64*quantizer P_src
#define L_Bits esp+28 // bit offset P_bits
#define L_CumRun esp+36 // cumulative run P_dst
// stack use
// ebp esp+0
// esi esp+4
// edi esp+8
// ebx esp+12
// return address esp+16
// input parameters
#define P_BlockAction esp+20 // L_Quantizer
#define P_src esp+24 // L_Quantizer64
#define P_bits esp+28 // L_Bits
#define P_num esp+32 //
#define P_dst esp+36 // L_CumRun
#pragma code_seg("IACODE1")
extern "C" __declspec(naked)
U32 VLD_RLD_IQ_Block(T_BlkAction *lpBlockAction,
U8 *lpSrc,
U32 uBitsread,
U32 *pN,
U32 *pIQ_INDEX)
{
__asm {
// save registers
push ebp
push esi
push edi
push ebx
//
// initialize
// make sure we read in the P_src and P_dst pointers before we
// overwrite them with L_Quantizer64 and L_CumRun.
//
// Output Registers:
// dl = block type ([P_BlockAction])
// esi = bitstream source pointer (P_src)
// edi = coefficient destination pointer (P_dst)
// ebp = coefficent counter (init to 0)
//
// Locals initialized on Stack: (these overwrite indicated input parameters)
// local var clobbers initial value
// ---------------------------------------------------
// L_Quantizer P_BlockAction input quantizer
// L_Quantizer64 P_src 64 * input quantizer
// L_CumRun P_dst -1
//
xor ebp, ebp // init coefficient counter to 0
xor eax, eax // zero eax for quantizer & coef. counter
mov ecx, [P_BlockAction] // ecx = block action pointer
mov ebx, -1 // beginning cumulative run value
mov esi, [P_src] // esi = bitstream source pointer
mov edi, [P_dst] // edi = coefficient pointer
mov al, [ecx+3] // al = Quantizer
mov [L_CumRun], ebx // init cumulative run to -1
mov [L_Quantizer], eax // save original quantizer
mov dl, [ecx] // block type in dl
shl eax, 6 // 64 * Quantizer
mov ecx, [L_Bits] // ecx = L_Bits
mov ebx, ecx // ebx = L_Bits
mov [L_Quantizer64], eax // save 64*Quantizer for this block
shr ebx, 3 // offset for input
and ecx, 7 // shift value
cmp dl, 1 // check the block type for INTRA
ja get_next_coefficient // if type 2 or larger, no INTRADC
//
// Decode INTRADC
//
// uses dword load & bitswap to achieve big endian ordering.
// prior codes prepares ebx, cl, and dl as follows:
// ebx = L_Bits>>3
// cl = L_Bits&7
// dl = BlockType (0=INTRA_DC, 1=INTRA, 2=INTER, etc.)
//
mov eax, [esi+ebx] // *** PROBABLE MALALIGNMENT ***
inc ebp // one coefficient decoded
bswap eax // big endian order
// *** NOT PAIRABLE ***
shl eax, cl // left justify bitstream buffer
// *** NOT PAIRABLE ***
// *** 4 CYCLES ***
shr eax, 21 // top 11 bits to the bottom
mov ecx, [L_Bits] // ecx = L_Bits
and eax, 07f8h // mask last 3 bits
add ecx, 8 // bits used += 8 for INTRADC
cmp eax, 07f8h // check for 11111111 codeword
jne skipa
mov eax, 0400h // 11111111 decodes to 400h = 1024
skipa:
mov [L_Bits], ecx // update bits used
xor ebx, ebx
mov [L_CumRun], ebx // save total run (starts with zero)
mov [edi], eax // save decoded DC coefficient
mov [edi+4], ebx // save 0 index
mov ebx, ecx // ebx = L_Bits
shr ebx, 3 // offset for input
add edi, 8 // update coefficient pointer
// check for last
test dl, dl // check for INTRA-DC (block type=0)
jz finish // if only the INTRADC present
//
// Get Next Coefficient
//
// prior codes prepares ebx and ecx as follows:
// ebx = L_Bits>>3
// ecx = L_Bits
//
get_next_coefficient:
// use dword load & bitswap to achieve big endian ordering
mov eax, [esi+ebx] // *** PROBABLE MALALIGNMENT ***
and ecx, 7 // shift value
bswap eax // big endian order
// *** NOT PAIRABLE ***
shl eax, cl // left justify buffer
// *** NOT PAIRABLE ***
// *** 4 CYCLES ***
// do table lookups
mov ebx, eax // ebx for major table
mov ecx, eax // ecx for minor table
shr ebx, 24 // major table lookup
shr ecx, 17 // minor table lookup in bits with garbage
mov ebx, [gTAB_TCOEFF_MAJOR+4*ebx] // get the major table value
// ** AGI **
shr ebx, 1 // test major hit ?
jnc skipb // if hit major
and ecx, 0ffch // mask off garbage for minor table
test ebx, ebx // escape code value was 0x00000001
jz escape_code // handle escape by major table.
mov ebx, [gTAB_TCOEFF_MINOR+ecx] // use minor table
//
// input is ebx = event. See function header for the meaning of its fields
// now we decode the event, extracting the run, value, last.
// The table value moves to ecx and is shifted downward as portions
// are extracted to ebx.
//
skipb:
mov ecx, ebx // ecx = table value
and ebx, 0ffh // ebx = 2*abs(level) + sign
shr ecx, 8 // run to bottom
mov edx, [L_Quantizer64] // edx = 64*quant
// ** PREFIX DELAY **
// ** AGI **
mov ax, [gTAB_INVERSE_Q+edx+2*ebx] // ax = dequantized value (I16)
mov ebx, ecx // ebx = table value
shl eax, 16 // shift value until sign bit is on top
and ebx, 0ffh // ebx = run + 1
sar eax, 16 // arithmetic shift extends value's sign
mov edx, [L_CumRun] // edx = (old) cumulative run
add edx, ebx // cumulative run += run + 1
mov [edi], eax // save coefficient's signed value
cmp edx, 03fh // check run for bitstream error
jg error
mov [L_CumRun], edx // update the cumulative run
inc ebp // increment number of coefficients read
// ** AGI **
mov edx, [gTAB_ZZ_RUN+4*edx] // edx = index of the current coefficient
mov ebx, ecx // ebx: bit 8 = last flag
mov [edi+4], edx // save coefficient's index
add edi, 8 // increment coefficient pointer
shr ecx, 9 // ecx = bits decoded
mov edx, [L_Bits] // edx = L_Bits
add ecx, edx // L_Bits += bits decoded
mov edx, ebx // ebx: bit 8 = last flag
mov [L_Bits], ecx // update L_Bits
mov ebx, ecx // ebx = L_Bits
shr ebx, 3 // offset for bitstream load
test edx, 100h // check for last
jz get_next_coefficient
finish:
mov ecx, [P_num] // pointer to number of coeffients read
mov eax, [L_Bits] // return total bits used
pop ebx
pop edi
mov [ecx], ebp // store number of coefficients read
pop esi
pop ebp
ret
//
// process escape code separately
//
// we have the following 4 cases to compute the reconstructed value
// depending on the sign of L=level and the parity of Q=quantizer:
//
// L pos L neg
// Q even 2QL+(Q-1) 2QL-(Q-1)
// Q odd 2QL+(Q) 2QL-(Q)
//
// The Q or Q-1 term is formed by adding Q to its parity bit
// and then subtracting 1.
// The + or - on this term is gotten by anding the term with a
// mask (=0 or =-1) formed from the sign bit of Q*L,
// doubling the result, then subtracting it from the term.
// This will negate the term when L is negative and leave
// it unchanged when L is positive.
//
// Register usages:
// eax starts with bitstream, later L, finally result
// ebx starts with Q, later is the Q or Q-1 term
// ecx startw with mask, later 2*term
// edx bitstream
//
escape_code:
mov edx, eax // edx = bitstream buffer
shl eax, 14 // signed 8-bit level to top
sar eax, 24 // eax = L (signed level)
mov ebx, [L_Quantizer]
test eax, 7fh // test for invalid codes
jz error
imul eax, ebx // eax = Q*L
// *** NOT PAIRABLE ***
// *** 10 cycles ***
dec ebx // term = Q-1
mov ecx, eax // mask = QL
or ebx, 1 // term = Q-1 if Q even, else = Q
sar ecx, 31 // mask = -1 if L neg, else = 0
xor ebx, ecx // term = ~Q[-1] if L neg, else = Q[-1]
add eax, eax // result = 2*Q*L
sub ebx, ecx // term = -(Q[-1]) if L neg, else = Q[-1]
mov ecx, edx // bitstream to ecx to get run
add eax, ebx // result = 2QL +- Q[-1]
// now clip to -2048 ... +2047 (12 bits: 0xfffff800 <= res <= 0x000007ff)
cmp eax, -2048
jge skip1
mov eax, -2048
jmp skip2
skip1:
cmp eax, +2047
jle skip2
mov eax, 2047
skip2:
// update run and compute index
shr ecx, 18 // run to bottom
mov ebx, [L_CumRun] // ebx = old total run
and ecx, 3fh // mask off bottom 6 bits for run
inc ebx // old run ++
add ebx, ecx // ebx = new cumulative run
mov [edi], eax // save coefficient's signed value
cmp ebx, 03fh // check run for bitstream error
jg error
mov [L_CumRun], ebx // update the cumulative run
mov ecx, [L_Bits] // ebx = number of bits used
mov ebx, [gTAB_ZZ_RUN+4*ebx] // ebx = index of the current coefficient
add ecx, 22 // escape code uses 22 bits
mov [edi+4], ebx // save coefficient's index
add edi, 8 // increment coefficient pointer
mov [L_Bits], ecx // update number of bits used
mov ebx, ecx // ebx = L_Bits
shr ebx, 3 // offset for bitstream load
inc ebp // increment number of coefficients read
test edx, 01000000h // check last bit
jz get_next_coefficient
jmp finish
error:
pop ebx
pop edi
pop esi
pop ebp
xor eax, eax // zero bits used indicates ERROR
ret
}
}
#pragma code_seg()
| 30.568306 | 84 | 0.578834 | [
"transform"
] |
00b6b48a4ab8d8bf1036c3cce538e5e77cbcb8ef | 3,075 | cc | C++ | archives/codelibraries/UofL-codeLibrary/intersect_circle_circle.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | 2 | 2019-09-07T17:00:26.000Z | 2020-08-05T02:08:35.000Z | archives/codelibraries/UofL-codeLibrary/intersect_circle_circle.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | archives/codelibraries/UofL-codeLibrary/intersect_circle_circle.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | // Determines the point(s) of intersection if a circle and a circle
//
// Author: Darcy Best
// Date : October 1, 2010
// Source: http://local.wasp.uwa.edu.au/~pbourke/geometry/2circle/
//
// Note: A circle of radius 0 must be considered independently.
// See comments in the implementation.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
using namespace std;
#define SQR(X) ((X) * (X))
// How close to call equal
const double EPS = 1e-4;
bool dEqual(double x,double y){
return fabs(x-y) < EPS;
}
struct Point{
double x,y;
bool operator<(const Point& a) const{
if(dEqual(x,a.x))
return y < a.y;
return x < a.x;
}
};
// Prints out the ordered pair. This also accounts for the negative 0.
void print(const Point& a){
cout << "(";
if(fabs(a.x) < 1e-4)
cout << "0.000";
else
cout << a.x;
cout << ",";
if(fabs(a.y) < 1e-4)
cout << "0.000";
else
cout << a.y;
cout << ")";
}
struct Circle{
double r,x,y;
};
// Input:
// Two circles to intersect
//
// Output:
// Number of points of intersection points
// If 1 (or 2), then ans1 (and ans2) contain those points.
// If 3, then there are infinitely many. (They're the same circle)
int intersect_circle_circle(Circle c1,Circle c2,Point& ans1,Point& ans2){
// If we have two singular points
if(fabs(c1.r) < EPS && fabs(c2.r) < EPS){
if(dEqual(c1.x,c2.x) && dEqual(c1.y,c2.y)){
ans1.x = c1.x;
ans1.y = c1.y;
// Here, you need to know what the intersection of two exact points is:
// "return 1;" - If the points intersect at only 1 point
// "return 3;" - If the circles are the same
// Note that both are true -- It all depends on the problem
return 1;
} else {
return 0;
}
}
double d = hypot(c1.x-c2.x,c1.y-c2.y);
// Check if the circles are exactly the same.
if(dEqual(c1.x,c2.x) && dEqual(c1.y,c2.y) && dEqual(c1.r,c2.r))
return 3;
// The circles are disjoint
if(d > c1.r + c2.r + EPS)
return 0;
// One circle is contained inside the other -- No intersection
if(d < abs(c1.r-c2.r) - EPS)
return 0;
double a = (SQR(c1.r) - SQR(c2.r) + SQR(d)) / (2*d);
double h = sqrt(abs(SQR(c1.r) - SQR(a)));
Point P;
P.x = c1.x + a / d * (c2.x - c1.x);
P.y = c1.y + a / d * (c2.y - c1.y);
ans1.x = P.x + h / d * (c2.y - c1.y);
ans1.y = P.y - h / d * (c2.x - c1.x);
if(fabs(h) < EPS)
return 1;
ans2.x = P.x - h / d * (c2.y - c1.y);
ans2.y = P.y + h / d * (c2.x - c1.x);
return 2;
}
int main(){
cout << fixed << setprecision(3);
Circle C1,C2;
Point a1,a2;
while(cin >> C1.x >> C1.y >> C1.r >> C2.x >> C2.y >> C2.r){
int num = intersect_circle_circle(C1,C2,a1,a2);
switch(num){
case 0:
cout << "NO INTERSECTION" << endl;
break;
case 1:
print(a1); cout << endl;
break;
case 2:
if(a2 < a1)
swap(a1,a2);
print(a1);print(a2);cout << endl;
break;
case 3:
cout << "THE CIRCLES ARE THE SAME" << endl;
break;
}
}
return 0;
}
| 22.610294 | 77 | 0.567154 | [
"geometry"
] |
00bb6413093313679488267f10a358008d1cc15b | 854 | cpp | C++ | utils/csrc/line_nms/line_nms.cpp | voldemortX/DeeplabV3_PyTorch1.3_Codebase | d22d23e74800fafb58eeb61d6649008745c1a287 | [
"BSD-3-Clause"
] | 1 | 2020-09-17T06:21:39.000Z | 2020-09-17T06:21:39.000Z | utils/csrc/line_nms/line_nms.cpp | voldemortX/pytorch-segmentation | 9c62c0a721d11c8ea6bf312ecf1c7b238a54dcda | [
"BSD-3-Clause"
] | null | null | null | utils/csrc/line_nms/line_nms.cpp | voldemortX/pytorch-segmentation | 9c62c0a721d11c8ea6bf312ecf1c7b238a54dcda | [
"BSD-3-Clause"
] | null | null | null | #include <torch/extension.h>
#include <torch/types.h>
#include <iostream>
std::vector<at::Tensor> nms_cuda_forward(
at::Tensor boxes,
at::Tensor idx,
float nms_overlap_thresh,
unsigned long top_k);
#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
std::vector<at::Tensor> nms_forward(
at::Tensor boxes,
at::Tensor scores,
float thresh,
unsigned long top_k) {
auto idx = std::get<1>(scores.sort(0,true));
CHECK_INPUT(boxes);
CHECK_INPUT(idx);
return nms_cuda_forward(boxes, idx, thresh, top_k);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &nms_forward, "NMS forward");
}
| 25.878788 | 83 | 0.667447 | [
"vector"
] |
00bc04ad338920f29f22f612a90959ca800ced47 | 2,306 | hpp | C++ | autofocus/Controller.hpp | asmirnou/libcamera-apps | 5a3c2ceb3378ef6a1a17c121243f5654d57c8dcb | [
"BSD-2-Clause"
] | null | null | null | autofocus/Controller.hpp | asmirnou/libcamera-apps | 5a3c2ceb3378ef6a1a17c121243f5654d57c8dcb | [
"BSD-2-Clause"
] | null | null | null | autofocus/Controller.hpp | asmirnou/libcamera-apps | 5a3c2ceb3378ef6a1a17c121243f5654d57c8dcb | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>
#include <functional>
class DRV8825;
class INA219;
class AS5600;
class Canon;
struct AutofocusConfig
{
std::string lens_port;
std::string input_dev;
uint8_t gpio_chip;
uint8_t motor;
uint8_t i2c;
uint8_t ina219_addr;
uint8_t as5600_addr;
short steps;
short micro_step;
float rpm;
short accel;
short decel;
long track_deg_len;
long stop_deg_dif;
double grid_size;
double tolerance;
double refocus_th_1;
double refocus_th_2;
double refocus_th_3;
double refocus_th_4;
float max_voltage;
float min_voltage;
float alert_th;
bool verbose;
};
class Controller
{
public:
explicit Controller(std::atomic<float> &focus, std::atomic<float> &blur_stddev, unsigned int aperture, unsigned int focal_length);
void Configure(AutofocusConfig config) { config_ = std::move(config); };
void Initialize();
void Teardown();
private:
std::atomic<float> &focus_;
std::atomic<float> &blur_stddev_;
AutofocusConfig config_ {};
DRV8825 *motor = nullptr;
INA219 *sensor = nullptr;
AS5600 *encoder = nullptr;
Canon *lens = nullptr;
bool stop_thread = false;
std::mutex stop_mutex;
std::condition_variable stop_cv;
std::thread *ctrl_thread = nullptr;
std::thread *zoom_thread = nullptr;
std::thread *angle_thread = nullptr;
std::thread *pwm_thread = nullptr;
std::thread *input_thread = nullptr;
unsigned int aperture_init;
unsigned int focal_len_init;
unsigned int focus_len_min = 0;
unsigned int focus_len_max = 0;
long max_steps = 0;
long max_steps_diff = 0;
long current_steps = 0;
std::atomic<float> current_angle;
std::atomic<int8_t> zoom_direction;
std::atomic<unsigned int> angle_poll_ms = 0;
void AutoFocus();
bool AutoFocusLocal();
bool AutoFocusGlobal();
bool WaitFocusChange();
void Zoom(unsigned int current_focal_length);
void ZoomTo(long steps_to_move, const std::function<bool()> &brake);
void MeasureTrackLength();
void AngleMonitor();
void PowerMonitor();
void InputMonitor();
float getCurrentFocus() { return focus_; };
float getBlurStdDev() { return blur_stddev_; };
template <typename Rep, typename Period>
bool wait(std::chrono::duration<Rep, Period> delay);
bool limitSwitch(float startAngle);
};
| 22.38835 | 131 | 0.751084 | [
"vector"
] |
00bec44de5d4e4ddf91d85a1736b5bde7d7b7871 | 21,336 | cpp | C++ | Project/Source/Panels/PanelInspector.cpp | TBD-org/TBD-Engine | 8b45d5a2a92e26bd0ec034047b8188e871fab0f9 | [
"MIT"
] | 7 | 2021-04-26T21:32:12.000Z | 2022-02-14T13:48:53.000Z | Project/Source/Panels/PanelInspector.cpp | TBD-org/RealBugEngine | 0131fde0abc2d86137500acd6f63ed8f0fc2835f | [
"MIT"
] | 66 | 2021-04-24T10:08:07.000Z | 2021-10-05T16:52:56.000Z | Project/Source/Panels/PanelInspector.cpp | TBD-org/TBD-Engine | 8b45d5a2a92e26bd0ec034047b8188e871fab0f9 | [
"MIT"
] | 1 | 2021-07-13T21:26:13.000Z | 2021-07-13T21:26:13.000Z | #include "PanelInspector.h"
#include "GameObject.h"
#include "Application.h"
#include "Components/Component.h"
#include "Components/ComponentType.h"
#include "Components/ComponentLight.h"
#include "Components/ComponentSkybox.h"
#include "Components/ComponentAnimation.h"
#include "Components/ComponentBillboard.h"
#include "Components/ComponentScript.h"
#include "Components/ComponentCamera.h"
#include "Components/ComponentAnimation.h"
#include "Components/ComponentMeshRenderer.h"
#include "Components/ComponentAgent.h"
#include "Components/ComponentObstacle.h"
#include "Components/UI/ComponentTransform2D.h"
#include "Components/UI/ComponentBoundingBox2D.h"
#include "Components/UI/ComponentEventSystem.h"
#include "Components/UI/ComponentSelectable.h"
#include "Components/UI/ComponentCanvasRenderer.h"
#include "Components/UI/ComponentText.h"
#include "Components/UI/ComponentImage.h"
#include "Components/UI/ComponentCanvas.h"
#include "Components/UI/ComponentButton.h"
#include "Components/UI/ComponentSlider.h"
#include "Components/UI/ComponentProgressBar.h"
#include "Components/Physics/ComponentSphereCollider.h"
#include "Components/Physics/ComponentBoxCollider.h"
#include "Modules/ModuleScene.h"
#include "Modules/ModuleEditor.h"
#include "Modules/ModuleRender.h"
#include "Modules/ModuleUserInterface.h"
#include "Math/float3.h"
#include "Math/float3x3.h"
#include "Math/float4x4.h"
#include "GL/glew.h"
#include "imgui.h"
#include "IconsFontAwesome5.h"
#include "IconsForkAwesome.h"
#include "Utils/Leaks.h"
PanelInspector::PanelInspector()
: Panel("Inspector", true) {}
void PanelInspector::Update() {
ImGui::SetNextWindowDockID(App->editor->dockRightId, ImGuiCond_FirstUseEver);
std::string windowName = std::string(ICON_FA_CUBE " ") + name;
std::string optionsSymbol = std::string(ICON_FK_COG);
if (ImGui::Begin(windowName.c_str(), &enabled)) {
GameObject* selected = App->editor->selectedGameObject;
if (selected != nullptr) {
ImGui::TextUnformatted("Id:");
ImGui::SameLine();
ImGui::TextColored(App->editor->textColor, "%llu", selected->GetID());
bool active = selected->IsActiveInternal();
if (ImGui::Checkbox("##game_object", &active)) {
// TODO: EventSystem would generate an event here
if (active) {
selected->Enable();
} else {
selected->Disable();
}
}
ImGui::SameLine();
char name[100];
sprintf_s(name, 100, "%s", selected->name.c_str());
if (ImGui::InputText("##game_object_name", name, 100)) {
selected->name = name;
}
bool isStatic = selected->IsStatic();
if (ImGui::Checkbox("Static##game_object_static", &isStatic)) {
selected->SetStatic(isStatic);
}
if (ImGui::Button("Mask")) {
ImGui::OpenPopup("Mask");
}
if (ImGui::BeginPopup("Mask")) {
for (int i = 0; i < ARRAY_LENGTH(selected->GetMask().maskNames); ++i) {
bool maskActive = selected->GetMask().maskValues[i];
if (ImGui::Checkbox(selected->GetMask().maskNames[i], &maskActive)) {
selected->GetMask().maskValues[i] = maskActive;
if (selected->GetMask().maskValues[i]) {
selected->AddMask(GetMaskTypeFromName(selected->GetMask().maskNames[i]));
} else {
selected->DeleteMask(GetMaskTypeFromName(selected->GetMask().maskNames[i]));
}
}
}
ImGui::Separator();
ImGui::EndPopup();
}
ImGui::Separator();
// Don't show Scene PanelInpector information
if (selected->GetParent() == nullptr) {
ImGui::End();
return;
}
// Show Component info
std::string cName = "";
for (Component* component : selected->GetComponents()) {
switch (component->GetType()) {
case ComponentType::TRANSFORM:
cName = "Transformation";
break;
case ComponentType::MESH_RENDERER:
cName = "Mesh Renderer";
break;
case ComponentType::CAMERA:
cName = "Camera";
break;
case ComponentType::LIGHT:
cName = "Light";
break;
case ComponentType::BOUNDING_BOX:
cName = "Bounding Box";
break;
case ComponentType::TRANSFORM2D:
cName = "Rect Transform";
break;
case ComponentType::BOUNDING_BOX_2D:
cName = "Bounding Box 2D";
break;
case ComponentType::EVENT_SYSTEM:
cName = "Event System";
break;
case ComponentType::CANVAS:
cName = "Canvas";
break;
case ComponentType::CANVASRENDERER:
cName = "Canvas Renderer";
break;
case ComponentType::BUTTON:
cName = "Button";
break;
case ComponentType::TOGGLE:
cName = "Toggle";
break;
case ComponentType::TEXT:
cName = "Text";
break;
case ComponentType::IMAGE:
cName = "Image";
break;
case ComponentType::VIDEO:
cName = "Video";
break;
case ComponentType::SELECTABLE:
cName = "Selectable";
break;
case ComponentType::SLIDER:
cName = "Slider";
break;
case ComponentType::SKYBOX:
cName = "Skybox";
break;
case ComponentType::SCRIPT:
cName = "Script";
break;
case ComponentType::ANIMATION:
cName = "Animation";
break;
case ComponentType::PARTICLE:
cName = "Particle";
break;
case ComponentType::TRAIL:
cName = "Trail";
break;
case ComponentType::BILLBOARD:
cName = "Billboard";
break;
case ComponentType::AUDIO_SOURCE:
cName = "Audio Source";
break;
case ComponentType::AUDIO_LISTENER:
cName = "Audio Listener";
break;
case ComponentType::PROGRESS_BAR:
cName = "Progress Bar";
break;
case ComponentType::SPHERE_COLLIDER:
cName = "Sphere Collider";
break;
case ComponentType::BOX_COLLIDER:
cName = "Box Collider";
break;
case ComponentType::CAPSULE_COLLIDER:
cName = "Capsule Collider";
break;
case ComponentType::AGENT:
cName = "Agent";
break;
case ComponentType::OBSTACLE:
cName = "Obstacle";
break;
case ComponentType::FOG:
cName = "Fog";
break;
default:
cName = "";
break;
}
ImGui::PushID(component);
// TODO: Place TransformComponent always th the top of the Inspector
bool headerOpen = ImGui::CollapsingHeader(cName.c_str(), ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_DefaultOpen);
// Options BUTTON (in the same line and at the end of the line)
ImGui::SameLine();
if (ImGui::GetWindowWidth() > 170) ImGui::Indent(ImGui::GetWindowWidth() - 43);
if (ImGui::Button(optionsSymbol.c_str())) ImGui::OpenPopup("Component Options");
// More Component buttons (edit the Indention)...
if (ImGui::GetWindowWidth() > 170) ImGui::Unindent(ImGui::GetWindowWidth() - 43);
// Options POPUP
if (ImGui::BeginPopup("Component Options")) {
if (component->GetType() != ComponentType::TRANSFORM) {
if (ImGui::MenuItem("Remove Component")) {
componentToDelete = component;
}
// TODO: force remove other components that this one requires for functioning
}
// More Options items ...
ImGui::EndPopup();
}
// Show Component info
if (headerOpen) component->OnEditorUpdate();
ImGui::PopID();
}
// Add New Components
ImGui::Spacing();
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
ImGui::Spacing();
if (ImGui::Button("Add New Component", ImVec2(ImGui::GetContentRegionAvail().x, 25))) { ImGui::OpenPopup("AddComponentPopup"); }
if (ImGui::BeginPopup("AddComponentPopup")) {
// Add a Component of type X. If a Component of the same type exists, it wont be created and the modal COMPONENT_EXISTS will show up.
if (ImGui::MenuItem("Mesh Renderer")) {
ComponentMeshRenderer* meshRenderer = selected->CreateComponent<ComponentMeshRenderer>();
if (meshRenderer != nullptr) {
meshRenderer->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Camera")) {
ComponentCamera* camera = selected->CreateComponent<ComponentCamera>();
if (camera != nullptr) {
camera->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Light")) {
ComponentLight* light = selected->CreateComponent<ComponentLight>();
if (light != nullptr) {
light->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Skybox")) {
ComponentSkyBox* skybox = selected->CreateComponent<ComponentSkyBox>();
if (skybox != nullptr) {
skybox->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Fog")) {
ComponentFog* fog = selected->CreateComponent<ComponentFog>();
if (fog != nullptr) {
fog->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Script")) {
ComponentScript* script = selected->CreateComponent<ComponentScript>();
if (script != nullptr) {
script->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Animation")) {
ComponentAnimation* animation = selected->CreateComponent<ComponentAnimation>();
if (animation != nullptr) {
animation->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
// TRANSFORM is always there, cannot add a new one.
AddParticleComponentsOptions(selected);
AddAudioComponentsOptions(selected);
AddUIComponentsOptions(selected);
AddColliderComponentsOptions(selected);
AddNavigationComponentsOptions(selected);
ImGui::EndPopup();
}
}
}
ImGui::End();
}
Component* PanelInspector::GetComponentToDelete() const {
return componentToDelete;
}
void PanelInspector::SetComponentToDelete(Component* comp) {
componentToDelete = comp;
}
void PanelInspector::AddParticleComponentsOptions(GameObject* selected) {
if (ImGui::BeginMenu("Particles")) {
if (ImGui::MenuItem("Particle")) {
ComponentParticleSystem* particle = selected->CreateComponent<ComponentParticleSystem>();
if (particle != nullptr) {
particle->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Billboard")) {
ComponentBillboard* billboard = selected->CreateComponent<ComponentBillboard>();
if (billboard != nullptr) {
billboard->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Trail")) {
ComponentTrail* trail = selected->CreateComponent<ComponentTrail>();
if (trail != nullptr) {
trail->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
ImGui::EndMenu();
}
}
void PanelInspector::AddAudioComponentsOptions(GameObject* selected) {
if (ImGui::BeginMenu("Audio")) {
if (ImGui::MenuItem("Audio Source")) {
ComponentAudioSource* audioSource = selected->CreateComponent<ComponentAudioSource>();
if (audioSource != nullptr) {
audioSource->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Audio Listener")) {
ComponentAudioListener* audioListener = selected->CreateComponent<ComponentAudioListener>();
if (audioListener != nullptr) {
audioListener->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
ImGui::EndMenu();
}
}
void PanelInspector::AddUIComponentsOptions(GameObject* selected) {
if (ImGui::BeginMenu("UI")) {
// ------ CREATING UI HANDLERS -------
ComponentType typeToCreate = ComponentType::UNKNOWN;
if (ImGui::MenuItem("Event System")) {
if (App->scene->scene->eventSystemComponents.Count() == 0) {
typeToCreate = ComponentType::EVENT_SYSTEM;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Canvas")) {
typeToCreate = ComponentType::CANVAS;
}
// ------ CREATING UI ELEMENTS -------
bool newUIComponentCreated = false; // If a UI component is created, we will create a Transform2D and a CanvasRenderer components for it
bool newUISelectableCreated = false; // In addition, if it is a selectable element, a ComponentBoundingBox2D will also be created
if (ImGui::MenuItem("Image")) {
ComponentImage* component = selected->GetComponent<ComponentImage>();
if (component == nullptr) {
newUIComponentCreated = true;
typeToCreate = ComponentType::IMAGE;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Video")) {
ComponentVideo* component = selected->GetComponent<ComponentVideo>();
if (component == nullptr) {
newUIComponentCreated = true;
typeToCreate = ComponentType::VIDEO;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Text")) {
ComponentText* component = selected->GetComponent<ComponentText>();
if (component == nullptr) {
newUIComponentCreated = true;
typeToCreate = ComponentType::TEXT;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
// ----- Selectables
if (ImGui::MenuItem("Button")) {
ComponentButton* component = selected->GetComponent<ComponentButton>();
if (component == nullptr) {
typeToCreate = ComponentType::BUTTON;
newUIComponentCreated = true;
newUISelectableCreated = true;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Toggle")) {
ComponentToggle* component = selected->GetComponent<ComponentToggle>();
if (component == nullptr) {
typeToCreate = ComponentType::TOGGLE;
newUIComponentCreated = true;
newUISelectableCreated = true;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("ProgressBar")) {
ComponentProgressBar* component = selected->GetComponent<ComponentProgressBar>();
if (component == nullptr) {
typeToCreate = ComponentType::PROGRESS_BAR;
newUIComponentCreated = true;
newUISelectableCreated = true;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Slider")) {
ComponentSlider* component = selected->GetComponent<ComponentSlider>();
if (component == nullptr) {
typeToCreate = ComponentType::SLIDER;
newUIComponentCreated = true;
newUISelectableCreated = true;
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (newUIComponentCreated) {
// Create new Transform2D
ComponentTransform2D* transform2d = selected->CreateComponent<ComponentTransform2D>();
if (transform2d != nullptr) transform2d->Init();
// Create new Canvas Renderer
ComponentCanvasRenderer* canvasRender = selected->CreateComponent<ComponentCanvasRenderer>();
if (canvasRender != nullptr) canvasRender->Init();
if (newUISelectableCreated) {
ComponentBoundingBox2D* boundingBox2d = selected->CreateComponent<ComponentBoundingBox2D>();
ComponentSelectable* selectable = selected->CreateComponent<ComponentSelectable>();
if (boundingBox2d != nullptr) boundingBox2d->Init();
if (selectable != nullptr) {
selectable->Init();
selectable->SetSelectableType(typeToCreate);
}
}
}
switch (typeToCreate) {
case ComponentType::EVENT_SYSTEM: {
ComponentEventSystem* component = selected->CreateComponent<ComponentEventSystem>();
if (component != nullptr) {
component->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
break;
}
case ComponentType::CANVAS: {
ComponentTransform2D* transform = selected->GetComponent<ComponentTransform2D>();
if (transform == nullptr) {
transform = selected->CreateComponent<ComponentTransform2D>();
transform->Init();
}
ComponentCanvas* component = selected->CreateComponent<ComponentCanvas>();
if (component != nullptr) {
component->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
break;
}
case ComponentType::IMAGE: {
ComponentImage* component = selected->CreateComponent<ComponentImage>();
component->Init();
break;
}
case ComponentType::VIDEO: {
ComponentVideo* component = selected->CreateComponent<ComponentVideo>();
component->Init();
break;
}
case ComponentType::TEXT: {
ComponentText* component = selected->CreateComponent<ComponentText>();
component->Init();
break;
}
case ComponentType::BUTTON: {
ComponentButton* component = selected->CreateComponent<ComponentButton>();
component->Init();
if (!selected->GetComponent<ComponentImage>()) {
ComponentImage* image = selected->CreateComponent<ComponentImage>();
image->Init();
}
break;
}
case ComponentType::TOGGLE: {
ComponentToggle* component = selected->CreateComponent<ComponentToggle>();
component->Init();
if (!selected->GetComponent<ComponentImage>()) {
ComponentImage* image = selected->CreateComponent<ComponentImage>();
image->Init();
}
break;
}
case ComponentType::PROGRESS_BAR: {
ComponentProgressBar* component = selected->CreateComponent<ComponentProgressBar>();
component->Init();
GameObject* background = App->scene->scene->CreateGameObject(selected, GenerateUID(), "Background");
ComponentTransform2D* transform2D = background->CreateComponent<ComponentTransform2D>();
ComponentCanvasRenderer* canvasRenderer = background->CreateComponent<ComponentCanvasRenderer>();
ComponentImage* image = background->CreateComponent<ComponentImage>();
background->Init();
transform2D->SetSize(float2(700, 80));
GameObject* fill = App->scene->scene->CreateGameObject(selected, GenerateUID(), "Fill");
ComponentTransform2D* transform2DFill = fill->CreateComponent<ComponentTransform2D>();
ComponentCanvasRenderer* canvasRendererFill = fill->CreateComponent<ComponentCanvasRenderer>();
ComponentImage* imageFill = fill->CreateComponent<ComponentImage>();
fill->Init();
imageFill->SetColor(float4(1.f, 0, 0, 1.f));
break;
}
case ComponentType::SLIDER: {
ComponentSlider* component = selected->CreateComponent<ComponentSlider>();
component->Init();
if (!selected->GetComponent<ComponentImage>()) {
ComponentImage* image = selected->CreateComponent<ComponentImage>();
image->Init();
}
GameObject* background = App->scene->scene->CreateGameObject(selected, GenerateUID(), "Background");
ComponentTransform2D* transform2D = background->CreateComponent<ComponentTransform2D>();
ComponentCanvasRenderer* canvasRenderer = background->CreateComponent<ComponentCanvasRenderer>();
ComponentImage* image = background->CreateComponent<ComponentImage>();
background->Init();
transform2D->SetSize(float2(700, 80));
GameObject* fill = App->scene->scene->CreateGameObject(selected, GenerateUID(), "Fill");
ComponentTransform2D* transform2DFill = fill->CreateComponent<ComponentTransform2D>();
ComponentCanvasRenderer* canvasRendererFill = fill->CreateComponent<ComponentCanvasRenderer>();
ComponentImage* imageFill = fill->CreateComponent<ComponentImage>();
fill->Init();
GameObject* handle = App->scene->scene->CreateGameObject(selected, GenerateUID(), "Handle");
ComponentTransform2D* transform2DHandle = fill->CreateComponent<ComponentTransform2D>();
ComponentCanvasRenderer* canvasRendererHandle = fill->CreateComponent<ComponentCanvasRenderer>();
ComponentImage* imageHandle = fill->CreateComponent<ComponentImage>();
fill->Init();
break;
}
} // ens switch
ImGui::EndMenu();
}
}
void PanelInspector::AddColliderComponentsOptions(GameObject* selected) {
if (ImGui::BeginMenu("Collider")) {
if (ImGui::MenuItem("Sphere Collider")) {
ComponentSphereCollider* sphereCollider = selected->CreateComponent<ComponentSphereCollider>();
if (sphereCollider != nullptr) {
sphereCollider->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS; // TODO: Control other colliders exists.
}
}
if (ImGui::MenuItem("Box Collider")) {
ComponentBoxCollider* boxCollider = selected->CreateComponent<ComponentBoxCollider>();
if (boxCollider != nullptr) {
boxCollider->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS; // TODO: Control other colliders exists.
}
}
if (ImGui::MenuItem("Capsule Collider")) {
ComponentCapsuleCollider* capsuleComponent = selected->CreateComponent<ComponentCapsuleCollider>();
if (capsuleComponent != nullptr) {
capsuleComponent->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS; // TODO: Control other colliders exists.
}
}
ImGui::EndMenu();
}
}
void PanelInspector::AddNavigationComponentsOptions(GameObject* selected) {
if (ImGui::BeginMenu("Navigation")) {
if (ImGui::MenuItem("Agent")) {
ComponentAgent* agent = selected->CreateComponent<ComponentAgent>();
if (agent != nullptr) {
agent->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
if (ImGui::MenuItem("Obstacle")) {
ComponentObstacle* obstacle = selected->CreateComponent<ComponentObstacle>();
if (obstacle != nullptr) {
obstacle->Init();
} else {
App->editor->modalToOpen = Modal::COMPONENT_EXISTS;
}
}
ImGui::EndMenu();
}
}
| 31.988006 | 139 | 0.684664 | [
"mesh",
"transform"
] |
00c295531f466b5a36d51eb5aeff97b6ec8f9f9c | 2,062 | cc | C++ | third_party/benchmark/test/filter_test.cc | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 31 | 2016-01-20T05:43:46.000Z | 2022-02-07T09:14:06.000Z | third_party/benchmark/test/filter_test.cc | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 221 | 2016-01-20T18:25:10.000Z | 2016-06-26T02:58:12.000Z | third_party/benchmark/test/filter_test.cc | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 17 | 2016-01-20T04:00:21.000Z | 2019-03-12T02:41:25.000Z | #include "benchmark/benchmark.h"
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <string>
namespace {
double CalculatePi(int depth) {
double pi = 0.0;
for (int i = 0; i < depth; ++i) {
double numerator = static_cast<double>(((i % 2) * 2) - 1);
double denominator = static_cast<double>((2 * i) - 1);
pi += numerator / denominator;
}
return (pi - 1.0) * 4;
}
class TestReporter : public benchmark::internal::ConsoleReporter {
public:
virtual bool ReportContext(const Context& context) const {
return ConsoleReporter::ReportContext(context);
};
virtual void ReportRuns(const std::vector<Run>& report) const {
++count_;
ConsoleReporter::ReportRuns(report);
};
TestReporter() : count_(0) {}
virtual ~TestReporter() {}
size_t GetCount() const {
return count_;
}
private:
mutable size_t count_;
};
} // end namespace
static void BM_CalculatePiRange(benchmark::State& state) {
double pi = 0.0;
while (state.KeepRunning())
pi = CalculatePi(state.range_x());
std::stringstream ss;
ss << pi;
state.SetLabel(ss.str());
}
BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024);
static void BM_CalculatePi(benchmark::State& state) {
static const int depth = 1024;
double pi BENCHMARK_UNUSED = 0.0;
while (state.KeepRunning()) {
pi = CalculatePi(depth);
}
}
BENCHMARK(BM_CalculatePi)->Threads(8);
BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32);
BENCHMARK(BM_CalculatePi)->ThreadPerCpu();
int main(int argc, const char* argv[]) {
benchmark::Initialize(&argc, argv);
assert(CalculatePi(1) == 0.0);
TestReporter test_reporter;
benchmark::RunSpecifiedBenchmarks(&test_reporter);
// Make sure we ran all of the tests
const size_t count = test_reporter.GetCount();
const size_t expected = (argc == 2) ? std::stoul(argv[1]) : count;
if (count != expected) {
std::cerr << "ERROR: Expected " << expected << " tests to be ran but only "
<< count << " completed" << std::endl;
return -1;
}
}
| 23.701149 | 79 | 0.666343 | [
"vector"
] |
00c2c2d801125f916e38ae482b2cf8504cdfc369 | 674 | cpp | C++ | Data_Structures/Array/range_queries.cpp | Spnetic-5/DSA_Python | 47b48186400bd4e6fe3e0df43c231e33a746272e | [
"MIT"
] | 1 | 2021-05-26T21:01:54.000Z | 2021-05-26T21:01:54.000Z | Data_Structures/Array/range_queries.cpp | Spnetic-5/DSA_Python | 47b48186400bd4e6fe3e0df43c231e33a746272e | [
"MIT"
] | null | null | null | Data_Structures/Array/range_queries.cpp | Spnetic-5/DSA_Python | 47b48186400bd4e6fe3e0df43c231e33a746272e | [
"MIT"
] | null | null | null | // -------------------------------------------------------------------- Range Queries ----------------------------------------------------------------------------
// Time Complexity O(Q+N)
#include <bits/stdc++.h>
using namespace std;
int main(){
int n=10;
vector<int> arr(n+1);
vector<vector<int>> queries = {
{2,3,5},
{1,6,3},
{3,9,7},
{0,4,3}
};
for(auto q : queries){
arr[q[0]] += q[2];
arr[q[1]] -= q[2];
}
for(int i=0; i<n; i++){
arr[i] = arr[i] + arr[i-1];
}
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
| 19.823529 | 162 | 0.311573 | [
"vector"
] |
00c3a15883ddaa2331cc9f03c8bd375e81c01695 | 18,065 | cpp | C++ | blast/src/connect/ncbi_socket_cxx.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/connect/ncbi_socket_cxx.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/connect/ncbi_socket_cxx.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id: ncbi_socket_cxx.cpp 594767 2019-10-09 14:55:40Z lavr $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Anton Lavrentiev
*
* File Description:
* C++ wrappers for the C "SOCK" API (UNIX, MS-Win, MacOS, Darwin)
* Implementation of out-of-line methods
*
*/
#include <ncbi_pch.hpp>
#include "ncbi_assert.h" // no _ASSERT()s, keep clean from xncbi
#include <connect/ncbi_socket_unix.hpp>
#include <limits.h> // for PATH_MAX
#if defined(NCBI_OS_MSWIN) && !defined(PATH_MAX)
# define PATH_MAX 512 // will actually use less than 32 chars
#endif // NCBI_OS_MSWIN && !PATH_MAX
BEGIN_NCBI_SCOPE
/////////////////////////////////////////////////////////////////////////////
// CTrigger::
//
CTrigger::~CTrigger()
{
if (m_Trigger)
TRIGGER_Close(m_Trigger);
}
/////////////////////////////////////////////////////////////////////////////
// CSocket::
//
CSocket::CSocket(const string& host,
unsigned short port,
const STimeout* timeout,
TSOCK_Flags flags)
: m_IsOwned(eTakeOwnership),
r_timeout(0/*kInfiniteTimeout*/), w_timeout(0), c_timeout(0)
{
if (timeout && timeout != kDefaultTimeout) {
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
SOCK_CreateEx(host.c_str(), port, o_timeout, &m_Socket, 0, 0, flags);
}
CSocket::CSocket(unsigned int host,
unsigned short port,
const STimeout* timeout,
TSOCK_Flags flags)
: m_IsOwned(eTakeOwnership),
r_timeout(0/*kInfiniteTimeout*/), w_timeout(0), c_timeout(0)
{
char x_host[16/*sizeof("255.255.255.255")*/];
if (timeout && timeout != kDefaultTimeout) {
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
if (SOCK_ntoa(host, x_host, sizeof(x_host)) != 0)
m_Socket = 0;
else
SOCK_CreateEx(x_host, port, o_timeout, &m_Socket, 0, 0, flags);
}
CUNIXSocket::CUNIXSocket(const string& path,
const STimeout* timeout,
TSOCK_Flags flags)
{
if (timeout && timeout != kDefaultTimeout) {
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
SOCK_CreateUNIX(path.c_str(), o_timeout, &m_Socket, 0, 0, flags);
}
CSocket::~CSocket()
{
if (m_Socket && m_IsOwned != eNoOwnership)
SOCK_Close(m_Socket);
}
EIO_Status CSocket::Connect(const string& host,
unsigned short port,
const STimeout* timeout,
TSOCK_Flags flags)
{
if ( m_Socket ) {
if (SOCK_Status(m_Socket, eIO_Open) != eIO_Closed)
return eIO_Unknown;
if (m_IsOwned != eNoOwnership)
SOCK_Close(m_Socket);
}
if (timeout != kDefaultTimeout) {
if ( timeout ) {
if (&oo_timeout != timeout)
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
}
EIO_Status status = SOCK_CreateEx(host.c_str(), port, o_timeout,
&m_Socket, 0, 0, flags);
if (status == eIO_Success) {
SOCK_SetTimeout(m_Socket, eIO_Read, r_timeout);
SOCK_SetTimeout(m_Socket, eIO_Write, w_timeout);
SOCK_SetTimeout(m_Socket, eIO_Close, c_timeout);
} else
assert(!m_Socket);
return status;
}
EIO_Status CUNIXSocket::Connect(const string& path,
const STimeout* timeout,
TSOCK_Flags flags)
{
if ( m_Socket ) {
if (SOCK_Status(m_Socket, eIO_Open) != eIO_Closed)
return eIO_Unknown;
if (m_IsOwned != eNoOwnership)
SOCK_Close(m_Socket);
}
if (timeout != kDefaultTimeout) {
if ( timeout ) {
if (&oo_timeout != timeout)
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
}
EIO_Status status = SOCK_CreateUNIX(path.c_str(), o_timeout,
&m_Socket, 0, 0, flags);
if (status == eIO_Success) {
SOCK_SetTimeout(m_Socket, eIO_Read, r_timeout);
SOCK_SetTimeout(m_Socket, eIO_Write, w_timeout);
SOCK_SetTimeout(m_Socket, eIO_Close, c_timeout);
} else
assert(!m_Socket);
return status;
}
EIO_Status CSocket::Reconnect(const STimeout* timeout)
{
if (timeout != kDefaultTimeout) {
if ( timeout ) {
if (&oo_timeout != timeout)
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
}
return m_Socket ? SOCK_Reconnect(m_Socket, 0, 0, o_timeout) : eIO_Closed;
}
EIO_Status CSocket::SetTimeout(EIO_Event event, const STimeout* timeout)
{
if (timeout == kDefaultTimeout)
return eIO_Success;
switch (event) {
case eIO_Open:
if ( timeout ) {
if (&oo_timeout != timeout)
oo_timeout = *timeout;
o_timeout = &oo_timeout;
} else
o_timeout = 0/*kInfiniteTimeout*/;
break;
case eIO_Read:
if ( timeout ) {
if (&rr_timeout != timeout)
rr_timeout = *timeout;
r_timeout = &rr_timeout;
} else
r_timeout = 0/*kInfiniteTimeout*/;
break;
case eIO_Write:
if ( timeout ) {
if (&ww_timeout != timeout)
ww_timeout = *timeout;
w_timeout = &ww_timeout;
} else
w_timeout = 0/*kInfiniteTimeout*/;
break;
case eIO_ReadWrite:
if ( timeout ) {
if (&rr_timeout != timeout)
rr_timeout = *timeout;
r_timeout = &rr_timeout;
if (&ww_timeout != timeout)
ww_timeout = *timeout;
w_timeout = &ww_timeout;
} else {
r_timeout = 0/*kInfiniteTimeout*/;
w_timeout = 0/*kInfiniteTimeout*/;
}
break;
case eIO_Close:
if ( timeout ) {
if (&cc_timeout != timeout)
cc_timeout = *timeout;
c_timeout = &cc_timeout;
} else
c_timeout = 0/*kInfiniteTimeout*/;
break;
default:
return eIO_InvalidArg;
}
return m_Socket ? SOCK_SetTimeout(m_Socket, event, timeout) : eIO_Success;
}
const STimeout* CSocket::GetTimeout(EIO_Event event) const
{
switch (event) {
case eIO_Open:
return o_timeout;
case eIO_Read:
return r_timeout;
case eIO_Write:
return w_timeout;
case eIO_ReadWrite:
if ( !r_timeout )
return w_timeout;
if ( !w_timeout )
return r_timeout;
return ((unsigned long) r_timeout->sec * 1000000 + r_timeout->usec >
(unsigned long) w_timeout->sec * 1000000 + w_timeout->usec)
? w_timeout : r_timeout;
case eIO_Close:
return c_timeout;
default:
break;
}
return kDefaultTimeout;
}
EIO_Status CSocket::Read(void* buf,
size_t size,
size_t* n_read,
EIO_ReadMethod how)
{
if ( m_Socket )
return SOCK_Read(m_Socket, buf, size, n_read, how);
if ( n_read )
*n_read = 0;
return eIO_Closed;
}
EIO_Status CSocket::ReadLine(string& str)
{
str.erase();
if ( !m_Socket )
return eIO_Closed;
EIO_Status status;
char buf[1024];
size_t size;
do {
status = SOCK_ReadLine(m_Socket, buf, sizeof(buf), &size);
if (!size)
break;
str.append(buf, size);
} while (status == eIO_Success && size == sizeof(buf));
return status;
}
EIO_Status CSocket::Write(const void* buf,
size_t size,
size_t* n_written,
EIO_WriteMethod how)
{
if ( m_Socket )
return SOCK_Write(m_Socket, buf, size, n_written, how);
if ( n_written )
*n_written = 0;
return eIO_Closed;
}
void CSocket::GetPeerAddress(unsigned int* host,
unsigned short* port,
ENH_ByteOrder byte_order) const
{
if ( !m_Socket ) {
if ( host )
*host = 0;
if ( port )
*port = 0;
} else
SOCK_GetPeerAddress(m_Socket, host, port, byte_order);
}
string CSocket::GetPeerAddress(ESOCK_AddressFormat format) const
{
char buf[PATH_MAX + 1];
if (m_Socket &&
SOCK_GetPeerAddressStringEx(m_Socket, buf, sizeof(buf), format) != 0) {
return string(buf);
}
return "";
}
void CSocket::Reset(SOCK sock, EOwnership if_to_own, ECopyTimeout whence)
{
if (m_Socket != sock) {
if (m_Socket && m_IsOwned != eNoOwnership)
SOCK_Close(m_Socket);
m_Socket = sock;
}
m_IsOwned = if_to_own;
if (whence == eCopyTimeoutsFromSOCK) {
if ( sock ) {
const STimeout* timeout;
timeout = SOCK_GetTimeout(sock, eIO_Read);
if ( timeout ) {
rr_timeout = *timeout;
r_timeout = &rr_timeout;
} else
r_timeout = 0/*kInfiniteTimeout*/;
timeout = SOCK_GetTimeout(sock, eIO_Write);
if ( timeout ) {
ww_timeout = *timeout;
w_timeout = &ww_timeout;
} else
w_timeout = 0/*kInfiniteTimeout*/;
timeout = SOCK_GetTimeout(sock, eIO_Close);
if ( timeout ) {
cc_timeout = *timeout;
c_timeout = &cc_timeout;
} else
c_timeout = 0/*kInfiniteTimeout*/;
} else
r_timeout = w_timeout = c_timeout = 0/*kInfiniteTimeout*/;
} else if ( sock ) {
SOCK_SetTimeout(sock, eIO_Read, r_timeout);
SOCK_SetTimeout(sock, eIO_Write, w_timeout);
SOCK_SetTimeout(sock, eIO_Close, c_timeout);
}
}
/////////////////////////////////////////////////////////////////////////////
// CDatagramSocket::
//
EIO_Status CDatagramSocket::Connect(unsigned int host,
unsigned short port)
{
char addr[40];
if (host && SOCK_ntoa(host, addr, sizeof(addr)) != 0)
return eIO_Unknown;
return m_Socket
? DSOCK_Connect(m_Socket, host ? addr : 0, port)
: eIO_Closed;
}
EIO_Status CDatagramSocket::Recv(void* buf,
size_t buflen,
size_t* msglen,
string* sender_host,
unsigned short* sender_port,
size_t maxmsglen)
{
if ( !m_Socket ) {
if ( msglen )
*msglen = 0;
if ( sender_host )
*sender_host = "";
if ( sender_port )
*sender_port = 0;
return eIO_Closed;
}
unsigned int addr;
EIO_Status status = DSOCK_RecvMsg(m_Socket, buf, buflen, maxmsglen,
msglen, &addr, sender_port);
if ( sender_host )
*sender_host = CSocketAPI::ntoa(addr);
return status;
}
/////////////////////////////////////////////////////////////////////////////
// CListeningSocket::
//
CListeningSocket::~CListeningSocket()
{
Close();
}
EIO_Status CListeningSocket::Accept(CSocket*& sock,
const STimeout* timeout,
TSOCK_Flags flags) const
{
if ( !m_Socket ) {
sock = 0;
return eIO_Closed;
}
SOCK x_sock;
EIO_Status status;
status = LSOCK_AcceptEx(m_Socket, timeout, &x_sock, flags);
assert(!x_sock ^ !(status != eIO_Success));
if (status == eIO_Success) {
try {
sock = new CSocket;
} catch (...) {
sock = 0;
SOCK_Abort(x_sock);
SOCK_Close(x_sock);
throw;
}
sock->Reset(x_sock, eTakeOwnership, eCopyTimeoutsToSOCK);
} else
sock = 0;
return status;
}
EIO_Status CListeningSocket::Accept(CSocket& sock,
const STimeout* timeout,
TSOCK_Flags flags) const
{
SOCK x_sock;
EIO_Status status;
if ( !m_Socket ) {
x_sock = 0;
status = eIO_Closed;
} else
status = LSOCK_AcceptEx(m_Socket, timeout, &x_sock, flags);
assert(!x_sock ^ !(status != eIO_Success));
sock.Reset(x_sock, eTakeOwnership, eCopyTimeoutsToSOCK);
return status;
}
EIO_Status CListeningSocket::Close(void)
{
if ( !m_Socket )
return eIO_Closed;
EIO_Status status = m_IsOwned != eNoOwnership
? LSOCK_Close(m_Socket) : eIO_Success;
m_Socket = 0;
return status;
}
/////////////////////////////////////////////////////////////////////////////
// CSocketAPI::
//
EIO_Status CSocketAPI::Poll(vector<SPoll>& polls,
const STimeout* timeout,
size_t* n_ready)
{
static const STimeout kZero = {0, 0};
size_t x_n = polls.size();
SPOLLABLE_Poll* x_polls = 0;
size_t x_ready = 0;
if (x_n && !(x_polls = new SPOLLABLE_Poll[x_n]))
return eIO_Unknown;
for (size_t i = 0; i < x_n; ++i) {
CPollable* p = polls[i].m_Pollable;
EIO_Event event = polls[i].m_Event;
if (p && event) {
CSocket* s = dynamic_cast<CSocket*>(p);
if (!s) {
CListeningSocket* ls = dynamic_cast<CListeningSocket*>(p);
if (!ls) {
CTrigger* tr = dynamic_cast<CTrigger*>(p);
x_polls[i].poll = POLLABLE_FromTRIGGER(tr
? tr->GetTRIGGER()
: 0);
} else
x_polls[i].poll = POLLABLE_FromLSOCK(ls->GetLSOCK());
polls[i].m_REvent = eIO_Open;
} else {
EIO_Event revent;
if (s->GetStatus(eIO_Open) != eIO_Closed) {
x_polls[i].poll = POLLABLE_FromSOCK(s->GetSOCK());
revent = eIO_Open;
} else {
x_polls[i].poll = 0;
revent = eIO_Close;
++x_ready;
}
polls[i].m_REvent = revent;
}
x_polls[i].event = event;
} else {
x_polls[i].poll = 0;
polls[i].m_REvent = eIO_Open;
}
}
size_t xx_ready;
EIO_Status status = POLLABLE_Poll(x_n, x_polls,
x_ready ? &kZero : timeout, &xx_ready);
for (size_t i = 0; i < x_n; ++i) {
if (x_polls[i].revent)
polls[i].m_REvent = x_polls[i].revent;
}
if (n_ready)
*n_ready = xx_ready + x_ready;
delete[] x_polls;
return status;
}
string CSocketAPI::ntoa(unsigned int host)
{
char addr[40];
if (SOCK_ntoa(host, addr, sizeof(addr)) != 0)
*addr = 0;
return string(addr);
}
string CSocketAPI::gethostname(ESwitch log)
{
char hostname[256];
if (SOCK_gethostnameEx(hostname, sizeof(hostname), log) != 0)
*hostname = 0;
return string(hostname);
}
string CSocketAPI::gethostbyaddr(unsigned int host, ESwitch log)
{
char hostname[256];
if (!SOCK_gethostbyaddrEx(host, hostname, sizeof(hostname), log))
*hostname = 0;
return string(hostname);
}
unsigned int CSocketAPI::gethostbyname(const string& host, ESwitch log)
{
return SOCK_gethostbynameEx(host == kEmptyStr ? 0 : host.c_str(), log);
}
string CSocketAPI::HostPortToString(unsigned int host,
unsigned short port)
{
char buf[80];
size_t len = SOCK_HostPortToString(host, port, buf, sizeof(buf));
return string(buf, len);
}
SIZE_TYPE CSocketAPI::StringToHostPort(const string& str,
unsigned int* host,
unsigned short* port)
{
const char* s = str.c_str();
const char* e = SOCK_StringToHostPort(s, host, port);
return e ? (SIZE_TYPE)(e - s) : NPOS;
}
END_NCBI_SCOPE
| 28.950321 | 79 | 0.523554 | [
"vector"
] |
00c84701d37dd89f8c9bf7df54b31a4d9fcecc24 | 5,339 | cpp | C++ | src/impl/client_impl_rest.cpp | CreeperLin/dlsrest | fbc6ce363b00bc26e1d06e3d03b6e88437422232 | [
"MIT"
] | 1 | 2021-07-01T09:59:07.000Z | 2021-07-01T09:59:07.000Z | src/impl/client_impl_rest.cpp | CreeperLin/dlsrest | fbc6ce363b00bc26e1d06e3d03b6e88437422232 | [
"MIT"
] | null | null | null | src/impl/client_impl_rest.cpp | CreeperLin/dlsrest | fbc6ce363b00bc26e1d06e3d03b6e88437422232 | [
"MIT"
] | null | null | null | #include <cpprest/http_client.h>
#include <cpprest/json.h>
#pragma comment(lib, "cpprest_2_10")
using namespace web;
using namespace web::http;
using namespace web::http::client;
#include <map>
#include <iostream>
#include "../common/utils.hpp"
#include "../server/server.hpp"
#include "def.hpp"
using namespace std;
map<string, http_client *> client_map;
pplx::task<http_response> make_task_request(
http_client &client,
method mtd,
string const &path,
json::value const &jvalue)
{
return (mtd == methods::GET || mtd == methods::HEAD) ? client.request(mtd, path) : client.request(mtd, path, jvalue);
}
http_client &get_client(string const &address)
{
if (client_map.find(address) == client_map.end())
{
client_map[address] = new http_client(U(address));
}
return *client_map[address];
}
void make_request(
string const &address,
method mtd,
string const &path,
json::value const &jvalue,
json::value &ret)
{
TRACE("cli: " + address + " " + mtd + " " + path + " " + jvalue.serialize());
make_task_request(get_client(address), mtd, path, jvalue)
.then([](http_response response)
{
if (response.status_code() == status_codes::OK)
{
return response.extract_json();
}
return pplx::task_from_result(json::value());
})
.then([&ret](pplx::task<json::value> previousTask)
{
try
{
ret = previousTask.get();
}
catch (http_exception const &e)
{
cout << e.what() << endl;
ret = json::value::object();
ret[STATUS_KEY] = 2;
ret["msg"] = json::value::string(e.what());
}
})
.wait();
if (ret[STATUS_KEY] == 2)
{
TRACE("exc");
http_client *cli = client_map[address];
client_map.erase(address);
delete cli;
} else if (ret[STATUS_KEY].is_null())
{
TRACE("exc null");
ret[STATUS_KEY] = 2;
ret["msg"] = json::value::string("null response");
}
display_json(ret, "R: ");
}
int acquire_lock_impl(string const &addr, string const &res_id, string const &cli_id, string const &auth, string &msg)
{
auto putvalue = json::value::object();
putvalue["res_id"] = json::value::string(res_id);
putvalue["cli_id"] = json::value::string(cli_id);
putvalue["auth"] = auth.empty() ? json::value() : json::value::string(auth);
json::value ret;
make_request(addr, methods::PUT, LOCK_PATH, putvalue, ret);
if (ret.at(STATUS_KEY) == 0)
{
return 0;
}
msg = ret["msg"].as_string();
return 1;
}
int release_lock_impl(string const &addr, string const &res_id, string const &cli_id, string const &auth, string &msg)
{
auto putvalue = json::value::object();
putvalue["res_id"] = json::value::string(res_id);
putvalue["cli_id"] = json::value::string(cli_id);
putvalue["auth"] = auth.empty() ? json::value() : json::value::string(auth);
json::value ret;
make_request(addr, methods::DEL, LOCK_PATH, putvalue, ret);
if (ret.at(STATUS_KEY) == 0)
{
return 0;
}
msg = ret["msg"].as_string();
return 1;
}
int stat_lock_impl(string const &addr, string const &res_id, string &stat, string &msg)
{
auto putvalue = json::value::object();
json::value ret;
putvalue["res_id"] = json::value::string(res_id);
make_request(addr, methods::POST, LOCK_PATH, putvalue, ret);
if (ret.at(STATUS_KEY) == 0)
{
stat = ret.at("stat").serialize();
return 0;
}
msg = ret["msg"].as_string();
return 1;
}
int list_lock_impl(string const &addr, map<string, Lock> &map, string &msg)
{
json::value ret;
make_request(addr, methods::GET, LOCK_PATH, json::value::null(), ret);
if (ret.at(STATUS_KEY) == 0)
{
for (auto const &p : ret.at("map").as_object())
{
json::value const &val = p.second;
Lock lock;
lock.res_id = p.first;
lock.cli_id = val.at("cli_id").as_string();
lock.expiry = val.at("expiry").as_integer();
lock.timestamp = val.at("timestamp").as_integer();
map[p.first] = lock;
}
return 0;
}
msg = ret["msg"].as_string();
return 1;
}
int hbeat_impl(string const &addr, string const &self_addr, string &msg)
{
auto putvalue = json::value::object();
json::value ret;
putvalue["addr"] = json::value::string(self_addr);
make_request(addr, methods::POST, HBEAT_PATH, putvalue, ret);
if (ret.at(STATUS_KEY) == 0)
{
return 0;
}
msg = ret["msg"].as_string();
return 1;
}
int auth_impl(string const &addr, string &auth, string &msg)
{
auto putvalue = json::value::object();
json::value ret;
make_request(addr, methods::POST, AUTH_PATH, putvalue, ret);
if (ret.at(STATUS_KEY) == 0)
{
auth = ret["auth"].as_string();
return 0;
}
msg = ret["msg"].as_string();
return 1;
}
void destory_clients_impl()
{
for (auto const &p : client_map)
{
delete p.second;
}
}
| 28.550802 | 121 | 0.566773 | [
"object"
] |
00dc84fe8c57412e57385c5ad1c0280bdf19fc5d | 3,030 | hpp | C++ | Include/FireEngine/Math/Vec3.hpp | storm20200/CMakeTesting | 0c3a68398d1c83636cae8d31e751c7d4796e04da | [
"MIT"
] | null | null | null | Include/FireEngine/Math/Vec3.hpp | storm20200/CMakeTesting | 0c3a68398d1c83636cae8d31e751c7d4796e04da | [
"MIT"
] | 2 | 2016-02-20T19:37:52.000Z | 2016-02-27T01:34:08.000Z | Include/FireEngine/Math/Vec3.hpp | storm20200/FireEngine | 0c3a68398d1c83636cae8d31e751c7d4796e04da | [
"MIT"
] | null | null | null | #ifndef FIRE_VEC3_HPP
#define FIRE_VEC3_HPP
#include <FireEngine/Utility/TypeTraits.hpp>
namespace fire
{
/// A mathematical 3-dimensional vector containing an X, Y and Z component. This can be used extensively as a constexpr
/// entity for compile-time computation.
/// \tparam T A floating-point or integer data type is expected. Anything else will likely create compiler errors.
template <typename T>
struct Vec3 final
{
// Require T to be an arithmetic type and not a bool.
//static_assert (is_arithmetic_excluding_v<T, bool, char>,
// "Vec3 can only be instantiated with arithmetic types, excluding bool.");
//
// Constructors and destructor.
//
/// \brief Defaults the Vec3 to (0,0,0).
constexpr Vec3<T>() noexcept = default;
/// \brief Sets each component to the value specified, e.g. (1,1,1).
/// \param value The value each component should be set to.
constexpr Vec3<T> (const T value) noexcept
: x (value), y (value), z (value) { }
/// \brief Sets the initial value of each component.
constexpr Vec3<T> (const T x_, const T y_, const T z_) noexcept
: x (x_), y (y_), z (z_) { }
constexpr Vec3<T> (const Vec3<T>& copy) noexcept = default;
constexpr Vec3<T> (Vec3<T>&& move) noexcept = default;
constexpr Vec3<T>& operator= (const Vec3<T>& copy) noexcept = default;
constexpr Vec3<T>& operator= (Vec3<T>&& move) noexcept = default;
~Vec3<T>() noexcept = default;
//
// Static methods.
//
// All type statics.
static constexpr Vec3<T> zero() noexcept { return { zeroValue }; }
static constexpr Vec3<T> right() noexcept { return { oneValue, zeroValue, zeroValue }; }
static constexpr Vec3<T> up() noexcept { return { zeroValue, oneValue, zeroValue }; }
static constexpr Vec3<T> back() noexcept { return { zeroValue, zeroValue, oneValue }; }
// Signed-only statics.
static constexpr Vec3<enable_if_signed_t<T>> left() noexcept { return { -oneValue, zeroValue, zeroValue }; }
static constexpr Vec3<enable_if_signed_t<T>> down() noexcept { return { zeroValue, -oneValue, zeroValue }; }
static constexpr Vec3<enable_if_signed_t<T>> forward() noexcept { return { zeroValue, zeroValue, -oneValue }; }
//
// Static members.
//
static constexpr T zeroValue { T (0) }; ///< Represents 0 for the given data type.
static constexpr T oneValue { T (1) }; ///< Represents 1 for the given data type.
//
// Members.
//
T x { zeroValue }; ///< The X component representing right/left.
T y { zeroValue }; ///< The Y component representing up/down.
T z { zeroValue }; ///< The Z component representing forward/backward.
};
}
#endif // FIRE_VEC3_HPP
| 42.083333 | 123 | 0.59736 | [
"vector"
] |
00dea3cbb493787c2bf89868971791a7fa274c44 | 15,822 | cpp | C++ | Code/System/String.cpp | mooming/Kronecker | 952cd025bd0a31fe49f0f0d5e11c35474917300c | [
"MIT"
] | null | null | null | Code/System/String.cpp | mooming/Kronecker | 952cd025bd0a31fe49f0f0d5e11c35474917300c | [
"MIT"
] | null | null | null | Code/System/String.cpp | mooming/Kronecker | 952cd025bd0a31fe49f0f0d5e11c35474917300c | [
"MIT"
] | null | null | null | // Copyright Hansol Park (anav96@naver.com, mooming.go@gmail.com). All rights reserved.
#include "System/String.h"
#include "System/Allocator.h"
#include "System/Debug.h"
#include "System/MemoryManager.h"
#include "System/StdUtil.h"
#include <cstdio>
#include <cstring>
using namespace HE;
String::String(const bool value) : buffer(), hashCode(0)
{
if (value)
{
buffer->resize(5);
auto& text = *buffer;
text[0] = 't';
text[1] = 'r';
text[2] = 'u';
text[3] = 'e';
text[4] = '\0';
}
else
{
buffer->resize(6);
auto& text = *buffer;
text[0] = 'f';
text[1] = 'a';
text[2] = 'l';
text[3] = 's';
text[4] = 'e';
text[5] = '\0';
}
CalculateHashCode();
}
String::String(const Pointer ptr) : buffer(), hashCode(0)
{
buffer->resize(32);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%p", ptr);
CalculateHashCode();
}
String::String(const char letter) : buffer(), hashCode(0)
{
buffer->resize(2);
auto& text = *buffer;
text[0] = letter;
text[1] = '\0';
CalculateHashCode();
}
String::String(const unsigned char value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "0x%02X", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const short value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%d", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const unsigned short value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%ud", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const int value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.capacity(), "%d", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const unsigned int value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%u", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const long value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%ld", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const unsigned long value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%lu", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const long long value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%lld", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const unsigned long long value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%llu", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const float value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%f", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const double value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%f", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const long double value) : buffer(), hashCode(0)
{
buffer->resize(16);
auto& text = *buffer;
snprintf(text.data(), text.size(), "%Lf", value);
buffer->resize(strlen(text.data()) + 1);
CalculateHashCode();
}
String::String(const char* text) : buffer(), hashCode(0)
{
const auto totalLength = strlen(text) + 1;
buffer->resize(totalLength);
Vector<Char>& textVec = *buffer;
memcpy(textVec.data(), text, totalLength);
CalculateHashCode();
}
String::String(const String& string, Index startIndex, Index endIndex) : buffer()
{
if (startIndex >= string.Length())
startIndex = string.Length();
if (endIndex > string.Length())
endIndex = string.Length();
if (startIndex > endIndex)
startIndex = endIndex;
auto length = endIndex - startIndex;
if (length > 0)
{
buffer->resize(length + 1);
auto ptr = buffer->data();
memcpy(ptr, string.buffer->data() + startIndex, length);
ptr[length] = '\0';
CalculateHashCode();
}
else
{
hashCode = 0;
}
}
String& String::operator=(const char* text)
{
if (buffer.GetReferenceCount() > 1)
{
Swap(String(text));
}
else
{
const auto textLength = strlen(text) + 1;
buffer->resize(textLength);
memcpy(buffer->data(), text, textLength);
}
return *this;
}
String& String::operator= (const String& rhs)
{
if (buffer.GetReferenceCount() > 1)
{
Swap(String(rhs.ToCharArray()));
}
else
{
const auto length = rhs.buffer->size();
buffer->resize(length);
memcpy(buffer->data(), rhs.buffer->data(), length);
}
return *this;
}
bool String::operator< (const String& rhs) const
{
const Index shorterLen = std::min(Length(), rhs.Length());
Index matchCount = 0;
for (Index i = 0; i < shorterLen; ++i)
{
if ((*buffer)[i] == (*rhs.buffer)[i])
{
++matchCount;
continue;
}
if ((*buffer)[i] > (*rhs.buffer)[i])
return false;
return true;
}
if (matchCount == shorterLen)
return Length() < rhs.Length();
return true;
}
bool String::operator==(const String& string) const
{
if (hashCode != string.hashCode)
return false;
const auto length = Length();
if (length != string.Length())
return false;
for (Index i = 0; i < length; ++i)
{
if ((*buffer)[i] != (*string.buffer)[i])
return false;
}
return true;
}
const char* String::ToCharArray() const
{
return buffer ? buffer.Get().data() : "";
}
String String::Clone() const
{
String str;
Assert(str.buffer);
*(str.buffer) = *buffer;
return str;
}
bool String::ContainsAt(const String& keyword, Index startIndex) const
{
const Index endIndex = startIndex + keyword.Length();
if (endIndex > Length())
return false;
Index index = 0;
for (Index i = startIndex; i < endIndex; ++i, ++index)
{
if ((*buffer)[i] != (*keyword.buffer)[index])
return false;
}
return true;
}
Index String::Find(const Char ch) const
{
const auto length = Length();
for (Index i = 0; i < length; ++i)
{
if ((*buffer)[i] == ch)
return i;
}
return length;
}
Index String::Find(const Array<Char>& chs) const
{
const auto length = Length();
auto chsLen = chs.Length();
for (Index i = 0; i < length; ++i)
{
for (decltype(chsLen) j = 0; j < chsLen; ++j)
{
if ((*buffer)[i] == chs[j])
return i;
}
}
return length;
}
Index String::Find(const String& keyword) const
{
const auto length = Length();
const auto keywordLength = Length();
if (keywordLength > length)
return length;
const Index lastIndex = length - keywordLength + 1;
for (Index i = 0; i < lastIndex; ++i)
{
if (ContainsAt(keyword, i))
return i;
}
return length;
}
Index String::Find(const String& keyword, Index startIndex, Index endIndex) const
{
const auto length = Length();
const auto keywordLength = Length();
Assert(startIndex < length);
if (startIndex >= length)
startIndex = length - 1;
Assert(endIndex >= startIndex);
if (endIndex < startIndex)
endIndex = startIndex;
Assert(endIndex <= length);
if (endIndex > length)
endIndex = length;
if ((startIndex + keywordLength) > endIndex)
return length;
const Index lastIndex = endIndex - keywordLength + 1;
for (Index i = startIndex; i < lastIndex; ++i)
{
if (ContainsAt(keyword, i))
return i;
}
return length;
}
Index String::FindLast(const Char ch) const
{
const auto length = Length();
for (Index i = length; i > 0;)
{
if ((*buffer)[--i] == ch)
return i;
}
return length;
}
String String::Append(const Char letter) const
{
String str;
const auto length = Length();
str.buffer->resize(length + sizeof(Char) + 1);
memcpy(str.buffer->data(), buffer->data(), length);
(*str.buffer)[length] = letter;
(*str.buffer)[length + 1] = '\0';
return str;
}
String String::Append(const int value) const
{
char tmp[16];
snprintf(tmp, sizeof(tmp), "%d", value);
const auto length = Length();
const Index tmpLength = static_cast<Index>(strlen(tmp));
String str;
str.buffer->resize(length + tmpLength + 1);
memcpy(str.buffer->data(), buffer->data(), length);
memcpy(str.buffer->data() + length, tmp, tmpLength + 1);
return str;
}
String String::Append(const float value) const
{
char tmp[16];
snprintf(tmp, sizeof(tmp), "%f", value);
const auto length = Length();
const Index tmpLength = static_cast<Index>(strlen(tmp));
String str;
str.buffer->resize(length + tmpLength + 1);
memcpy(str.buffer->data(), buffer->data(), length);
memcpy(str.buffer->data() + length, tmp, tmpLength + 1);
return str;
}
String String::Append(const Char* text) const
{
const auto length = Length();
const Index textLength = static_cast<Index>(strlen(text));
String str;
str.buffer->resize(length + textLength + 1);
memcpy(str.buffer->data(), buffer->data(), length);
memcpy(str.buffer->data() + length, text, textLength + 1);
return str;
}
String String::Append(const String& string) const
{
if (string.IsEmpty())
return Clone();
const auto length = Length();
const auto strLength = string.Length();
String str;
str.buffer->resize(length + strLength + 1);
memcpy(str.buffer->data(), buffer->data(), length);
memcpy(str.buffer->data() + length, string.buffer->data(), strLength + 1);
return str;
}
void String::AppendSelf(const Char letter)
{
const auto index = Length();
buffer->push_back('\0');
buffer.Get()[index] = letter;
}
void String::AppendSelf(const int value)
{
char tmp[16];
snprintf(tmp, sizeof(tmp), "%d", value);
const auto length = Length();
const Index tmpLength = static_cast<Index>(strlen(tmp));
const auto newLength = length + tmpLength + 1;
if (newLength > buffer->capacity())
{
buffer->reserve(newLength * 3 / 2);
}
buffer->resize(newLength);
memcpy(buffer->data() + length, tmp, tmpLength + 1);
}
void String::AppendSelf(const float value)
{
char tmp[16];
snprintf(tmp, sizeof(tmp), "%f", value);
const auto length = Length();
const Index tmpLength = static_cast<Index>(strlen(tmp));
const auto newLength = length + tmpLength + 1;
if (newLength > buffer->capacity())
{
buffer->reserve(newLength * 3 / 2);
}
buffer->resize(newLength);
memcpy(buffer->data() + length, tmp, tmpLength + 1);
}
void String::AppendSelf(const Char* text)
{
const auto length = Length();
const Index textLength = static_cast<Index>(strlen(text));;
const auto newLength = length + textLength + 1;
if (newLength > buffer->capacity())
{
buffer->reserve(newLength * 3 / 2);
}
buffer->resize(newLength);
memcpy(buffer->data() + length, text, textLength + 1);
}
void String::AppendSelf(const String& string)
{
if (string.IsEmpty())
return;
const auto length = Length();
const Index textLength = string.Length();
const auto newLength = length + textLength + 1;
if (newLength > buffer->capacity())
{
buffer->reserve(newLength * 3 / 2);
}
buffer->resize(newLength);
memcpy(buffer->data() + length, string.buffer->data(), textLength + 1);
}
String String::Replace(const String& from, const String& to, Index offset, Index endIndex) const
{
// TODO - NOT IMPLEMENTED YET
Assert(false);
return String();
}
String String::ReplaceAll(char from, char to) const
{
if (!buffer)
return String();
String str = Clone();
Char* data = str.buffer->data();
Assert(data != nullptr);
Index length = str.Length();
for (Index i = 0; i < length; ++i)
{
if (data[i] == from)
data[i] = to;
}
str.CalculateHashCode();
return str;
}
String String::ReplaceAll(String from, String to) const
{
// TODO - NOT IMPLEMENTED YET
Assert(false);
return String();
}
void String::ParseKeyValue(String& key, String& value)
{
auto index = Find("=");
key = SubString(0, index).Trim();
value = SubString(index + 1).Trim();
}
void String::CalculateHashCode()
{
hashCode = 5381;
const auto length = Length();
auto text = buffer->data();
Assert(length != 0 || text[0] == '\0');
for (Index i = 0; i < length; ++i)
{
Index ch = text[i];
hashCode = ((hashCode << 5) + hashCode) + ch; /* hash * 33 + c */
}
}
void String::ResetBuffer(size_t size)
{
buffer->reserve(static_cast<Index>(size + 1));
buffer->clear();
buffer->push_back('\0');
}
#ifdef __UNIT_TEST__
#include "Time.h"
#include <iostream>
bool StringTest::DoTest()
{
using namespace std;
String str = "Hello? World!";
cout << str << endl;
if (str != "Hello? World!")
{
cout << "String Compare Failure." << endl;
return false;
}
auto lower = str.GetLowerCase();
cout << lower << endl;
if (lower != "hello? world!")
{
cout << "To lowercase failed." << endl;
return false;
}
auto upper = str.GetUpperCase();
cout << upper << endl;
if (upper != "HELLO? WORLD!")
{
cout << "To uppercase failed." << endl;
return false;
}
auto tmpString = std::move(upper);
cout << tmpString << endl;
if (tmpString != "HELLO? WORLD!")
{
cout << "String move failed." << endl;
return false;
}
auto lastL = str.FindLast('l');
if (lastL != 10)
{
cout << "Failed to find the last 'l', index = " << lastL << ", but expected 10." << endl;
}
auto afterL = str.SubString(lastL);
cout << afterL << endl;
if (afterL != "ld!")
{
cout << "Substring failed" << endl;
return false;
}
constexpr int COUNT = 100000;
float heTime = 0.0f;
{
Time::MeasureSec measure(heTime);
String str;
for (int i = 0; i < COUNT; ++i)
{
str = "";
for (char ch = 'a'; ch <= 'z'; ++ch)
{
str += ch;
}
}
}
float stlTime = 0.0f;
{
Time::MeasureSec measure(stlTime);
std::string str;
for (int i = 0; i < COUNT; ++i)
{
str = "";
for (char ch = 'a'; ch <= 'z'; ++ch)
{
str += ch;
}
}
}
cout << "Time: he = " << heTime << ", stl = " << stlTime << endl;
return true;
}
#endif //__UNIT_TEST__
| 21.585266 | 97 | 0.570408 | [
"vector"
] |
00e6a94bdca8135a80a0021e819a22933c543c41 | 272 | cpp | C++ | Leetcode/0455. Assign Cookies/0455.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0455. Assign Cookies/0455.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0455. Assign Cookies/0455.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(begin(g), end(g));
sort(begin(s), end(s));
int i = 0;
for (int j = 0; j < s.size() && i < g.size(); ++j)
if (g[i] <= s[j])
++i;
return i;
}
};
| 18.133333 | 59 | 0.474265 | [
"vector"
] |
00e6db04f9c5edd68918ebde5fb9a35432267d36 | 1,643 | cpp | C++ | SPOJ/SPOJ - NKLEAVES/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | SPOJ/SPOJ - NKLEAVES/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | SPOJ/SPOJ - NKLEAVES/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2020-07-07 16:40:31
* solution_verdict: Accepted language: C++
* run_time (ms): 190 memory_used (MB): 15.4
* problem: https://vjudge.net/problem/SPOJ-NKLEAVES
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define long long long
using namespace std;
const int N=1e5;
int a[N+2];long qm[N+2],an[N+2],dp[10+2][N+2];
void dfs(int i,int lo,int hi,int lt,int rt)
{
if(lo>hi)return ;
int j=(lo+hi)>>1,op;long &mn=dp[i][j],now;
for(int k=lt,r=min(j,rt);k<=r;k++)
{
now=an[j]-an[k-1]-(qm[j]-qm[k-1])*(k-1)+dp[i-1][k-1];
//cout<<k<<" "<<j<<" "<<an[j]-an[k-1]-(qm[j]-qm[k-1])*(k-1)<<endl;
if(now<mn)mn=now,op=k;
}
dfs(i,lo,j-1,lt,op);dfs(i,j+1,hi,op,rt);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,k;cin>>n>>k;
for(int i=1;i<=n;i++)cin>>a[i],qm[i]=qm[i-1]+a[i];
for(int i=1;i<=n;i++)an[i]=an[i-1]+1LL*a[i]*(i-1);
memset(dp,60,sizeof dp);
for(int i=0;i<10+2;i++)dp[i][0]=0;
for(int i=1;i<=k;i++)dfs(i,1,n,1,n);
cout<<dp[k][n]<<endl;
return 0;
} | 30.425926 | 111 | 0.468655 | [
"vector"
] |
00e7de42aa1970447f307fac8fc1ef01f95e3489 | 14,990 | cpp | C++ | Resonator/Source/PluginEditor.cpp | francoise-rosen/DSP | b24551beb04baf0b1379a3c99b98d29480968ff5 | [
"MIT"
] | null | null | null | Resonator/Source/PluginEditor.cpp | francoise-rosen/DSP | b24551beb04baf0b1379a3c99b98d29480968ff5 | [
"MIT"
] | null | null | null | Resonator/Source/PluginEditor.cpp | francoise-rosen/DSP | b24551beb04baf0b1379a3c99b98d29480968ff5 | [
"MIT"
] | null | null | null | /*
==============================================================================
This file contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
ResonatorAudioProcessorEditor::ResonatorAudioProcessorEditor (ResonatorAudioProcessor& p)
: AudioProcessorEditor (&p), audioProcessor (p)
{
setLookAndFeel(&resonLookAndFeel);
initialiseSliders();
initialiseImageButtons();
addAndMakeVisible(&algoBox);
fillAlgoBox();
bypassButton.setButtonText("On");
bypassButton.setToggleState(true, juce::dontSendNotification);
addAndMakeVisible(&bypassButton);
attachParameters();
setResizable(true, true);
setResizeLimits(segmentLength, segmentLength * 5 / 3, segmentLength * 6, segmentLength * 10);
setSize (segmentLength * 3, segmentLength * 5);
}
ResonatorAudioProcessorEditor::~ResonatorAudioProcessorEditor()
{
setLookAndFeel(nullptr);
}
//==============================================================================
void ResonatorAudioProcessorEditor::fillAlgoBox()
{
// make a list of available band pass algorithms
assert (ResonatorAudioProcessor::listOfAlgorithms.size() == static_cast<int>(sfd::FilterAlgorithm::numOfAlgorithms));
algoBox.addItemList (ResonatorAudioProcessor::listOfAlgorithms, 100);
algoBox.setJustificationType (juce::Justification::centred);
}
void ResonatorAudioProcessorEditor::initialiseSliders()
{
for (int i = 0; i < numOfSliders; ++i)
{
sliderArray.push_back (std::make_unique<juce::Slider> (
juce::Slider::SliderStyle::Rotary, juce::Slider::TextBoxBelow
)
);
sliderArray[i]->setTextBoxStyle (juce::Slider::TextBoxBelow, false, textBoxWidth, textBoxHeight);
sliderArray[i]->setLookAndFeel (&resonLookAndFeel);
addAndMakeVisible (*(sliderArray[i]));
};
}
void ResonatorAudioProcessorEditor::initialiseImageButtons()
{
imageButtonArray.clear();
imageButtonArray.resize (numOfImageButtons);
/* images */
std::array<juce::Image, numOfImageButtons> images {
juce::ImageCache::getFromMemory (BinaryData::github_square_black_png, BinaryData::github_square_black_pngSize),
juce::ImageCache::getFromMemory (BinaryData::linkedin_square_black_png, BinaryData::linkedin_square_black_pngSize),
juce::ImageCache::getFromMemory (BinaryData::soundcloud_square_black_png, BinaryData::soundcloud_square_black_pngSize),
juce::ImageCache::getFromMemory (BinaryData::instagram_square_black_png, BinaryData::instagram_square_black_pngSize)
};
juce::StringArray componentIDs {
"https://github.com/francoise-rosen",
"https://www.linkedin.com/in/stan-barvinsky/",
"https://soundcloud.com/francoise_rosen",
"https://www.instagram.com/francoise.rosen/?hl=en"
};
assert (images.size() == imageButtonArray.size());
for (int i = 0; i < imageButtonArray.size(); ++i)
{
imageButtonArray[i] = std::make_unique<juce::ImageButton>();
imageButtonArray[i]->setImages (false, true, true, images[i], 1.0f, juce::Colours::white.withAlpha (0.75f), images[i], 1.0f, juce::Colours::white.withAlpha (0.25f), images[i], 1.0f, juce::Colours::lightgrey);
imageButtonArray[i]->setComponentID (componentIDs[i]);
addAndMakeVisible (*imageButtonArray[i]);
imageButtonArray[i]->addListener (this);
}
}
void ResonatorAudioProcessorEditor::attachParameters()
{
/* attach the sliders to the AudioProcessorValueTreeState object */
sliderAttachments.clear();
sliderAttachments.resize (sliderArray.size());
for (int i = 0; i < sliderArray.size(); ++i)
{
sliderAttachments[i] = std::make_unique<SliderAttachment> (
audioProcessor.getValueTree(),
paramData::paramArray[i].getID(),
*(sliderArray[i])
);
}
/* attach the combobox to the AudioProcessorValueTreeState object */
algoBoxAttachment = std::make_unique<ComboBoxAttachment> (
audioProcessor.getValueTree(),
paramData::paramArray[paramData::algo].getID(),
algoBox
);
/* attach the bypass button to the AudioProcessorValueTreeState object */
bypassAttachment = std::make_unique<ButtonAttachment> (
audioProcessor.getValueTree(),
paramData::paramArray[paramData::bypass].getID(),
bypassButton
);
}
//==============================================================================
void ResonatorAudioProcessorEditor::paint (juce::Graphics& g)
{
juce::Colour backgroundColour = juce::Colours::black;
g.fillAll (backgroundColour);
resonLookAndFeel.setBackgroundColour(backgroundColour);
g.setColour (juce::Colours::gold.withBrightness(0.26f).withHue(1.72f));
if (frames.size() != numOfFrames)
setFrames();
for (int i = 0; i < frames.size(); ++i)
{
g.drawRoundedRectangle(frames[i]->toFloat(), 7, 2);
if (frames[i] == frames[linkButtonsFrame])
{
g.setColour(backgroundColour.withAlpha(0.5f));
g.fillRect(*frames[linkButtonsFrame]);
g.setColour(juce::Colours::gold.withBrightness(0.26f).withHue(1.72f));
}
}
// add lables
juce::Rectangle<int> resLabelRect {
static_cast<int>(frames[qFrame]->getX() - frames[qFrame]->getWidth() * 0.25f),
static_cast<int>(edge * 2),
static_cast<int>(frames[qFrame]->getWidth() * 0.5f),
static_cast<int>(fontHeight + edge * 2)
};
juce::Rectangle<int> fineLabelRect {
static_cast<int>(frames[fineFrame]->getWidth() * 0.75f - edge * 2),
static_cast<int>(frames[fineFrame]->getBottom() - (fontHeight + edge * 2)),
static_cast<int>(frames[fineFrame]->getWidth() * 0.25f),
static_cast<int>(fontHeight + edge * 2)
};
fineLabelRect.translate(edge * 2, - juce::jmin(20, frames[fineFrame]->getHeight() / 5));
juce::Rectangle<int> gainLabelRect {
frames[gainFrame]->withTop (frames[freqFrame]->getBottom() - fontHeight / 2).withRight(frames[gainFrame]->getRight() - edge * 2)
};
g.setFont(juce::Font("Monaco", "Bold", fontHeight));
g.setColour(resonLookAndFeel.getRimColour());
// g.drawRect(resLabelRect);
// g.drawRect(fineLabelRect);
g.drawFittedText("Fre(Q)ueNCy", frames[freqFrame]->reduced(edge * 2), juce::Justification::topRight, 1);
g.drawFittedText("ReSONaNCe", resLabelRect, juce::Justification::centred, 1);
g.drawFittedText("FINe", fineLabelRect, juce::Justification::centred, 1);
g.drawFittedText("GaIN", gainLabelRect, juce::Justification::topRight, 1);
/* frequency label -> dial pointer */
auto rightX = frames[freqFrame]->getRight();
auto topY = frames[freqFrame]->getY();
std::vector<juce::Point<float>> freqLinePoints
{
/* Point 0 */
{
rightX - edge * 2.0f,
topY + edge * 3 + fontHeight
},
/* Point 1 */
{
rightX * 0.72f,
topY + edge * 3 + fontHeight
},
/* Point 2 */
{
rightX * 0.69f,
topY + edge * 3 + fontHeight
},
/* Point 3 */
{
rightX * 0.72f,
topY + edge * 5 + fontHeight
},
/* Point 4 */
{
rightX * 0.75f,
topY + edge * 7 + fontHeight
},
/* Point 5 */
{
rightX * 0.7f,
topY + edge * 7 + fontHeight * 1.5f
},
/* Point 6 */
{
static_cast<float>(frames[freqFrame]->getCentreX()),
static_cast<float>(frames[freqFrame]->getCentreY())
}
};
g.setColour (resonLookAndFeel.getRimColour().withAlpha(0.5f));
juce::Path freqLinePath;
freqLinePath.startNewSubPath (freqLinePoints[0]);
freqLinePath.lineTo (freqLinePoints[1]);
freqLinePath.quadraticTo (freqLinePoints[2], freqLinePoints[3]);
freqLinePath.cubicTo (freqLinePoints[4], freqLinePoints[5], freqLinePoints[6]);
g.strokePath (freqLinePath, juce::PathStrokeType(2.0f));
/* fine tune label -> dial pointer */
fineLabelRect.getRight();
std::vector<juce::Point<float>> fineLinePoints
{
/* Point 0 */
{
static_cast<float>(fineLabelRect.getRight()),
static_cast<float>(fineLabelRect.getBottom())
},
/* Point 1 */
{
static_cast<float>(fineLabelRect.getX() + 10),
static_cast<float>(fineLabelRect.getBottom())
},
/* Point 2 */
{
static_cast<float>(fineLabelRect.getX() - 10),
static_cast<float>(fineLabelRect.getBottom())
},
/* Point 3 */
{
static_cast<float>(fineLabelRect.getX() - fineLabelRect.getWidth() * 0.75f),
static_cast<float>(fineLabelRect.getBottom() - fineLabelRect.getHeight() * 0.5f)
},
/* Point 4 */
{
static_cast<float>(fineLabelRect.getX()),
static_cast<float>(fineLabelRect.getY())
},
/* Point 5 */
{
static_cast<float>(fineLabelRect.getCentreX()),
static_cast<float>(fineLabelRect.getY() - 10.0f)
},
/* Point 6 */
{
static_cast<float>(fineLabelRect.getX()),
static_cast<float>(fineLabelRect.getY() - fineLabelRect.getHeight())
},
/* Point 7 */
{
static_cast<float>(frames[fineFrame]->getCentreX()),
static_cast<float>(frames[fineFrame]->getCentreY())
}
};
juce::Path fineLinePath;
fineLinePath.startNewSubPath (fineLinePoints[0]);
fineLinePath.lineTo (fineLinePoints[1]);
fineLinePath.cubicTo (fineLinePoints[2], fineLinePoints[3], fineLinePoints[4]);
fineLinePath.cubicTo (fineLinePoints[5], fineLinePoints[6], fineLinePoints[7]);
g.strokePath (fineLinePath, juce::PathStrokeType(2.0f));
/* resonance label -> dial pointer */
std::vector<juce::Point<float>> resLinePoints
{
/* Point 0 */
{
static_cast<float>(resLabelRect.getX()),
static_cast<float>(resLabelRect.getBottom())
},
/* Point 1 */
{
static_cast<float>(resLabelRect.getRight() - 20),
static_cast<float>(resLabelRect.getBottom())
},
/* Point 1 */
{
static_cast<float>(resLabelRect.getRight()),
static_cast<float>(resLabelRect.getBottom())
},
/* Point 3 */
{
static_cast<float>(resLabelRect.getRight() - resLabelRect.getWidth() * 0.25f),
static_cast<float>(resLabelRect.getBottom() + fontHeight / 2)
},
/* Point 4 */
{
static_cast<float>(resLabelRect.getRight() - resLabelRect.getWidth() * 0.35f),
static_cast<float>(resLabelRect.getBottom() + fontHeight)
},
/* Point 5 */
{
static_cast<float>(resLabelRect.getRight() - resLabelRect.getWidth() * 0.25f),
static_cast<float>(resLabelRect.getBottom() + fontHeight + edge)
},
/* Point 6 */
{
static_cast<float>(resLabelRect.getRight() - resLabelRect.getWidth() * 0.15f),
static_cast<float>(resLabelRect.getBottom() + fontHeight + edge * 2)
}
};
juce::Path resLinePath;
resLinePath.startNewSubPath(resLinePoints[0]);
resLinePath.lineTo(resLinePoints[1]);
resLinePath.quadraticTo(resLinePoints[2], resLinePoints[3]);
resLinePath.cubicTo(resLinePoints[4], resLinePoints[5], resLinePoints[6]);
g.strokePath(resLinePath, juce::PathStrokeType(2.0f));
}
void ResonatorAudioProcessorEditor::resized()
{
setFrames();
fontHeight = getHeight() / 30.0f;
// resize sliders
for (int i = 0; i < sliderArray.size(); ++i)
{
sliderArray[i]->setBounds(frames[i]->reduced(edge * 4));
}
// resize combobox
algoBox.setBounds(frames[algorithmListFrame]->reduced(edge * 2.0f, edge * 3.0f));
//algoBox.setBounds(frames[algorithmListFrame]->reduced(edge, edge * 1.5f));
// buttons
auto buttonArea = *frames[linkButtonsFrame];
buttonArea.reduced(edge * 2);
auto buttonWidth = buttonArea.getWidth() / numOfImageButtons;
for (int i = 0; i < imageButtonArray.size(); ++i)
{
imageButtonArray[i]->setBounds(buttonArea.removeFromLeft(buttonWidth).reduced(edge * 1.5, edge * 2));
}
repaint(); // resizes the font height
}
void ResonatorAudioProcessorEditor::setFrames()
{
frames.clear();
frames.resize(numOfFrames);
auto upperHeight = getHeight() * 3 / 10;
auto lowerHeight = upperHeight;
auto midSection = getLocalBounds();
auto upperSection = midSection.removeFromTop(upperHeight);
auto lowerSection = midSection.removeFromBottom(lowerHeight);
frames[freqFrame] = std::make_unique<juce::Rectangle<int>>(midSection);
frames[fineFrame] = std::make_unique<juce::Rectangle<int>>(upperSection.removeFromLeft(getWidth()/2));
frames[qFrame] = std::make_unique<juce::Rectangle<int>>(upperSection);
frames[gainFrame] = std::make_unique<juce::Rectangle<int>>(lowerSection.removeFromRight(getWidth()/2));
frames[algorithmListFrame] = std::make_unique<juce::Rectangle<int>>(lowerSection.removeFromTop(lowerSection.getHeight() * 0.5f));
frames[linkButtonsFrame] = std::make_unique<juce::Rectangle<int>>(lowerSection);
for (int i = 0; i < frames.size(); ++i)
{
assert (frames[i] != nullptr);
}
}
void ResonatorAudioProcessorEditor::buttonClicked(juce::Button* button)
{
juce::URL link {button->getComponentID()};
if (link.isWellFormed())
{
link.launchInDefaultBrowser();
}
}
void ResonatorAudioProcessorEditor::buttonStateChanged(juce::Button* button)
{
}
| 36.560976 | 217 | 0.577985 | [
"object",
"vector"
] |
00f5042ff24ef870626e54eb638c1a5e97efe1b4 | 1,133 | cc | C++ | yggdrasil_decision_forests/model/metadata.cc | google/yggdrasil-decision-forests | 0b284d8afe7ac4773abcdeee88a77681f8681127 | [
"Apache-2.0"
] | 135 | 2021-05-12T18:02:11.000Z | 2022-03-30T16:48:44.000Z | yggdrasil_decision_forests/model/metadata.cc | google/yggdrasil-decision-forests | 0b284d8afe7ac4773abcdeee88a77681f8681127 | [
"Apache-2.0"
] | 11 | 2021-06-25T17:25:38.000Z | 2022-03-30T03:31:24.000Z | yggdrasil_decision_forests/model/metadata.cc | google/yggdrasil-decision-forests | 0b284d8afe7ac4773abcdeee88a77681f8681127 | [
"Apache-2.0"
] | 10 | 2021-05-27T02:51:36.000Z | 2022-03-28T07:03:52.000Z | /*
* Copyright 2021 Google LLC.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "yggdrasil_decision_forests/model/metadata.h"
namespace yggdrasil_decision_forests {
namespace model {
void MetaData::Export(model::proto::Metadata* dst) const {
dst->set_owner(owner_);
dst->set_created_date(created_date_);
dst->set_uid(uid_);
dst->set_framework(framework_);
}
void MetaData::Import(const model::proto::Metadata& src) {
owner_ = src.owner();
created_date_ = src.created_date();
uid_ = src.uid();
framework_ = src.framework();
}
} // namespace model
} // namespace yggdrasil_decision_forests
| 30.621622 | 75 | 0.737864 | [
"model"
] |
00fa554635bcabd95b71bb2d9647651c3e9f92bd | 785 | hpp | C++ | include/GameEngine/GameEnginePch.hpp | DragonJoker/CastorTD | b055df76aff9f42945a0a5e7ed4ddbf03be84381 | [
"MIT"
] | null | null | null | include/GameEngine/GameEnginePch.hpp | DragonJoker/CastorTD | b055df76aff9f42945a0a5e7ed4ddbf03be84381 | [
"MIT"
] | null | null | null | include/GameEngine/GameEnginePch.hpp | DragonJoker/CastorTD | b055df76aff9f42945a0a5e7ed4ddbf03be84381 | [
"MIT"
] | null | null | null | /**
See licence file in root folder, MIT.txt
*/
#pragma once
#ifndef ___EFO_GameEnginePch_HPP___
#define ___EFO_GameEnginePch_HPP___
#include <CastorUtils/Design/Named.hpp>
#include <Castor3D/Cache/OverlayCache.hpp>
#include <Castor3D/Event/Frame/FrameListener.hpp>
#include <Castor3D/Event/Frame/CpuFunctorEvent.hpp>
#include <Castor3D/Event/Frame/GpuFunctorEvent.hpp>
#include <Castor3D/Model/Mesh/Mesh.hpp>
#include <Castor3D/Model/Mesh/Submesh/Submesh.hpp>
#include <Castor3D/Overlay/Overlay.hpp>
#include <Castor3D/Overlay/TextOverlay.hpp>
#include <Castor3D/Scene/Geometry.hpp>
#include <Castor3D/Scene/Scene.hpp>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#endif
| 24.53125 | 51 | 0.788535 | [
"mesh",
"geometry",
"vector",
"model"
] |
00fcf6b79bdb42a3c0d1d6b11de33bd96830ea45 | 107,234 | cc | C++ | components/signin/public/identity_manager/identity_manager_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | components/signin/public/identity_manager/identity_manager_unittest.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | components/signin/public/identity_manager/identity_manager_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2017 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 "components/signin/public/identity_manager/identity_manager.h"
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/flat_set.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/image_fetcher/core/fake_image_decoder.h"
#include "components/signin/internal/identity_manager/account_fetcher_service.h"
#include "components/signin/internal/identity_manager/account_tracker_service.h"
#include "components/signin/internal/identity_manager/accounts_cookie_mutator_impl.h"
#include "components/signin/internal/identity_manager/accounts_mutator_impl.h"
#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h"
#include "components/signin/internal/identity_manager/diagnostics_provider_impl.h"
#include "components/signin/internal/identity_manager/fake_profile_oauth2_token_service.h"
#include "components/signin/internal/identity_manager/gaia_cookie_manager_service.h"
#include "components/signin/internal/identity_manager/primary_account_manager.h"
#include "components/signin/internal/identity_manager/primary_account_mutator_impl.h"
#include "components/signin/internal/identity_manager/primary_account_policy_manager_impl.h"
#include "components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.h"
#include "components/signin/public/base/account_consistency_method.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/base/list_accounts_test_utils.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/base/test_signin_client.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/accounts_cookie_mutator.h"
#include "components/signin/public/identity_manager/device_accounts_synchronizer.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "components/signin/public/identity_manager/set_accounts_in_cookie_result.h"
#include "components/signin/public/identity_manager/test_identity_manager_observer.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "google_apis/gaia/core_account_id.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/cookies/cookie_change_dispatcher.h"
#include "net/cookies/cookie_constants.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_cookie_manager.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_ANDROID)
#include "components/signin/internal/identity_manager/child_account_info_fetcher_android.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/components/account_manager/account_manager_factory.h"
#include "components/account_manager_core/account.h"
#include "components/account_manager_core/chromeos/account_manager.h"
#include "components/signin/internal/identity_manager/test_profile_oauth2_token_service_delegate_chromeos.h"
#endif
namespace signin {
namespace {
const char kTestConsumerId[] = "dummy_consumer";
const char kTestConsumerId2[] = "dummy_consumer 2";
const char kTestGaiaId[] = "dummyId";
const char kTestGaiaId2[] = "dummyId2";
const char kTestGaiaId3[] = "dummyId3";
const char kTestEmail[] = "me@gmail.com";
const char kTestEmail2[] = "me2@gmail.com";
const char kTestEmail3[] = "me3@gmail.com";
const char kTestHostedDomain[] = "example.com";
const char kTestFullName[] = "full_name";
const char kTestGivenName[] = "given_name";
const char kTestLocale[] = "locale";
const char kTestPictureUrl[] = "http://picture.example.com/picture.jpg";
#if BUILDFLAG(IS_CHROMEOS_ASH)
const char kTestEmailWithPeriod[] = "m.e@gmail.com";
#endif
// Subclass of FakeOAuth2AccessTokenManager with bespoke behavior.
class CustomFakeOAuth2AccessTokenManager : public FakeOAuth2AccessTokenManager {
public:
CustomFakeOAuth2AccessTokenManager(
OAuth2AccessTokenManager::Delegate* delegate)
: FakeOAuth2AccessTokenManager(delegate) {}
void set_on_access_token_invalidated_info(
CoreAccountId expected_account_id_to_invalidate,
std::set<std::string> expected_scopes_to_invalidate,
std::string expected_access_token_to_invalidate,
base::OnceClosure callback) {
expected_account_id_to_invalidate_ = expected_account_id_to_invalidate;
expected_scopes_to_invalidate_ = expected_scopes_to_invalidate;
expected_access_token_to_invalidate_ = expected_access_token_to_invalidate;
on_access_token_invalidated_callback_ = std::move(callback);
}
private:
friend class CustomFakeProfileOAuth2TokenService;
// OAuth2AccessTokenManager:
void InvalidateAccessTokenImpl(const CoreAccountId& account_id,
const std::string& client_id,
const ScopeSet& scopes,
const std::string& access_token) override {
if (on_access_token_invalidated_callback_) {
EXPECT_EQ(expected_account_id_to_invalidate_, account_id);
EXPECT_EQ(expected_scopes_to_invalidate_, scopes);
EXPECT_EQ(expected_access_token_to_invalidate_, access_token);
// It should trigger OnAccessTokenRemovedFromCache from
// IdentityManager::DiagnosticsObserver.
for (auto& observer : GetDiagnosticsObserversForTesting())
observer.OnAccessTokenRemoved(account_id, scopes);
std::move(on_access_token_invalidated_callback_).Run();
}
}
CoreAccountId expected_account_id_to_invalidate_;
std::set<std::string> expected_scopes_to_invalidate_;
std::string expected_access_token_to_invalidate_;
base::OnceClosure on_access_token_invalidated_callback_;
};
// Subclass of FakeProfileOAuth2TokenService with bespoke behavior.
class CustomFakeProfileOAuth2TokenService
: public FakeProfileOAuth2TokenService {
public:
explicit CustomFakeProfileOAuth2TokenService(PrefService* user_prefs)
: FakeProfileOAuth2TokenService(user_prefs) {
OverrideAccessTokenManagerForTesting(
std::make_unique<CustomFakeOAuth2AccessTokenManager>(
this /* OAuth2AccessTokenManager::Delegate* */));
}
CustomFakeProfileOAuth2TokenService(
PrefService* user_prefs,
std::unique_ptr<ProfileOAuth2TokenServiceDelegate> delegate)
: FakeProfileOAuth2TokenService(user_prefs, std::move(delegate)) {
OverrideAccessTokenManagerForTesting(
std::make_unique<CustomFakeOAuth2AccessTokenManager>(
this /* OAuth2AccessTokenManager::Delegate* */));
}
void set_on_access_token_invalidated_info(
CoreAccountId expected_account_id_to_invalidate,
std::set<std::string> expected_scopes_to_invalidate,
std::string expected_access_token_to_invalidate,
base::OnceClosure callback) {
GetCustomAccessTokenManager()->set_on_access_token_invalidated_info(
expected_account_id_to_invalidate, expected_scopes_to_invalidate,
expected_access_token_to_invalidate, std::move(callback));
}
private:
CustomFakeOAuth2AccessTokenManager* GetCustomAccessTokenManager() {
return static_cast<CustomFakeOAuth2AccessTokenManager*>(
GetAccessTokenManager());
}
};
class TestIdentityManagerDiagnosticsObserver
: IdentityManager::DiagnosticsObserver {
public:
explicit TestIdentityManagerDiagnosticsObserver(
IdentityManager* identity_manager)
: identity_manager_(identity_manager) {
identity_manager_->AddDiagnosticsObserver(this);
}
~TestIdentityManagerDiagnosticsObserver() override {
identity_manager_->RemoveDiagnosticsObserver(this);
}
void set_on_access_token_requested_callback(base::OnceClosure callback) {
on_access_token_requested_callback_ = std::move(callback);
}
void set_on_access_token_request_completed_callback(
base::OnceClosure callback) {
on_access_token_request_completed_callback_ = std::move(callback);
}
const CoreAccountId& token_requestor_account_id() {
return token_requestor_account_id_;
}
const std::string& token_requestor_consumer_id() {
return token_requestor_consumer_id_;
}
const ScopeSet& token_requestor_scopes() { return token_requestor_scopes_; }
const CoreAccountId& token_remover_account_id() {
return token_remover_account_id_;
}
const ScopeSet& token_remover_scopes() { return token_remover_scopes_; }
const CoreAccountId& on_access_token_request_completed_account_id() {
return access_token_request_completed_account_id_;
}
const std::string& on_access_token_request_completed_consumer_id() {
return access_token_request_completed_consumer_id_;
}
const ScopeSet& on_access_token_request_completed_scopes() {
return access_token_request_completed_scopes_;
}
const GoogleServiceAuthError& on_access_token_request_completed_error() {
return access_token_request_completed_error_;
}
private:
// IdentityManager::DiagnosticsObserver:
void OnAccessTokenRequested(const CoreAccountId& account_id,
const std::string& consumer_id,
const ScopeSet& scopes) override {
token_requestor_account_id_ = account_id;
token_requestor_consumer_id_ = consumer_id;
token_requestor_scopes_ = scopes;
if (on_access_token_requested_callback_)
std::move(on_access_token_requested_callback_).Run();
}
void OnAccessTokenRemovedFromCache(const CoreAccountId& account_id,
const ScopeSet& scopes) override {
token_remover_account_id_ = account_id;
token_remover_scopes_ = scopes;
}
void OnAccessTokenRequestCompleted(const CoreAccountId& account_id,
const std::string& consumer_id,
const ScopeSet& scopes,
GoogleServiceAuthError error,
base::Time expiration_time) override {
access_token_request_completed_account_id_ = account_id;
access_token_request_completed_consumer_id_ = consumer_id;
access_token_request_completed_scopes_ = scopes;
access_token_request_completed_error_ = error;
if (on_access_token_request_completed_callback_)
std::move(on_access_token_request_completed_callback_).Run();
}
IdentityManager* identity_manager_;
base::OnceClosure on_access_token_requested_callback_;
base::OnceClosure on_access_token_request_completed_callback_;
CoreAccountId token_requestor_account_id_;
std::string token_requestor_consumer_id_;
CoreAccountId token_remover_account_id_;
ScopeSet token_requestor_scopes_;
ScopeSet token_remover_scopes_;
CoreAccountId access_token_request_completed_account_id_;
std::string access_token_request_completed_consumer_id_;
ScopeSet access_token_request_completed_scopes_;
GoogleServiceAuthError access_token_request_completed_error_;
};
} // namespace
class IdentityManagerTest : public testing::Test {
public:
IdentityManagerTest(const IdentityManagerTest&) = delete;
IdentityManagerTest& operator=(const IdentityManagerTest&) = delete;
protected:
IdentityManagerTest()
: signin_client_(&pref_service_, &test_url_loader_factory_) {
IdentityManager::RegisterProfilePrefs(pref_service_.registry());
IdentityManager::RegisterLocalStatePrefs(pref_service_.registry());
RecreateIdentityManager(
AccountConsistencyMethod::kDisabled,
PrimaryAccountManagerSetup::kWithAuthenticatedAccout);
primary_account_id_ =
identity_manager_->PickAccountIdForAccount(kTestGaiaId, kTestEmail);
}
~IdentityManagerTest() override {
identity_manager_->Shutdown();
signin_client_.Shutdown();
}
IdentityManager* identity_manager() { return identity_manager_.get(); }
TestIdentityManagerObserver* identity_manager_observer() {
return identity_manager_observer_.get();
}
TestIdentityManagerDiagnosticsObserver*
identity_manager_diagnostics_observer() {
return identity_manager_diagnostics_observer_.get();
}
AccountTrackerService* account_tracker() {
return identity_manager()->GetAccountTrackerService();
}
CustomFakeProfileOAuth2TokenService* token_service() {
return static_cast<CustomFakeProfileOAuth2TokenService*>(
identity_manager()->GetTokenService());
}
// See RecreateIdentityManager.
enum class PrimaryAccountManagerSetup {
kWithAuthenticatedAccout,
kNoAuthenticatedAccount
};
// Used by some tests that need to re-instantiate IdentityManager after
// performing some other setup.
void RecreateIdentityManager() {
RecreateIdentityManager(
AccountConsistencyMethod::kDisabled,
PrimaryAccountManagerSetup::kNoAuthenticatedAccount);
}
// Recreates IdentityManager with given |account_consistency| and optionally
// seeds with an authenticated account depending on
// |primary_account_manager_setup|. This process destroys any existing
// IdentityManager and its dependencies, then remakes them. Dependencies that
// outlive PrimaryAccountManager (e.g. SigninClient) will be reused.
void RecreateIdentityManager(
AccountConsistencyMethod account_consistency,
PrimaryAccountManagerSetup primary_account_manager_setup) {
// Remove observers first, otherwise IdentityManager destruction might
// trigger a DCHECK because there are still living observers.
identity_manager_observer_.reset();
identity_manager_diagnostics_observer_.reset();
if (identity_manager_)
identity_manager_->Shutdown();
identity_manager_.reset();
if (temp_profile_dir_.IsValid()) {
// We are actually re-creating everything. Delete the previously used
// directory.
ASSERT_TRUE(temp_profile_dir_.Delete());
}
ASSERT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
auto account_tracker_service = std::make_unique<AccountTrackerService>();
account_tracker_service->Initialize(&pref_service_,
temp_profile_dir_.GetPath());
#if BUILDFLAG(IS_CHROMEOS_ASH)
account_manager::AccountManager::RegisterPrefs(pref_service_.registry());
auto* ash_account_manager = GetAccountManagerFactory()->GetAccountManager(
temp_profile_dir_.GetPath().value());
ash_account_manager->InitializeInEphemeralMode(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_));
ash_account_manager->SetPrefService(&pref_service_);
auto* ash_account_manager_mojo_service =
GetAccountManagerFactory()->GetAccountManagerMojoService(
temp_profile_dir_.GetPath().value());
auto token_service = std::make_unique<CustomFakeProfileOAuth2TokenService>(
&pref_service_,
std::make_unique<TestProfileOAuth2TokenServiceDelegateChromeOS>(
account_tracker_service.get(), ash_account_manager_mojo_service,
/*is_regular_profile=*/true));
#else
auto token_service =
std::make_unique<CustomFakeProfileOAuth2TokenService>(&pref_service_);
#endif
auto gaia_cookie_manager_service =
std::make_unique<GaiaCookieManagerService>(token_service.get(),
&signin_client_);
auto account_fetcher_service = std::make_unique<AccountFetcherService>();
account_fetcher_service->Initialize(
&signin_client_, token_service.get(), account_tracker_service.get(),
std::make_unique<image_fetcher::FakeImageDecoder>());
DCHECK_EQ(account_consistency, AccountConsistencyMethod::kDisabled)
<< "AccountConsistency is not used by PrimaryAccountManager";
std::unique_ptr<PrimaryAccountPolicyManager> policy_manager;
#if !BUILDFLAG(IS_CHROMEOS_ASH)
policy_manager =
std::make_unique<PrimaryAccountPolicyManagerImpl>(&signin_client_);
#endif
auto primary_account_manager = std::make_unique<PrimaryAccountManager>(
&signin_client_, token_service.get(), account_tracker_service.get(),
std::move(policy_manager));
// Passing this switch ensures that the new PrimaryAccountManager starts
// with a clean slate. Otherwise PrimaryAccountManager::Initialize will use
// the account id stored in prefs::kGoogleServicesAccountId.
base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
cmd_line->AppendSwitch(switches::kClearTokenService);
primary_account_manager->Initialize(&pref_service_);
if (primary_account_manager_setup ==
PrimaryAccountManagerSetup::kWithAuthenticatedAccout) {
CoreAccountId account_id =
account_tracker_service->SeedAccountInfo(kTestGaiaId, kTestEmail);
primary_account_manager->SetSyncPrimaryAccountInfo(
account_tracker_service->GetAccountInfo(account_id));
}
IdentityManager::InitParameters init_params;
init_params.accounts_cookie_mutator =
std::make_unique<AccountsCookieMutatorImpl>(
&signin_client_, token_service.get(),
gaia_cookie_manager_service.get(), account_tracker_service.get());
init_params.diagnostics_provider =
std::make_unique<DiagnosticsProviderImpl>(
token_service.get(), gaia_cookie_manager_service.get());
init_params.primary_account_mutator =
std::make_unique<PrimaryAccountMutatorImpl>(
account_tracker_service.get(), token_service.get(),
primary_account_manager.get(), &pref_service_, account_consistency);
#if defined(OS_ANDROID) || defined(OS_IOS)
init_params.device_accounts_synchronizer =
std::make_unique<DeviceAccountsSynchronizerImpl>(
token_service->GetDelegate());
#else
init_params.accounts_mutator = std::make_unique<AccountsMutatorImpl>(
token_service.get(), account_tracker_service.get(),
primary_account_manager.get(), &pref_service_);
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
init_params.ash_account_manager = ash_account_manager;
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
init_params.signin_client = &signin_client_;
#endif
init_params.account_fetcher_service = std::move(account_fetcher_service);
init_params.account_tracker_service = std::move(account_tracker_service);
init_params.gaia_cookie_manager_service =
std::move(gaia_cookie_manager_service);
init_params.primary_account_manager = std::move(primary_account_manager);
init_params.token_service = std::move(token_service);
identity_manager_ =
std::make_unique<IdentityManager>(std::move(init_params));
identity_manager_observer_ =
std::make_unique<TestIdentityManagerObserver>(identity_manager_.get());
identity_manager_diagnostics_observer_ =
std::make_unique<TestIdentityManagerDiagnosticsObserver>(
identity_manager_.get());
// CustomFakeProfileOAuth2TokenService loads credentials immediately, so
// several tests (for example, `AreRefreshTokensLoaded`) expect this
// behavior from all platforms, even from ones where tokens are loaded
// asynchronously (e.g., ChromeOS). Wait for loading to finish to meet these
// expectations.
// TODO(https://crbug.com/1195170): Move waiting to tests that need it.
signin::WaitForRefreshTokensLoaded(identity_manager());
}
void SimulateAdditionOfAccountToCookieSuccess(GaiaAuthConsumer* consumer,
const std::string& data) {
consumer->OnMergeSessionSuccess(data);
}
void SimulateAdditionOfAccountToCookieSuccessFailure(
GaiaAuthConsumer* consumer,
const GoogleServiceAuthError& error) {
consumer->OnMergeSessionFailure(error);
}
void SimulateCookieDeletedByUser(
network::mojom::CookieChangeListener* listener,
const net::CanonicalCookie& cookie) {
listener->OnCookieChange(net::CookieChangeInfo(
cookie, net::CookieAccessResult(), net::CookieChangeCause::EXPLICIT));
}
void SimulateOAuthMultiloginFinished(GaiaCookieManagerService* manager,
SetAccountsInCookieResult error) {
manager->OnSetAccountsFinished(error);
}
const CoreAccountId& primary_account_id() const {
return primary_account_id_;
}
TestSigninClient* signin_client() { return &signin_client_; }
network::TestURLLoaderFactory* test_url_loader_factory() {
return &test_url_loader_factory_;
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
ash::AccountManagerFactory* GetAccountManagerFactory() {
return &account_manager_factory_;
}
#endif
private:
base::ScopedTempDir temp_profile_dir_;
base::test::TaskEnvironment task_environment_;
#if BUILDFLAG(IS_CHROMEOS_ASH)
ash::AccountManagerFactory account_manager_factory_;
#endif
sync_preferences::TestingPrefServiceSyncable pref_service_;
network::TestURLLoaderFactory test_url_loader_factory_;
TestSigninClient signin_client_;
std::unique_ptr<IdentityManager> identity_manager_;
std::unique_ptr<TestIdentityManagerObserver> identity_manager_observer_;
std::unique_ptr<TestIdentityManagerDiagnosticsObserver>
identity_manager_diagnostics_observer_;
CoreAccountId primary_account_id_;
};
// Test that IdentityManager's constructor properly sets all passed parameters.
TEST_F(IdentityManagerTest, Construct) {
EXPECT_NE(identity_manager()->GetAccountTrackerService(), nullptr);
EXPECT_NE(identity_manager()->GetTokenService(), nullptr);
EXPECT_NE(identity_manager()->GetGaiaCookieManagerService(), nullptr);
EXPECT_NE(identity_manager()->GetPrimaryAccountManager(), nullptr);
EXPECT_NE(identity_manager()->GetAccountFetcherService(), nullptr);
EXPECT_NE(identity_manager()->GetPrimaryAccountMutator(), nullptr);
EXPECT_NE(identity_manager()->GetAccountsCookieMutator(), nullptr);
EXPECT_NE(identity_manager()->GetDiagnosticsProvider(), nullptr);
#if defined(OS_ANDROID) || defined(OS_IOS)
EXPECT_EQ(identity_manager()->GetAccountsMutator(), nullptr);
EXPECT_NE(identity_manager()->GetDeviceAccountsSynchronizer(), nullptr);
#else
EXPECT_NE(identity_manager()->GetAccountsMutator(), nullptr);
EXPECT_EQ(identity_manager()->GetDeviceAccountsSynchronizer(), nullptr);
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
EXPECT_NE(identity_manager()->GetAshAccountManager(), nullptr);
#endif
}
// Test that IdentityManager starts off with the information in
// PrimaryAccountManager.
TEST_F(IdentityManagerTest, PrimaryAccountInfoAtStartup) {
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
EXPECT_EQ(kTestGaiaId, primary_account_info.gaia);
EXPECT_EQ(kTestEmail, primary_account_info.email);
// Primary account is by definition also unconsented primary account.
EXPECT_EQ(primary_account_info,
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin));
// There is no guarantee that this will be notified via callback on startup.
}
// Signin/signout tests aren't relevant and cannot build on ChromeOS, which
// doesn't support signin/signout.
#if !BUILDFLAG(IS_CHROMEOS_ASH)
// Test that the user signing in results in firing of the IdentityManager
// observer callback and the IdentityManager's state being updated.
TEST_F(IdentityManagerTest, PrimaryAccountInfoAfterSignin) {
ClearPrimaryAccount(identity_manager());
SetPrimaryAccount(identity_manager(), kTestEmail, ConsentLevel::kSync);
auto event = identity_manager_observer()->GetPrimaryAccountChangedEvent();
EXPECT_EQ(PrimaryAccountChangeEvent::Type::kSet,
event.GetEventTypeFor(ConsentLevel::kSync));
EXPECT_EQ(PrimaryAccountChangeEvent::Type::kSet,
event.GetEventTypeFor(ConsentLevel::kSignin));
CoreAccountInfo primary_account_from_set_callback =
event.GetCurrentState().primary_account;
EXPECT_EQ(kTestGaiaId, primary_account_from_set_callback.gaia);
EXPECT_EQ(kTestEmail, primary_account_from_set_callback.email);
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
EXPECT_EQ(kTestGaiaId, primary_account_info.gaia);
EXPECT_EQ(kTestEmail, primary_account_info.email);
// Primary account is by definition also unconsented primary account.
EXPECT_EQ(primary_account_info,
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin));
CoreAccountId primary_account_id =
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync);
EXPECT_EQ(primary_account_id, CoreAccountId(kTestGaiaId));
EXPECT_EQ(primary_account_id, primary_account_info.account_id);
EXPECT_EQ(primary_account_id, identity_manager()->GetPrimaryAccountId(
signin::ConsentLevel::kSignin));
}
// Test that the user signing out results in firing of the IdentityManager
// observer callback and the IdentityManager's state being updated.
TEST_F(IdentityManagerTest, PrimaryAccountInfoAfterSigninAndSignout) {
ClearPrimaryAccount(identity_manager());
// First ensure that the user is signed in from the POV of the
// IdentityManager.
SetPrimaryAccount(identity_manager(), kTestEmail, ConsentLevel::kSync);
// Sign the user out and check that the IdentityManager responds
// appropriately.
ClearPrimaryAccount(identity_manager());
auto event = identity_manager_observer()->GetPrimaryAccountChangedEvent();
EXPECT_EQ(PrimaryAccountChangeEvent::Type::kCleared,
event.GetEventTypeFor(ConsentLevel::kSync));
EXPECT_EQ(PrimaryAccountChangeEvent::Type::kCleared,
event.GetEventTypeFor(ConsentLevel::kSignin));
CoreAccountInfo primary_account_from_cleared_callback =
event.GetPreviousState().primary_account;
EXPECT_EQ(kTestGaiaId, primary_account_from_cleared_callback.gaia);
EXPECT_EQ(kTestEmail, primary_account_from_cleared_callback.email);
// After the sign-out, there is no unconsented primary account.
EXPECT_TRUE(identity_manager()
->GetPrimaryAccountInfo(ConsentLevel::kSignin)
.IsEmpty());
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
EXPECT_EQ("", primary_account_info.gaia);
EXPECT_EQ("", primary_account_info.email);
EXPECT_EQ(primary_account_info,
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin));
CoreAccountId primary_account_id =
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync);
EXPECT_TRUE(primary_account_id.empty());
EXPECT_EQ(primary_account_id, primary_account_info.account_id);
EXPECT_EQ(primary_account_id, identity_manager()->GetPrimaryAccountId(
signin::ConsentLevel::kSignin));
}
// Test that the primary account's core info remains tracked by the
// IdentityManager after signing in even after having removed the refresh token
// without signing out.
TEST_F(IdentityManagerTest,
PrimaryAccountInfoAfterSigninAndRefreshTokenRemoval) {
ClearPrimaryAccount(identity_manager());
// First ensure that the user is signed in from the POV of the
// IdentityManager.
SetPrimaryAccount(identity_manager(), kTestEmail, ConsentLevel::kSync);
identity_manager()->account_fetcher_service_->EnableAccountRemovalForTest();
// Revoke the primary's account credentials from the token service and
// check that the returned CoreAccountInfo is still valid since the
// identity_manager stores it.
token_service()->RevokeCredentials(
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync));
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
EXPECT_EQ(kTestGaiaId, primary_account_info.gaia);
EXPECT_EQ(kTestEmail, primary_account_info.email);
EXPECT_EQ(CoreAccountId(kTestGaiaId), primary_account_info.account_id);
EXPECT_EQ(primary_account_info,
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin));
CoreAccountId primary_account_id =
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync);
EXPECT_EQ(primary_account_id, CoreAccountId(kTestGaiaId));
EXPECT_EQ(primary_account_id,
identity_manager()->GetPrimaryAccountId(ConsentLevel::kSignin));
}
#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(IdentityManagerTest, HasPrimaryAccount) {
EXPECT_TRUE(
identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
// Removing the account from the AccountTrackerService should not cause
// IdentityManager to think that there is no longer a primary account.
account_tracker()->RemoveAccount(
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync));
EXPECT_TRUE(
identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
#if !BUILDFLAG(IS_CHROMEOS_ASH)
// Signing out should cause IdentityManager to recognize that there is no
// longer a primary account.
ClearPrimaryAccount(identity_manager());
EXPECT_FALSE(
identity_manager()->HasPrimaryAccount(signin::ConsentLevel::kSync));
EXPECT_FALSE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
EXPECT_FALSE(identity_manager_observer()
->GetPrimaryAccountChangedEvent()
.GetPreviousState()
.primary_account.IsEmpty());
#endif
}
TEST_F(IdentityManagerTest, GetAccountsInteractionWithPrimaryAccount) {
// Should not have any refresh tokens at initialization.
EXPECT_TRUE(identity_manager()->GetAccountsWithRefreshTokens().empty());
// Add a refresh token for the primary account and check that it shows up in
// GetAccountsWithRefreshTokens().
SetRefreshTokenForPrimaryAccount(identity_manager());
std::vector<CoreAccountInfo> accounts_after_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(1u, accounts_after_update.size());
EXPECT_EQ(accounts_after_update[0].account_id, primary_account_id());
EXPECT_EQ(accounts_after_update[0].gaia, kTestGaiaId);
EXPECT_EQ(accounts_after_update[0].email, kTestEmail);
// Update the token and check that it doesn't change the state (or blow up).
SetRefreshTokenForPrimaryAccount(identity_manager());
std::vector<CoreAccountInfo> accounts_after_second_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(1u, accounts_after_second_update.size());
EXPECT_EQ(accounts_after_second_update[0].account_id, primary_account_id());
EXPECT_EQ(accounts_after_second_update[0].gaia, kTestGaiaId);
EXPECT_EQ(accounts_after_second_update[0].email, kTestEmail);
// Remove the token for the primary account and check that this is likewise
// reflected.
RemoveRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_TRUE(identity_manager()->GetAccountsWithRefreshTokens().empty());
}
TEST_F(IdentityManagerTest,
QueryingOfRefreshTokensInteractionWithPrimaryAccount) {
CoreAccountInfo account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
// Should not have a refresh token for the primary account at initialization.
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info.account_id));
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Add a refresh token for the primary account and check that it affects this
// state.
SetRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info.account_id));
EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Update the token and check that it doesn't change the state (or blow up).
SetRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info.account_id));
EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Remove the token for the primary account and check that this is likewise
// reflected.
RemoveRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info.account_id));
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
}
TEST_F(IdentityManagerTest, QueryingOfRefreshTokensReflectsEmptyInitialState) {
CoreAccountInfo account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
CoreAccountId account_id = account_info.account_id;
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info.account_id));
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
SetRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info.account_id));
EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
}
TEST_F(IdentityManagerTest, GetAccountsInteractionWithSecondaryAccounts) {
// Should not have any refresh tokens at initialization.
EXPECT_TRUE(identity_manager()->GetAccountsWithRefreshTokens().empty());
// Add a refresh token for a secondary account and check that it shows up in
// GetAccountsWithRefreshTokens().
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
CoreAccountId account_id2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2);
std::vector<CoreAccountInfo> accounts_after_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(1u, accounts_after_update.size());
EXPECT_EQ(accounts_after_update[0].account_id, account_id2);
EXPECT_EQ(accounts_after_update[0].gaia, kTestGaiaId2);
EXPECT_EQ(accounts_after_update[0].email, kTestEmail2);
// Add a refresh token for a different secondary account and check that it
// also shows up in GetAccountsWithRefreshTokens().
account_tracker()->SeedAccountInfo(kTestGaiaId3, kTestEmail3);
CoreAccountId account_id3 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId3).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id3);
std::vector<CoreAccountInfo> accounts_after_second_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(2u, accounts_after_second_update.size());
for (CoreAccountInfo account_info : accounts_after_second_update) {
if (account_info.account_id == account_id2) {
EXPECT_EQ(account_info.gaia, kTestGaiaId2);
EXPECT_EQ(account_info.email, kTestEmail2);
} else {
EXPECT_EQ(account_info.gaia, kTestGaiaId3);
EXPECT_EQ(account_info.email, kTestEmail3);
}
}
// Remove the token for account2 and check that account3 is still present.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
std::vector<CoreAccountInfo> accounts_after_third_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(1u, accounts_after_third_update.size());
EXPECT_EQ(accounts_after_third_update[0].account_id, account_id3);
EXPECT_EQ(accounts_after_third_update[0].gaia, kTestGaiaId3);
EXPECT_EQ(accounts_after_third_update[0].email, kTestEmail3);
}
TEST_F(IdentityManagerTest,
HasPrimaryAccountWithRefreshTokenInteractionWithSecondaryAccounts) {
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Adding a refresh token for a secondary account shouldn't change anything
// about the primary account
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
CoreAccountId account_id2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Adding a refresh token for a different secondary account should not do so
// either.
account_tracker()->SeedAccountInfo(kTestGaiaId3, kTestEmail3);
CoreAccountId account_id3 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId3).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id3);
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Removing the token for account2 should have no effect.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
}
TEST_F(IdentityManagerTest,
HasAccountWithRefreshTokenInteractionWithSecondaryAccounts) {
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
AccountInfo account_info2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2);
CoreAccountId account_id2 = account_info2.account_id;
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
// Add a refresh token for account_info2 and check that this is reflected by
// HasAccountWithRefreshToken(.account_id).
SetRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
// Go through the same process for a different secondary account.
account_tracker()->SeedAccountInfo(kTestGaiaId3, kTestEmail3);
AccountInfo account_info3 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId3);
CoreAccountId account_id3 = account_info3.account_id;
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info3.account_id));
SetRefreshTokenForAccount(identity_manager(), account_id3);
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info3.account_id));
// Remove the token for account2.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info3.account_id));
}
TEST_F(IdentityManagerTest,
GetAccountsInteractionBetweenPrimaryAndSecondaryAccounts) {
// Should not have any refresh tokens at initialization.
EXPECT_TRUE(identity_manager()->GetAccountsWithRefreshTokens().empty());
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// Add a refresh token for a secondary account and check that it shows up in
// GetAccountsWithRefreshTokens().
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
CoreAccountId account_id2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2);
std::vector<CoreAccountInfo> accounts_after_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(1u, accounts_after_update.size());
EXPECT_EQ(accounts_after_update[0].account_id, account_id2);
EXPECT_EQ(accounts_after_update[0].gaia, kTestGaiaId2);
EXPECT_EQ(accounts_after_update[0].email, kTestEmail2);
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// The user still has a primary account.
EXPECT_EQ(identity_manager()
->GetPrimaryAccountInfo(signin::ConsentLevel::kSync)
.email,
kTestEmail);
EXPECT_EQ(
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin).email,
kTestEmail);
// Add a refresh token for the primary account and check that it
// also shows up in GetAccountsWithRefreshTokens().
SetRefreshTokenForPrimaryAccount(identity_manager());
std::vector<CoreAccountInfo> accounts_after_second_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(2u, accounts_after_second_update.size());
for (const CoreAccountInfo& account_info : accounts_after_second_update) {
if (account_info.account_id == account_id2) {
EXPECT_EQ(account_info.gaia, kTestGaiaId2);
EXPECT_EQ(account_info.email, kTestEmail2);
} else {
EXPECT_EQ(account_info.gaia, kTestGaiaId);
EXPECT_EQ(account_info.email, kTestEmail);
}
}
EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
EXPECT_EQ(identity_manager()
->GetPrimaryAccountInfo(signin::ConsentLevel::kSync)
.email,
kTestEmail);
EXPECT_EQ(
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin).email,
kTestEmail);
// Remove the token for the primary account and check that account2 is still
// present.
RemoveRefreshTokenForPrimaryAccount(identity_manager());
std::vector<CoreAccountInfo> accounts_after_third_update =
identity_manager()->GetAccountsWithRefreshTokens();
EXPECT_EQ(1u, accounts_after_third_update.size());
EXPECT_EQ(accounts_after_update[0].account_id, account_id2);
EXPECT_EQ(accounts_after_update[0].gaia, kTestGaiaId2);
EXPECT_EQ(accounts_after_update[0].email, kTestEmail2);
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
// The user still has a primary account.
EXPECT_EQ(identity_manager()
->GetPrimaryAccountInfo(signin::ConsentLevel::kSync)
.email,
kTestEmail);
EXPECT_EQ(
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin).email,
kTestEmail);
}
TEST_F(
IdentityManagerTest,
HasPrimaryAccountWithRefreshTokenInteractionBetweenPrimaryAndSecondaryAccounts) {
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
// Add a refresh token for a secondary account and check that it doesn't
// impact the above state.
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
CoreAccountId account_id2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
// Add a refresh token for the primary account and check that it
// *does* impact the stsate of
// HasPrimaryAccountWithRefreshToken(signin::ConsentLevel::kSync).
SetRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
// Remove the token for the secondary account and check that this doesn't flip
// the state.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
// Remove the token for the primary account and check that this flips the
// state.
RemoveRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
signin::ConsentLevel::kSync));
EXPECT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
}
TEST_F(
IdentityManagerTest,
HasAccountWithRefreshTokenInteractionBetweenPrimaryAndSecondaryAccounts) {
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
CoreAccountId primary_account_id = primary_account_info.account_id;
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
AccountInfo account_info2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2);
CoreAccountId account_id2 = account_info2.account_id;
EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken(
primary_account_info.account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
// Add a refresh token for account_info2 and check that this is reflected by
// HasAccountWithRefreshToken(.account_id).
SetRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken(
primary_account_info.account_id));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
// Go through the same process for the primary account.
SetRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken(
primary_account_info.account_id));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
// Remove the token for account2.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken(
primary_account_info.account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshToken(account_info2.account_id));
}
TEST_F(IdentityManagerTest,
CallbackSentOnUpdateToErrorStateOfRefreshTokenForAccount) {
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
CoreAccountId primary_account_id = primary_account_info.account_id;
SetRefreshTokenForPrimaryAccount(identity_manager());
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
AccountInfo account_info2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2);
CoreAccountId account_id2 = account_info2.account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2);
GoogleServiceAuthError user_not_signed_up_error =
GoogleServiceAuthError(GoogleServiceAuthError::State::USER_NOT_SIGNED_UP);
GoogleServiceAuthError invalid_gaia_credentials_error =
GoogleServiceAuthError(
GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS);
GoogleServiceAuthError transient_error = GoogleServiceAuthError(
GoogleServiceAuthError::State::SERVICE_UNAVAILABLE);
// Set a persistent error for |account_id2| and check that it's reflected.
token_service()->UpdateAuthErrorForTesting(account_id2,
user_not_signed_up_error);
EXPECT_EQ(account_id2,
identity_manager_observer()
->AccountFromErrorStateOfRefreshTokenUpdatedCallback()
.account_id);
EXPECT_EQ(user_not_signed_up_error,
identity_manager_observer()
->ErrorFromErrorStateOfRefreshTokenUpdatedCallback());
// A transient error should not cause a callback.
token_service()->UpdateAuthErrorForTesting(primary_account_id,
transient_error);
EXPECT_EQ(account_id2,
identity_manager_observer()
->AccountFromErrorStateOfRefreshTokenUpdatedCallback()
.account_id);
EXPECT_EQ(user_not_signed_up_error,
identity_manager_observer()
->ErrorFromErrorStateOfRefreshTokenUpdatedCallback());
// Set a different persistent error for the primary account and check that
// it's reflected.
token_service()->UpdateAuthErrorForTesting(primary_account_id,
invalid_gaia_credentials_error);
EXPECT_EQ(primary_account_id,
identity_manager_observer()
->AccountFromErrorStateOfRefreshTokenUpdatedCallback()
.account_id);
EXPECT_EQ(invalid_gaia_credentials_error,
identity_manager_observer()
->ErrorFromErrorStateOfRefreshTokenUpdatedCallback());
}
TEST_F(IdentityManagerTest, GetErrorStateOfRefreshTokenForAccount) {
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
CoreAccountId primary_account_id = primary_account_info.account_id;
// A primary account without a refresh token should not be in an error
// state, and setting a refresh token should not affect that.
EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(
primary_account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account_id));
SetRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(
primary_account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account_id));
// A secondary account without a refresh token should not be in an error
// state, and setting a refresh token should not affect that.
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
AccountInfo account_info2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2);
CoreAccountId account_id2 = account_info2.account_id;
EXPECT_EQ(
GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(account_id2));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
account_id2));
SetRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_EQ(
GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(account_id2));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
account_id2));
GoogleServiceAuthError user_not_signed_up_error =
GoogleServiceAuthError(GoogleServiceAuthError::State::USER_NOT_SIGNED_UP);
GoogleServiceAuthError invalid_gaia_credentials_error =
GoogleServiceAuthError(
GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS);
GoogleServiceAuthError transient_error = GoogleServiceAuthError(
GoogleServiceAuthError::State::SERVICE_UNAVAILABLE);
// Set a persistent error for |account_id2| and check that it's reflected.
token_service()->UpdateAuthErrorForTesting(account_id2,
user_not_signed_up_error);
EXPECT_EQ(
user_not_signed_up_error,
identity_manager()->GetErrorStateOfRefreshTokenForAccount(account_id2));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
account_id2));
EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(
primary_account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account_id));
// A transient error should cause no change in the error state.
token_service()->UpdateAuthErrorForTesting(primary_account_id,
transient_error);
EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(
primary_account_id));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account_id));
// Set a different persistent error for the primary account and check that
// it's reflected.
token_service()->UpdateAuthErrorForTesting(primary_account_id,
invalid_gaia_credentials_error);
EXPECT_EQ(
user_not_signed_up_error,
identity_manager()->GetErrorStateOfRefreshTokenForAccount(account_id2));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
account_id2));
EXPECT_EQ(invalid_gaia_credentials_error,
identity_manager()->GetErrorStateOfRefreshTokenForAccount(
primary_account_id));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account_id));
// Remove the token for account2 and check that it goes back to having no
// error.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
EXPECT_EQ(
GoogleServiceAuthError::AuthErrorNone(),
identity_manager()->GetErrorStateOfRefreshTokenForAccount(account_id2));
EXPECT_FALSE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
account_id2));
EXPECT_EQ(invalid_gaia_credentials_error,
identity_manager()->GetErrorStateOfRefreshTokenForAccount(
primary_account_id));
EXPECT_TRUE(
identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
primary_account_id));
}
TEST_F(IdentityManagerTest, RemoveAccessTokenFromCache) {
std::set<std::string> scopes{"scope"};
std::string access_token = "access_token";
identity_manager()->GetAccountTrackerService()->SeedAccountInfo(kTestGaiaId,
kTestEmail);
identity_manager()->GetPrimaryAccountMutator()->SetPrimaryAccount(
primary_account_id(), ConsentLevel::kSync);
SetRefreshTokenForAccount(identity_manager(), primary_account_id(),
"refresh_token");
base::RunLoop run_loop;
token_service()->set_on_access_token_invalidated_info(
primary_account_id(), scopes, access_token, run_loop.QuitClosure());
identity_manager()->RemoveAccessTokenFromCache(primary_account_id(), scopes,
access_token);
run_loop.Run();
// RemoveAccessTokenFromCache should lead to OnAccessTokenRemovedFromCache
// from IdentityManager::DiagnosticsObserver.
EXPECT_EQ(
primary_account_id(),
identity_manager_diagnostics_observer()->token_remover_account_id());
EXPECT_EQ(scopes,
identity_manager_diagnostics_observer()->token_remover_scopes());
}
TEST_F(IdentityManagerTest, CreateAccessTokenFetcher) {
std::set<std::string> scopes{"scope"};
AccessTokenFetcher::TokenCallback callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
std::unique_ptr<AccessTokenFetcher> token_fetcher =
identity_manager()->CreateAccessTokenFetcherForAccount(
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync),
kTestConsumerId, scopes, std::move(callback),
AccessTokenFetcher::Mode::kImmediate);
EXPECT_TRUE(token_fetcher);
}
TEST_F(IdentityManagerTest,
CreateAccessTokenFetcherWithCustomURLLoaderFactory) {
base::RunLoop run_loop;
identity_manager_diagnostics_observer()
->set_on_access_token_requested_callback(run_loop.QuitClosure());
identity_manager()->GetAccountTrackerService()->SeedAccountInfo(kTestGaiaId,
kTestEmail);
identity_manager()->GetPrimaryAccountMutator()->SetPrimaryAccount(
primary_account_id(), ConsentLevel::kSync);
SetRefreshTokenForAccount(identity_manager(), primary_account_id(),
"refresh_token");
std::set<std::string> scopes{"scope"};
AccessTokenFetcher::TokenCallback callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
// We first create and AccessTokenFetcher with a custom URLLoaderFactory,
// to check that such factory is actually used in the requests generated.
network::TestURLLoaderFactory test_url_loader_factory;
scoped_refptr<network::SharedURLLoaderFactory> test_shared_url_loader_factory(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory));
std::unique_ptr<AccessTokenFetcher> token_fetcher =
identity_manager()->CreateAccessTokenFetcherForAccount(
primary_account_id(), kTestConsumerId, test_shared_url_loader_factory,
scopes, std::move(callback), AccessTokenFetcher::Mode::kImmediate);
run_loop.Run();
// The URLLoaderFactory present in the pending request should match
// the one we specified when creating the AccessTokenFetcher.
std::vector<FakeOAuth2AccessTokenManager::PendingRequest> pending_requests =
token_service()->GetPendingRequests();
EXPECT_EQ(pending_requests.size(), 1U);
EXPECT_EQ(pending_requests[0].url_loader_factory,
test_shared_url_loader_factory);
// The account ID and consumer's name should match the data passed as well.
EXPECT_EQ(
primary_account_id(),
identity_manager_diagnostics_observer()->token_requestor_account_id());
EXPECT_EQ(
kTestConsumerId,
identity_manager_diagnostics_observer()->token_requestor_consumer_id());
// Cancel the pending request in preparation to check that creating an
// AccessTokenFetcher without a custom factory works as expected as well.
token_service()->IssueErrorForAllPendingRequestsForAccount(
primary_account_id(),
GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
// Now add a second account and request an access token for it to test
// that the default URLLoaderFactory is used if none is specified.
base::RunLoop run_loop2;
identity_manager_diagnostics_observer()
->set_on_access_token_requested_callback(run_loop2.QuitClosure());
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
CoreAccountId account_id2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2, "refresh_token");
// No changes to the declared scopes, we can reuse it.
callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
std::unique_ptr<AccessTokenFetcher> token_fetcher2 =
identity_manager()->CreateAccessTokenFetcherForAccount(
account_id2, kTestConsumerId2, scopes, std::move(callback),
AccessTokenFetcher::Mode::kImmediate);
run_loop2.Run();
// There should be one pending request now as well, just like before.
std::vector<FakeOAuth2AccessTokenManager::PendingRequest> pending_requests2 =
token_service()->GetPendingRequests();
EXPECT_EQ(pending_requests2.size(), 1U);
// The URLLoaderFactory present in the pending request should match
// the one created by default for the token service's delegate.
ProfileOAuth2TokenServiceDelegate* service_delegate =
token_service()->GetDelegate();
EXPECT_EQ(pending_requests2[0].url_loader_factory,
service_delegate->GetURLLoaderFactory());
// The account ID and consumer's name should match the data passed again.
EXPECT_EQ(
account_id2,
identity_manager_diagnostics_observer()->token_requestor_account_id());
EXPECT_EQ(
kTestConsumerId2,
identity_manager_diagnostics_observer()->token_requestor_consumer_id());
}
TEST_F(IdentityManagerTest, ObserveAccessTokenFetch) {
base::RunLoop run_loop;
identity_manager_diagnostics_observer()
->set_on_access_token_requested_callback(run_loop.QuitClosure());
identity_manager()->GetAccountTrackerService()->SeedAccountInfo(kTestGaiaId,
kTestEmail);
identity_manager()->GetPrimaryAccountMutator()->SetPrimaryAccount(
primary_account_id(), ConsentLevel::kSync);
SetRefreshTokenForAccount(identity_manager(), primary_account_id(),
"refresh_token");
std::set<std::string> scopes{"scope"};
AccessTokenFetcher::TokenCallback callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
std::unique_ptr<AccessTokenFetcher> token_fetcher =
identity_manager()->CreateAccessTokenFetcherForAccount(
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync),
kTestConsumerId, scopes, std::move(callback),
AccessTokenFetcher::Mode::kImmediate);
run_loop.Run();
EXPECT_EQ(
primary_account_id(),
identity_manager_diagnostics_observer()->token_requestor_account_id());
EXPECT_EQ(
kTestConsumerId,
identity_manager_diagnostics_observer()->token_requestor_consumer_id());
EXPECT_EQ(scopes,
identity_manager_diagnostics_observer()->token_requestor_scopes());
}
TEST_F(IdentityManagerTest,
ObserveAccessTokenRequestCompletionWithoutRefreshToken) {
base::RunLoop run_loop;
identity_manager_diagnostics_observer()
->set_on_access_token_request_completed_callback(run_loop.QuitClosure());
std::set<std::string> scopes{"scope"};
AccessTokenFetcher::TokenCallback callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
// Account has no refresh token.
std::unique_ptr<AccessTokenFetcher> token_fetcher =
identity_manager()->CreateAccessTokenFetcherForAccount(
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync),
kTestConsumerId, scopes, std::move(callback),
AccessTokenFetcher::Mode::kImmediate);
run_loop.Run();
EXPECT_TRUE(token_fetcher);
EXPECT_EQ(GoogleServiceAuthError(GoogleServiceAuthError::USER_NOT_SIGNED_UP),
identity_manager_diagnostics_observer()
->on_access_token_request_completed_error());
}
TEST_F(IdentityManagerTest,
ObserveAccessTokenRequestCompletionWithRefreshToken) {
base::RunLoop run_loop;
identity_manager_diagnostics_observer()
->set_on_access_token_request_completed_callback(run_loop.QuitClosure());
identity_manager()->GetAccountTrackerService()->SeedAccountInfo(kTestGaiaId,
kTestEmail);
identity_manager()->GetPrimaryAccountMutator()->SetPrimaryAccount(
primary_account_id(), ConsentLevel::kSync);
SetRefreshTokenForAccount(identity_manager(), primary_account_id(),
"refresh_token");
token_service()->set_auto_post_fetch_response_on_message_loop(true);
std::set<std::string> scopes{"scope"};
AccessTokenFetcher::TokenCallback callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
// This should result in a request for an access token without an error.
std::unique_ptr<AccessTokenFetcher> token_fetcher =
identity_manager()->CreateAccessTokenFetcherForAccount(
identity_manager()->GetPrimaryAccountId(signin::ConsentLevel::kSync),
kTestConsumerId, scopes, std::move(callback),
AccessTokenFetcher::Mode::kImmediate);
run_loop.Run();
EXPECT_TRUE(token_fetcher);
EXPECT_EQ(primary_account_id(),
identity_manager_diagnostics_observer()
->on_access_token_request_completed_account_id());
EXPECT_EQ(kTestConsumerId,
identity_manager_diagnostics_observer()
->on_access_token_request_completed_consumer_id());
EXPECT_EQ(scopes, identity_manager_diagnostics_observer()
->on_access_token_request_completed_scopes());
EXPECT_EQ(GoogleServiceAuthError(GoogleServiceAuthError::NONE),
identity_manager_diagnostics_observer()
->on_access_token_request_completed_error());
}
TEST_F(IdentityManagerTest,
ObserveAccessTokenRequestCompletionAfterRevokingRefreshToken) {
base::RunLoop run_loop;
identity_manager_diagnostics_observer()
->set_on_access_token_request_completed_callback(run_loop.QuitClosure());
account_tracker()->SeedAccountInfo(kTestGaiaId2, kTestEmail2);
CoreAccountId account_id2 =
account_tracker()->FindAccountInfoByGaiaId(kTestGaiaId2).account_id;
SetRefreshTokenForAccount(identity_manager(), account_id2, "refresh_token");
std::set<std::string> scopes{"scope"};
AccessTokenFetcher::TokenCallback callback = base::BindOnce(
[](GoogleServiceAuthError error, AccessTokenInfo access_token_info) {});
// This should result in a request for an access token.
std::unique_ptr<AccessTokenFetcher> token_fetcher =
identity_manager()->CreateAccessTokenFetcherForAccount(
account_id2, kTestConsumerId2, scopes, std::move(callback),
AccessTokenFetcher::Mode::kImmediate);
// Revoke the refresh token result cancelling access token request.
RemoveRefreshTokenForAccount(identity_manager(), account_id2);
run_loop.Run();
EXPECT_TRUE(token_fetcher);
EXPECT_EQ(GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED),
identity_manager_diagnostics_observer()
->on_access_token_request_completed_error());
}
TEST_F(IdentityManagerTest, GetAccountsCookieMutator) {
AccountsCookieMutator* mutator =
identity_manager()->GetAccountsCookieMutator();
EXPECT_TRUE(mutator);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// On ChromeOS, AccountTrackerService first receives the normalized email
// address from GAIA and then later has it updated with the user's
// originally-specified version of their email address (at the time of that
// address' creation). This latter will differ if the user's originally-
// specified address was not in normalized form (e.g., if it contained
// periods). This test simulates such a flow in order to verify that
// IdentityManager correctly reflects the updated version. See crbug.com/842041
// and crbug.com/842670 for further details.
TEST_F(IdentityManagerTest, IdentityManagerReflectsUpdatedEmailAddress) {
CoreAccountInfo primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
EXPECT_EQ(kTestGaiaId, primary_account_info.gaia);
EXPECT_EQ(kTestEmail, primary_account_info.email);
// Simulate the flow wherein the user's email address was updated
// to the originally-created non-normalized version.
SimulateSuccessfulFetchOfAccountInfo(
identity_manager(), primary_account_info.account_id, kTestEmailWithPeriod,
kTestGaiaId, kTestHostedDomain, kTestFullName, kTestGivenName,
kTestLocale, kTestPictureUrl);
// Verify that IdentityManager reflects the update.
primary_account_info =
identity_manager()->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
EXPECT_EQ(kTestGaiaId, primary_account_info.gaia);
EXPECT_EQ(kTestEmailWithPeriod, primary_account_info.email);
EXPECT_EQ(identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin),
primary_account_info);
}
#endif
TEST_F(IdentityManagerTest,
CallbackSentOnPrimaryAccountRefreshTokenUpdateWithValidToken) {
SetRefreshTokenForPrimaryAccount(identity_manager());
CoreAccountInfo account_info =
identity_manager_observer()->AccountFromRefreshTokenUpdatedCallback();
EXPECT_EQ(kTestGaiaId, account_info.gaia);
EXPECT_EQ(kTestEmail, account_info.email);
}
TEST_F(IdentityManagerTest,
CallbackSentOnPrimaryAccountRefreshTokenUpdateWithInvalidToken) {
SetInvalidRefreshTokenForPrimaryAccount(identity_manager());
CoreAccountInfo account_info =
identity_manager_observer()->AccountFromRefreshTokenUpdatedCallback();
EXPECT_EQ(kTestGaiaId, account_info.gaia);
EXPECT_EQ(kTestEmail, account_info.email);
}
TEST_F(IdentityManagerTest, CallbackSentOnPrimaryAccountRefreshTokenRemoval) {
SetRefreshTokenForPrimaryAccount(identity_manager());
RemoveRefreshTokenForPrimaryAccount(identity_manager());
EXPECT_EQ(
primary_account_id(),
identity_manager_observer()->AccountIdFromRefreshTokenRemovedCallback());
}
TEST_F(IdentityManagerTest,
CallbackSentOnSecondaryAccountRefreshTokenUpdateWithValidToken) {
AccountInfo expected_account_info =
MakeAccountAvailable(identity_manager(), kTestEmail2);
EXPECT_EQ(kTestEmail2, expected_account_info.email);
CoreAccountInfo account_info =
identity_manager_observer()->AccountFromRefreshTokenUpdatedCallback();
EXPECT_EQ(expected_account_info.account_id, account_info.account_id);
EXPECT_EQ(expected_account_info.gaia, account_info.gaia);
EXPECT_EQ(expected_account_info.email, account_info.email);
}
TEST_F(IdentityManagerTest,
CallbackSentOnSecondaryAccountRefreshTokenUpdateWithInvalidToken) {
AccountInfo expected_account_info =
MakeAccountAvailable(identity_manager(), kTestEmail2);
EXPECT_EQ(kTestEmail2, expected_account_info.email);
SetInvalidRefreshTokenForAccount(identity_manager(),
expected_account_info.account_id);
CoreAccountInfo account_info =
identity_manager_observer()->AccountFromRefreshTokenUpdatedCallback();
EXPECT_EQ(expected_account_info.account_id, account_info.account_id);
EXPECT_EQ(expected_account_info.gaia, account_info.gaia);
EXPECT_EQ(expected_account_info.email, account_info.email);
}
TEST_F(IdentityManagerTest, CallbackSentOnSecondaryAccountRefreshTokenRemoval) {
AccountInfo expected_account_info =
MakeAccountAvailable(identity_manager(), kTestEmail2);
EXPECT_EQ(kTestEmail2, expected_account_info.email);
RemoveRefreshTokenForAccount(identity_manager(),
expected_account_info.account_id);
EXPECT_EQ(
expected_account_info.account_id,
identity_manager_observer()->AccountIdFromRefreshTokenRemovedCallback());
}
#if !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(
IdentityManagerTest,
CallbackSentOnSecondaryAccountRefreshTokenUpdateWithValidTokenWhenNoPrimaryAccount) {
ClearPrimaryAccount(identity_manager());
// Add an unconsented primary account, incl. proper cookies.
AccountInfo expected_account_info = MakeAccountAvailableWithCookies(
identity_manager(), test_url_loader_factory(), kTestEmail2, kTestGaiaId2);
EXPECT_EQ(kTestEmail2, expected_account_info.email);
CoreAccountInfo account_info =
identity_manager_observer()->AccountFromRefreshTokenUpdatedCallback();
EXPECT_EQ(expected_account_info.account_id, account_info.account_id);
EXPECT_EQ(expected_account_info.gaia, account_info.gaia);
EXPECT_EQ(expected_account_info.email, account_info.email);
}
TEST_F(
IdentityManagerTest,
CallbackSentOnSecondaryAccountRefreshTokenUpdateWithInvalidTokenWhenNoPrimaryAccount) {
ClearPrimaryAccount(identity_manager());
// Add an unconsented primary account, incl. proper cookies.
AccountInfo expected_account_info = MakeAccountAvailableWithCookies(
identity_manager(), test_url_loader_factory(), kTestEmail2, kTestGaiaId2);
EXPECT_EQ(kTestEmail2, expected_account_info.email);
SetInvalidRefreshTokenForAccount(identity_manager(),
expected_account_info.account_id);
CoreAccountInfo account_info =
identity_manager_observer()->AccountFromRefreshTokenUpdatedCallback();
EXPECT_EQ(expected_account_info.account_id, account_info.account_id);
EXPECT_EQ(expected_account_info.gaia, account_info.gaia);
EXPECT_EQ(expected_account_info.email, account_info.email);
}
TEST_F(IdentityManagerTest,
CallbackSentOnSecondaryAccountRefreshTokenRemovalWhenNoPrimaryAccount) {
ClearPrimaryAccount(identity_manager());
// Add an unconsented primary account, incl. proper cookies.
AccountInfo expected_account_info = MakeAccountAvailableWithCookies(
identity_manager(), test_url_loader_factory(), kTestEmail2, kTestGaiaId2);
EXPECT_EQ(kTestEmail2, expected_account_info.email);
RemoveRefreshTokenForAccount(identity_manager(),
expected_account_info.account_id);
EXPECT_EQ(
expected_account_info.account_id,
identity_manager_observer()->AccountIdFromRefreshTokenRemovedCallback());
}
TEST_F(IdentityManagerTest, CallbackSentOnRefreshTokenRemovalOfUnknownAccount) {
// When the token service is still loading credentials, it may send token
// revoked callbacks for accounts that it has never sent a token available
// callback. Our common test setup actually completes this loading, so use the
// *for_testing() method below to simulate the race condition and ensure that
// IdentityManager passes on the callback in this case.
token_service()->set_all_credentials_loaded_for_testing(false);
CoreAccountId dummy_account_id("dummy_account");
base::RunLoop run_loop;
token_service()->RevokeCredentials(dummy_account_id);
run_loop.RunUntilIdle();
EXPECT_EQ(
dummy_account_id,
identity_manager_observer()->AccountIdFromRefreshTokenRemovedCallback());
}
#endif
TEST_F(IdentityManagerTest, IdentityManagerGetsTokensLoadedEvent) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnRefreshTokensLoadedCallback(
run_loop.QuitClosure());
// Credentials are already loaded in PrimaryAccountManager::Initialize()
// which runs even before the IdentityManager is created. That's why
// we fake the credentials loaded state and force another load in
// order to be able to capture the TokensLoaded event.
token_service()->set_all_credentials_loaded_for_testing(false);
token_service()->LoadCredentials(CoreAccountId());
run_loop.Run();
}
TEST_F(IdentityManagerTest,
CallbackSentOnUpdateToAccountsInCookieWithNoAccounts) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseNoAccounts(test_url_loader_factory());
identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts();
run_loop.Run();
const AccountsInCookieJarInfo& accounts_in_cookie_jar_info =
identity_manager_observer()
->AccountsInfoFromAccountsInCookieUpdatedCallback();
EXPECT_TRUE(accounts_in_cookie_jar_info.accounts_are_fresh);
EXPECT_TRUE(accounts_in_cookie_jar_info.signed_in_accounts.empty());
}
TEST_F(IdentityManagerTest,
CallbackSentOnUpdateToAccountsInCookieWithOneAccount) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseOneAccount(kTestEmail, kTestGaiaId,
test_url_loader_factory());
identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts();
run_loop.Run();
const AccountsInCookieJarInfo& accounts_in_cookie_jar_info =
identity_manager_observer()
->AccountsInfoFromAccountsInCookieUpdatedCallback();
EXPECT_TRUE(accounts_in_cookie_jar_info.accounts_are_fresh);
ASSERT_EQ(1u, accounts_in_cookie_jar_info.signed_in_accounts.size());
ASSERT_TRUE(accounts_in_cookie_jar_info.signed_out_accounts.empty());
gaia::ListedAccount listed_account =
accounts_in_cookie_jar_info.signed_in_accounts[0];
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId, kTestEmail),
listed_account.id);
EXPECT_EQ(kTestGaiaId, listed_account.gaia_id);
EXPECT_EQ(kTestEmail, listed_account.email);
}
TEST_F(IdentityManagerTest,
CallbackSentOnUpdateToAccountsInCookieWithTwoAccounts) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseTwoAccounts(kTestEmail, kTestGaiaId, kTestEmail2,
kTestGaiaId2, test_url_loader_factory());
identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts();
run_loop.Run();
const AccountsInCookieJarInfo& accounts_in_cookie_jar_info =
identity_manager_observer()
->AccountsInfoFromAccountsInCookieUpdatedCallback();
EXPECT_TRUE(accounts_in_cookie_jar_info.accounts_are_fresh);
ASSERT_EQ(2u, accounts_in_cookie_jar_info.signed_in_accounts.size());
ASSERT_TRUE(accounts_in_cookie_jar_info.signed_out_accounts.empty());
// Verify not only that both accounts are present but that they are listed in
// the expected order as well.
gaia::ListedAccount listed_account1 =
accounts_in_cookie_jar_info.signed_in_accounts[0];
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId, kTestEmail),
listed_account1.id);
EXPECT_EQ(kTestGaiaId, listed_account1.gaia_id);
EXPECT_EQ(kTestEmail, listed_account1.email);
gaia::ListedAccount account_info2 =
accounts_in_cookie_jar_info.signed_in_accounts[1];
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId2, kTestEmail2),
account_info2.id);
EXPECT_EQ(kTestGaiaId2, account_info2.gaia_id);
EXPECT_EQ(kTestEmail2, account_info2.email);
}
TEST_F(IdentityManagerTest, CallbackSentOnUpdateToSignOutAccountsInCookie) {
struct SignedOutStatus {
bool account_1;
bool account_2;
} signed_out_status_set[] = {
{false, false}, {true, false}, {false, true}, {true, true}};
for (const auto& signed_out_status : signed_out_status_set) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseWithParams(
{{kTestEmail, kTestGaiaId, true /* valid */,
signed_out_status.account_1 /* signed_out */, true /* verified */},
{kTestEmail2, kTestGaiaId2, true /* valid */,
signed_out_status.account_2 /* signed_out */, true /* verified */}},
test_url_loader_factory());
identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts();
run_loop.Run();
size_t accounts_signed_out = size_t{signed_out_status.account_1} +
size_t{signed_out_status.account_2};
const AccountsInCookieJarInfo& accounts_in_cookie_jar_info =
identity_manager_observer()
->AccountsInfoFromAccountsInCookieUpdatedCallback();
EXPECT_TRUE(accounts_in_cookie_jar_info.accounts_are_fresh);
ASSERT_EQ(2 - accounts_signed_out,
accounts_in_cookie_jar_info.signed_in_accounts.size());
ASSERT_EQ(accounts_signed_out,
accounts_in_cookie_jar_info.signed_out_accounts.size());
// Verify not only that both accounts are present but that they are listed
// in the expected order as well.
//
// The two variables below, control the lookup indexes signed in and signed
// out accounts list, respectively.
int i = 0, j = 0;
gaia::ListedAccount listed_account1 =
signed_out_status.account_1
? accounts_in_cookie_jar_info.signed_out_accounts[i++]
: accounts_in_cookie_jar_info.signed_in_accounts[j++];
if (!signed_out_status.account_1)
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId, kTestEmail),
listed_account1.id);
EXPECT_EQ(kTestGaiaId, listed_account1.gaia_id);
EXPECT_EQ(kTestEmail, listed_account1.email);
gaia::ListedAccount listed_account2 =
signed_out_status.account_2
? accounts_in_cookie_jar_info.signed_out_accounts[i++]
: accounts_in_cookie_jar_info.signed_in_accounts[j++];
if (!signed_out_status.account_2)
EXPECT_EQ(identity_manager()->PickAccountIdForAccount(kTestGaiaId2,
kTestEmail2),
listed_account2.id);
EXPECT_EQ(kTestGaiaId2, listed_account2.gaia_id);
EXPECT_EQ(kTestEmail2, listed_account2.email);
}
}
TEST_F(IdentityManagerTest,
CallbackSentOnUpdateToAccountsInCookieWithStaleAccounts) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
// Configure list accounts to return a permanent Gaia auth error.
SetListAccountsResponseWithUnexpectedServiceResponse(
test_url_loader_factory());
identity_manager()->GetGaiaCookieManagerService()->TriggerListAccounts();
run_loop.Run();
const AccountsInCookieJarInfo& accounts_in_cookie_jar_info =
identity_manager_observer()
->AccountsInfoFromAccountsInCookieUpdatedCallback();
EXPECT_FALSE(accounts_in_cookie_jar_info.accounts_are_fresh);
EXPECT_TRUE(accounts_in_cookie_jar_info.signed_in_accounts.empty());
EXPECT_TRUE(accounts_in_cookie_jar_info.signed_out_accounts.empty());
}
TEST_F(IdentityManagerTest, GetAccountsInCookieJarWithNoAccounts) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseNoAccounts(test_url_loader_factory());
// Do an initial call to GetAccountsInCookieJar(). This call should return no
// accounts but should also trigger an internal update and eventual
// notification that the accounts in the cookie jar have been updated.
const AccountsInCookieJarInfo& accounts_in_cookie_jar =
identity_manager()->GetAccountsInCookieJar();
EXPECT_FALSE(accounts_in_cookie_jar.accounts_are_fresh);
EXPECT_TRUE(accounts_in_cookie_jar.signed_in_accounts.empty());
EXPECT_TRUE(accounts_in_cookie_jar.signed_out_accounts.empty());
run_loop.Run();
// The state of the accounts in IdentityManager should now reflect the
// internal update.
const AccountsInCookieJarInfo updated_accounts_in_cookie_jar =
identity_manager()->GetAccountsInCookieJar();
EXPECT_TRUE(updated_accounts_in_cookie_jar.accounts_are_fresh);
EXPECT_TRUE(updated_accounts_in_cookie_jar.signed_in_accounts.empty());
EXPECT_TRUE(updated_accounts_in_cookie_jar.signed_out_accounts.empty());
}
TEST_F(IdentityManagerTest, GetAccountsInCookieJarWithOneAccount) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseOneAccount(kTestEmail, kTestGaiaId,
test_url_loader_factory());
// Do an initial call to GetAccountsInCookieJar(). This call should return no
// accounts but should also trigger an internal update and eventual
// notification that the accounts in the cookie jar have been updated.
const AccountsInCookieJarInfo& accounts_in_cookie_jar =
identity_manager()->GetAccountsInCookieJar();
EXPECT_FALSE(accounts_in_cookie_jar.accounts_are_fresh);
EXPECT_TRUE(accounts_in_cookie_jar.signed_in_accounts.empty());
EXPECT_TRUE(accounts_in_cookie_jar.signed_out_accounts.empty());
run_loop.Run();
// The state of the accounts in IdentityManager should now reflect the
// internal update.
const AccountsInCookieJarInfo& updated_accounts_in_cookie_jar =
identity_manager()->GetAccountsInCookieJar();
EXPECT_TRUE(updated_accounts_in_cookie_jar.accounts_are_fresh);
ASSERT_EQ(1u, updated_accounts_in_cookie_jar.signed_in_accounts.size());
ASSERT_TRUE(updated_accounts_in_cookie_jar.signed_out_accounts.empty());
gaia::ListedAccount listed_account =
updated_accounts_in_cookie_jar.signed_in_accounts[0];
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId, kTestEmail),
listed_account.id);
EXPECT_EQ(kTestGaiaId, listed_account.gaia_id);
EXPECT_EQ(kTestEmail, listed_account.email);
}
TEST_F(IdentityManagerTest, GetAccountsInCookieJarWithTwoAccounts) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnAccountsInCookieUpdatedCallback(
run_loop.QuitClosure());
SetListAccountsResponseTwoAccounts(kTestEmail, kTestGaiaId, kTestEmail2,
kTestGaiaId2, test_url_loader_factory());
// Do an initial call to GetAccountsInCookieJar(). This call should return no
// accounts but should also trigger an internal update and eventual
// notification that the accounts in the cookie jar have been updated.
const AccountsInCookieJarInfo& accounts_in_cookie_jar =
identity_manager()->GetAccountsInCookieJar();
EXPECT_FALSE(accounts_in_cookie_jar.accounts_are_fresh);
EXPECT_TRUE(accounts_in_cookie_jar.signed_in_accounts.empty());
EXPECT_TRUE(accounts_in_cookie_jar.signed_out_accounts.empty());
run_loop.Run();
// The state of the accounts in IdentityManager should now reflect the
// internal update.
const AccountsInCookieJarInfo& updated_accounts_in_cookie_jar =
identity_manager()->GetAccountsInCookieJar();
EXPECT_TRUE(updated_accounts_in_cookie_jar.accounts_are_fresh);
ASSERT_EQ(2u, updated_accounts_in_cookie_jar.signed_in_accounts.size());
ASSERT_TRUE(updated_accounts_in_cookie_jar.signed_out_accounts.empty());
// Verify not only that both accounts are present but that they are listed in
// the expected order as well.
gaia::ListedAccount listed_account1 =
updated_accounts_in_cookie_jar.signed_in_accounts[0];
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId, kTestEmail),
listed_account1.id);
EXPECT_EQ(kTestGaiaId, listed_account1.gaia_id);
EXPECT_EQ(kTestEmail, listed_account1.email);
gaia::ListedAccount listed_account2 =
updated_accounts_in_cookie_jar.signed_in_accounts[1];
EXPECT_EQ(
identity_manager()->PickAccountIdForAccount(kTestGaiaId2, kTestEmail2),
listed_account2.id);
EXPECT_EQ(kTestGaiaId2, listed_account2.gaia_id);
EXPECT_EQ(kTestEmail2, listed_account2.email);
}
TEST_F(IdentityManagerTest, CallbackSentOnSuccessfulAdditionOfAccountToCookie) {
const CoreAccountId kTestAccountId("account_id");
CoreAccountId account_from_add_account_to_cookie_completed_callback;
GoogleServiceAuthError error_from_add_account_to_cookie_completed_callback;
auto completion_callback =
base::BindLambdaForTesting([&](const CoreAccountId& account_id,
const GoogleServiceAuthError& error) {
account_from_add_account_to_cookie_completed_callback = account_id;
error_from_add_account_to_cookie_completed_callback = error;
});
identity_manager()->GetGaiaCookieManagerService()->AddAccountToCookie(
kTestAccountId, gaia::GaiaSource::kChrome,
std::move(completion_callback));
SimulateAdditionOfAccountToCookieSuccess(
identity_manager()->GetGaiaCookieManagerService(), "token");
EXPECT_EQ(account_from_add_account_to_cookie_completed_callback,
kTestAccountId);
EXPECT_EQ(error_from_add_account_to_cookie_completed_callback,
GoogleServiceAuthError::AuthErrorNone());
}
TEST_F(IdentityManagerTest, CallbackSentOnFailureAdditionOfAccountToCookie) {
const CoreAccountId kTestAccountId("account_id");
CoreAccountId account_from_add_account_to_cookie_completed_callback;
GoogleServiceAuthError error_from_add_account_to_cookie_completed_callback;
auto completion_callback =
base::BindLambdaForTesting([&](const CoreAccountId& account_id,
const GoogleServiceAuthError& error) {
account_from_add_account_to_cookie_completed_callback = account_id;
error_from_add_account_to_cookie_completed_callback = error;
});
identity_manager()->GetGaiaCookieManagerService()->AddAccountToCookie(
kTestAccountId, gaia::GaiaSource::kChrome,
std::move(completion_callback));
GoogleServiceAuthError error(GoogleServiceAuthError::SERVICE_ERROR);
SimulateAdditionOfAccountToCookieSuccessFailure(
identity_manager()->GetGaiaCookieManagerService(), error);
EXPECT_EQ(account_from_add_account_to_cookie_completed_callback,
kTestAccountId);
EXPECT_EQ(error_from_add_account_to_cookie_completed_callback, error);
}
TEST_F(IdentityManagerTest,
CallbackSentOnSetAccountsInCookieCompleted_Success) {
const CoreAccountId kTestAccountId("account_id");
const CoreAccountId kTestAccountId2("account_id2");
const std::vector<std::pair<CoreAccountId, std::string>> accounts = {
{kTestAccountId, kTestAccountId.ToString()},
{kTestAccountId2, kTestAccountId2.ToString()}};
SetAccountsInCookieResult
error_from_set_accounts_in_cookie_completed_callback;
auto completion_callback = base::BindLambdaForTesting(
[&error_from_set_accounts_in_cookie_completed_callback](
SetAccountsInCookieResult error) {
error_from_set_accounts_in_cookie_completed_callback = error;
});
// Needed to insert request in the queue.
identity_manager()->GetGaiaCookieManagerService()->SetAccountsInCookie(
gaia::MultiloginMode::MULTILOGIN_UPDATE_COOKIE_ACCOUNTS_ORDER, accounts,
gaia::GaiaSource::kChrome, std::move(completion_callback));
SimulateOAuthMultiloginFinished(
identity_manager()->GetGaiaCookieManagerService(),
SetAccountsInCookieResult::kSuccess);
EXPECT_EQ(error_from_set_accounts_in_cookie_completed_callback,
SetAccountsInCookieResult::kSuccess);
}
TEST_F(IdentityManagerTest,
CallbackSentOnSetAccountsInCookieCompleted_Failure) {
const CoreAccountId kTestAccountId("account_id");
const CoreAccountId kTestAccountId2("account_id2");
const std::vector<std::pair<CoreAccountId, std::string>> accounts = {
{kTestAccountId, kTestAccountId.ToString()},
{kTestAccountId2, kTestAccountId2.ToString()}};
SetAccountsInCookieResult
error_from_set_accounts_in_cookie_completed_callback;
auto completion_callback = base::BindLambdaForTesting(
[&error_from_set_accounts_in_cookie_completed_callback](
SetAccountsInCookieResult error) {
error_from_set_accounts_in_cookie_completed_callback = error;
});
// Needed to insert request in the queue.
identity_manager()->GetGaiaCookieManagerService()->SetAccountsInCookie(
gaia::MultiloginMode::MULTILOGIN_UPDATE_COOKIE_ACCOUNTS_ORDER, accounts,
gaia::GaiaSource::kChrome, std::move(completion_callback));
// Sample an erroneous response.
SetAccountsInCookieResult error = SetAccountsInCookieResult::kPersistentError;
SimulateOAuthMultiloginFinished(
identity_manager()->GetGaiaCookieManagerService(), error);
EXPECT_EQ(error_from_set_accounts_in_cookie_completed_callback, error);
}
TEST_F(IdentityManagerTest, CallbackSentOnAccountsCookieDeletedByUserAction) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnCookieDeletedByUserCallback(
run_loop.QuitClosure());
auto cookie = net::CanonicalCookie::CreateUnsafeCookieForTesting(
"SAPISID", std::string(), ".google.com", "/", base::Time(), base::Time(),
base::Time(), /*secure=*/true, false, net::CookieSameSite::NO_RESTRICTION,
net::COOKIE_PRIORITY_DEFAULT, false);
SimulateCookieDeletedByUser(identity_manager()->GetGaiaCookieManagerService(),
*cookie);
run_loop.Run();
}
TEST_F(IdentityManagerTest, OnNetworkInitialized) {
auto test_cookie_manager = std::make_unique<network::TestCookieManager>();
network::TestCookieManager* test_cookie_manager_ptr =
test_cookie_manager.get();
signin_client()->set_cookie_manager(std::move(test_cookie_manager));
identity_manager()->OnNetworkInitialized();
base::RunLoop run_loop;
identity_manager_observer()->SetOnCookieDeletedByUserCallback(
run_loop.QuitClosure());
// Dispatch a known change of a known cookie instance *through the mojo
// pipe* in order to ensure the GCMS is listening to CookieManager changes.
//
// It is important the the cause of the change is known here (ie
// network::mojom::CookieChangeCause::EXPLICIT) so the test can block of the
// proper IdentityManager observer callback to be called (in this case
// OnAccountsCookieDeletedByUserAction).
//
// Note that this call differs from calling SimulateCookieDeletedByUser()
// directly in the sense that SimulateCookieDeletedByUser() does not go
// through any mojo pipe.
auto cookie = net::CanonicalCookie::CreateUnsafeCookieForTesting(
"SAPISID", std::string(), ".google.com", "/", base::Time(), base::Time(),
base::Time(), /*secure=*/true, false, net::CookieSameSite::NO_RESTRICTION,
net::COOKIE_PRIORITY_DEFAULT, false);
test_cookie_manager_ptr->DispatchCookieChange(net::CookieChangeInfo(
*cookie, net::CookieAccessResult(), net::CookieChangeCause::EXPLICIT));
run_loop.Run();
}
TEST_F(IdentityManagerTest,
BatchChangeObserversAreNotifiedOnCredentialsUpdate) {
identity_manager()->GetAccountTrackerService()->SeedAccountInfo(kTestGaiaId,
kTestEmail);
identity_manager()->GetPrimaryAccountMutator()->SetPrimaryAccount(
primary_account_id(), ConsentLevel::kSync);
SetRefreshTokenForAccount(identity_manager(), primary_account_id(),
"refresh_token");
EXPECT_EQ(1ul, identity_manager_observer()->BatchChangeRecords().size());
EXPECT_EQ(1ul,
identity_manager_observer()->BatchChangeRecords().at(0).size());
EXPECT_EQ(primary_account_id(),
identity_manager_observer()->BatchChangeRecords().at(0).at(0));
}
// Check that FindExtendedAccountInfo returns a valid account info iff the
// account is known, and all the extended information is available.
TEST_F(IdentityManagerTest, FindExtendedAccountInfo) {
CoreAccountInfo account_info;
account_info.email = kTestEmail2;
account_info.gaia = kTestGaiaId2;
account_info.account_id = identity_manager()->PickAccountIdForAccount(
account_info.gaia, account_info.email);
// FindExtendedAccountInfo() returns empty if the account_info is invalid.
EXPECT_TRUE(
identity_manager()->FindExtendedAccountInfo(CoreAccountInfo{}).IsEmpty());
// FindExtendedAccountInfo() returns empty if the account_info is unknown.
EXPECT_TRUE(
identity_manager()->FindExtendedAccountInfo(account_info).IsEmpty());
// Insert the core account information in the AccountTrackerService.
const CoreAccountId account_id =
account_tracker()->SeedAccountInfo(account_info.gaia, account_info.email);
ASSERT_EQ(account_info.account_id, account_id);
// The refresh token is not available.
EXPECT_TRUE(
identity_manager()->FindExtendedAccountInfo(account_info).IsEmpty());
// FindExtendedAccountInfo() returns extended account information if the
// account is known and the token is available.
SetRefreshTokenForAccount(identity_manager(), account_info.account_id,
"token");
const AccountInfo extended_account_info =
identity_manager()->FindExtendedAccountInfo(account_info);
EXPECT_TRUE(!extended_account_info.IsEmpty());
EXPECT_EQ(account_info.gaia, extended_account_info.gaia);
EXPECT_EQ(account_info.email, extended_account_info.email);
EXPECT_EQ(account_info.account_id, extended_account_info.account_id);
}
// Checks that FindExtendedAccountInfoByAccountId() returns information about
// the account if the account is found, or an empty account info.
TEST_F(IdentityManagerTest, FindExtendedAccountInfoByAccountId) {
CoreAccountInfo account_info;
account_info.email = kTestEmail2;
account_info.gaia = kTestGaiaId2;
account_info.account_id = identity_manager()->PickAccountIdForAccount(
account_info.gaia, account_info.email);
// Account is unknown.
AccountInfo maybe_account_info =
identity_manager()->FindExtendedAccountInfoByAccountId(
account_info.account_id);
EXPECT_TRUE(maybe_account_info.IsEmpty());
// Refresh token is not available.
const CoreAccountId account_id =
account_tracker()->SeedAccountInfo(account_info.gaia, account_info.email);
maybe_account_info = identity_manager()->FindExtendedAccountInfoByAccountId(
account_info.account_id);
EXPECT_TRUE(maybe_account_info.IsEmpty());
// Account with refresh token.
SetRefreshTokenForAccount(identity_manager(), account_info.account_id,
"token");
maybe_account_info = identity_manager()->FindExtendedAccountInfoByAccountId(
account_info.account_id);
EXPECT_FALSE(maybe_account_info.IsEmpty());
EXPECT_EQ(account_info.account_id, maybe_account_info.account_id);
EXPECT_EQ(account_info.email, maybe_account_info.email);
EXPECT_EQ(account_info.gaia, maybe_account_info.gaia);
}
// Checks that FindExtendedAccountInfoByEmailAddress() returns information about
// the account if the account is found, or an empty account info.
TEST_F(IdentityManagerTest, FindExtendedAccountInfoByEmailAddress) {
CoreAccountInfo account_info;
account_info.email = kTestEmail2;
account_info.gaia = kTestGaiaId2;
account_info.account_id = identity_manager()->PickAccountIdForAccount(
account_info.gaia, account_info.email);
// Account is unknown.
AccountInfo maybe_account_info =
identity_manager()->FindExtendedAccountInfoByEmailAddress(
account_info.email);
EXPECT_TRUE(maybe_account_info.IsEmpty());
// Refresh token is not available.
const CoreAccountId account_id =
account_tracker()->SeedAccountInfo(account_info.gaia, account_info.email);
maybe_account_info =
identity_manager()->FindExtendedAccountInfoByEmailAddress(
account_info.email);
EXPECT_TRUE(maybe_account_info.IsEmpty());
// Account with refresh token.
SetRefreshTokenForAccount(identity_manager(), account_info.account_id,
"token");
maybe_account_info =
identity_manager()->FindExtendedAccountInfoByEmailAddress(
account_info.email);
EXPECT_FALSE(maybe_account_info.IsEmpty());
EXPECT_EQ(account_info.account_id, maybe_account_info.account_id);
EXPECT_EQ(account_info.email, maybe_account_info.email);
EXPECT_EQ(account_info.gaia, maybe_account_info.gaia);
}
// Checks that FindExtendedAccountInfoByGaiaId() returns information about the
// account if the account is found, or an empty account info.
TEST_F(IdentityManagerTest, FindExtendedAccountInfoByGaiaId) {
CoreAccountInfo account_info;
account_info.email = kTestEmail2;
account_info.gaia = kTestGaiaId2;
account_info.account_id = identity_manager()->PickAccountIdForAccount(
account_info.gaia, account_info.email);
// Account is unknown.
AccountInfo maybe_account_info =
identity_manager()->FindExtendedAccountInfoByGaiaId(account_info.gaia);
EXPECT_TRUE(maybe_account_info.IsEmpty());
// Refresh token is not available.
const CoreAccountId account_id =
account_tracker()->SeedAccountInfo(account_info.gaia, account_info.email);
maybe_account_info =
identity_manager()->FindExtendedAccountInfoByGaiaId(account_info.gaia);
EXPECT_TRUE(maybe_account_info.IsEmpty());
// Account with refresh token.
SetRefreshTokenForAccount(identity_manager(), account_info.account_id,
"token");
maybe_account_info =
identity_manager()->FindExtendedAccountInfoByGaiaId(account_info.gaia);
EXPECT_FALSE(maybe_account_info.IsEmpty());
EXPECT_EQ(account_info.account_id, maybe_account_info.account_id);
EXPECT_EQ(account_info.email, maybe_account_info.email);
EXPECT_EQ(account_info.gaia, maybe_account_info.gaia);
}
TEST_F(IdentityManagerTest, FindExtendedPrimaryAccountInfo) {
// AccountInfo found for primary account, even without token.
RemoveRefreshTokenForPrimaryAccount(identity_manager());
ASSERT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
ASSERT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken(
ConsentLevel::kSignin));
AccountInfo extended_info =
identity_manager()->FindExtendedPrimaryAccountInfo(ConsentLevel::kSignin);
CoreAccountInfo core_info =
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSignin);
EXPECT_FALSE(extended_info.IsEmpty());
EXPECT_EQ(core_info.account_id, extended_info.account_id);
EXPECT_EQ(core_info.email, extended_info.email);
EXPECT_EQ(core_info.gaia, extended_info.gaia);
#if !BUILDFLAG(IS_CHROMEOS_ASH)
// It's not possible to sign out on Ash.
ClearPrimaryAccount(identity_manager());
SetRefreshTokenForAccount(identity_manager(), core_info.account_id, "token");
// No info found if there is no primary account.
ASSERT_FALSE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSignin));
ASSERT_TRUE(
identity_manager()->HasAccountWithRefreshToken(core_info.account_id));
EXPECT_TRUE(identity_manager()
->FindExtendedPrimaryAccountInfo(ConsentLevel::kSignin)
.IsEmpty());
#endif
}
// Checks that AreRefreshTokensLoaded() returns true after LoadCredentials.
TEST_F(IdentityManagerTest, AreRefreshTokensLoaded) {
base::RunLoop run_loop;
identity_manager_observer()->SetOnRefreshTokensLoadedCallback(
run_loop.QuitClosure());
// Credentials are already loaded in PrimaryAccountManager::Initialize()
// which runs even before the IdentityManager is created. That's why
// we fake the credentials loaded state and force another load in
// order to test AreRefreshTokensLoaded.
token_service()->set_all_credentials_loaded_for_testing(false);
EXPECT_FALSE(identity_manager()->AreRefreshTokensLoaded());
token_service()->LoadCredentials(CoreAccountId());
run_loop.Run();
EXPECT_TRUE(identity_manager()->AreRefreshTokensLoaded());
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
TEST_F(IdentityManagerTest, SetPrimaryAccount) {
signin_client()->SetInitialPrimaryAccountForTests(account_manager::Account{
account_manager::AccountKey{kTestGaiaId,
account_manager::AccountType::kGaia},
kTestEmail});
// Do not sign into a primary account as part of the test setup.
RecreateIdentityManager(AccountConsistencyMethod::kDisabled,
PrimaryAccountManagerSetup::kNoAuthenticatedAccount);
// We should have a Primary Account set up automatically.
ASSERT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
EXPECT_EQ(
kTestGaiaId,
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSync).gaia);
}
// TODO(https://crbug.com/1223364): Remove this when all the users are migrated.
TEST_F(IdentityManagerTest, SetPrimaryAccountClearsExistingPrimaryAccount) {
signin_client()->SetInitialPrimaryAccountForTests(account_manager::Account{
account_manager::AccountKey{kTestGaiaId2,
account_manager::AccountType::kGaia},
kTestEmail2});
// RecreateIdentityManager will create PrimaryAccountManager with the primary
// account set to kTestGaiaId. After that, IdentityManager ctor should clear
// this existing primary account and set the new one to the initial value
// provided by the SigninClient.
RecreateIdentityManager(AccountConsistencyMethod::kDisabled,
PrimaryAccountManagerSetup::kWithAuthenticatedAccout);
ASSERT_TRUE(identity_manager()->HasPrimaryAccount(ConsentLevel::kSync));
EXPECT_EQ(
kTestGaiaId2,
identity_manager()->GetPrimaryAccountInfo(ConsentLevel::kSync).gaia);
}
#endif
TEST_F(IdentityManagerTest, AccountIdMigration_DoneOnInitialization) {
EXPECT_EQ(IdentityManager::AccountIdMigrationState::MIGRATION_DONE,
identity_manager()->GetAccountIdMigrationState());
}
// Checks that IdentityManager::Observer gets OnAccountUpdated when account info
// is updated.
TEST_F(IdentityManagerTest, ObserveOnAccountUpdated) {
const AccountInfo account_info =
MakeAccountAvailable(identity_manager(), kTestEmail3);
SimulateSuccessfulFetchOfAccountInfo(
identity_manager(), account_info.account_id, account_info.email,
account_info.gaia, kTestHostedDomain, kTestFullName, kTestGivenName,
kTestLocale, kTestPictureUrl);
EXPECT_EQ(account_info.account_id, identity_manager_observer()
->AccountFromAccountUpdatedCallback()
.account_id);
EXPECT_EQ(
account_info.email,
identity_manager_observer()->AccountFromAccountUpdatedCallback().email);
}
TEST_F(IdentityManagerTest, TestOnAccountRemovedWithInfoCallback) {
AccountInfo account_info =
MakeAccountAvailable(identity_manager(), kTestEmail2);
EXPECT_EQ(kTestEmail2, account_info.email);
account_tracker()->RemoveAccount(account_info.account_id);
// Check if OnAccountRemovedWithInfo is called after removing |account_info|
// by RemoveAccount().
EXPECT_TRUE(
identity_manager_observer()->WasCalledAccountRemovedWithInfoCallback());
// Check if the passed AccountInfo is the same to the removing one.
EXPECT_EQ(account_info.account_id,
identity_manager_observer()
->AccountFromAccountRemovedWithInfoCallback()
.account_id);
EXPECT_EQ(account_info.email,
identity_manager_observer()
->AccountFromAccountRemovedWithInfoCallback()
.email);
}
TEST_F(IdentityManagerTest, TestPickAccountIdForAccount) {
const CoreAccountId account_id =
identity_manager()->PickAccountIdForAccount(kTestGaiaId, kTestEmail);
const bool account_id_migration_done =
identity_manager()->GetAccountIdMigrationState() ==
IdentityManager::AccountIdMigrationState::MIGRATION_DONE;
if (account_id_migration_done) {
EXPECT_EQ(kTestGaiaId, account_id.ToString());
} else {
EXPECT_TRUE(gaia::AreEmailsSame(kTestEmail, account_id.ToString()));
}
}
#if defined(OS_ANDROID)
TEST_F(IdentityManagerTest, RefreshAccountInfoIfStale) {
// The flow of this test results in an interaction with
// ChildAccountInfoFetcherAndroid, which requires initialization of
// AccountManagerFacade in java code to avoid a crash.
SetUpMockAccountManagerFacade();
identity_manager()->GetAccountFetcherService()->OnNetworkInitialized();
AccountInfo account_info =
MakeAccountAvailable(identity_manager(), kTestEmail2);
identity_manager()->RefreshAccountInfoIfStale(account_info.account_id);
SimulateSuccessfulFetchOfAccountInfo(
identity_manager(), account_info.account_id, account_info.email,
account_info.gaia, kTestHostedDomain, kTestFullName, kTestGivenName,
kTestLocale, kTestPictureUrl);
const AccountInfo& refreshed_account_info =
identity_manager_observer()->AccountFromAccountUpdatedCallback();
EXPECT_EQ(account_info.account_id, refreshed_account_info.account_id);
EXPECT_EQ(account_info.email, refreshed_account_info.email);
EXPECT_EQ(account_info.gaia, refreshed_account_info.gaia);
EXPECT_EQ(kTestHostedDomain, refreshed_account_info.hosted_domain);
EXPECT_EQ(kTestFullName, refreshed_account_info.full_name);
EXPECT_EQ(kTestGivenName, refreshed_account_info.given_name);
EXPECT_EQ(kTestLocale, refreshed_account_info.locale);
EXPECT_EQ(kTestPictureUrl, refreshed_account_info.picture_url);
}
#endif
} // namespace signin
| 43.344382 | 108 | 0.768534 | [
"vector"
] |
2e031da3b0d34c99c73fb81fc8b74473de356ccb | 11,845 | cpp | C++ | Tools/Tools/DumpRenderTree/win/ResourceLoadDelegate.cpp | VincentWei/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | Tools/Tools/DumpRenderTree/win/ResourceLoadDelegate.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | null | null | null | Tools/Tools/DumpRenderTree/win/ResourceLoadDelegate.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "ResourceLoadDelegate.h"
#include "DumpRenderTree.h"
#include "LayoutTestController.h"
#include <WebKit/WebKitCOMAPI.h>
#include <comutil.h>
#include <sstream>
#include <tchar.h>
#include <wtf/HashMap.h>
#include <wtf/Vector.h>
using namespace std;
static inline wstring wstringFromBSTR(BSTR str)
{
return wstring(str, ::SysStringLen(str));
}
static inline wstring wstringFromInt(int i)
{
wostringstream ss;
ss << i;
return ss.str();
}
static inline BSTR BSTRFromString(const string& str)
{
int length = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), 0, 0);
BSTR result = ::SysAllocStringLen(0, length);
::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), result, length);
return result;
}
typedef HashMap<unsigned long, wstring> IdentifierMap;
IdentifierMap& urlMap()
{
static IdentifierMap urlMap;
return urlMap;
}
static wstring descriptionSuitableForTestResult(unsigned long identifier)
{
IdentifierMap::iterator it = urlMap().find(identifier);
if (it == urlMap().end())
return L"<unknown>";
return urlSuitableForTestResult(it->second);
}
static wstring descriptionSuitableForTestResult(IWebURLRequest* request)
{
if (!request)
return L"(null)";
BSTR urlBSTR;
if (FAILED(request->URL(&urlBSTR)))
return wstring();
wstring url = urlSuitableForTestResult(wstringFromBSTR(urlBSTR));
::SysFreeString(urlBSTR);
BSTR mainDocumentURLBSTR;
if (FAILED(request->mainDocumentURL(&mainDocumentURLBSTR)))
return wstring();
wstring mainDocumentURL = urlSuitableForTestResult(wstringFromBSTR(mainDocumentURLBSTR));
::SysFreeString(mainDocumentURLBSTR);
BSTR httpMethodBSTR;
if (FAILED(request->HTTPMethod(&httpMethodBSTR)))
return wstring();
wstring httpMethod = wstringFromBSTR(httpMethodBSTR);
::SysFreeString(httpMethodBSTR);
return L"<NSURLRequest URL " + url + L", main document URL " + mainDocumentURL + L", http method " + httpMethod + L">";
}
static wstring descriptionSuitableForTestResult(IWebURLResponse* response)
{
if (!response)
return L"(null)";
BSTR urlBSTR;
if (FAILED(response->URL(&urlBSTR)))
return wstring();
wstring url = urlSuitableForTestResult(wstringFromBSTR(urlBSTR));
::SysFreeString(urlBSTR);
int statusCode = 0;
COMPtr<IWebHTTPURLResponse> httpResponse;
if (response && SUCCEEDED(response->QueryInterface(&httpResponse)))
httpResponse->statusCode(&statusCode);
return L"<NSURLResponse " + url + L", http status code " + wstringFromInt(statusCode) + L">";
}
static wstring descriptionSuitableForTestResult(IWebError* error, unsigned long identifier)
{
wstring result = L"<NSError ";
BSTR domainSTR;
if (FAILED(error->domain(&domainSTR)))
return wstring();
wstring domain = wstringFromBSTR(domainSTR);
::SysFreeString(domainSTR);
int code;
if (FAILED(error->code(&code)))
return wstring();
if (domain == L"CFURLErrorDomain") {
domain = L"NSURLErrorDomain";
// Convert kCFURLErrorUnknown to NSURLErrorUnknown
if (code == -998)
code = -1;
} else if (domain == L"kCFErrorDomainWinSock") {
domain = L"NSURLErrorDomain";
// Convert the winsock error code to an NSURLError code.
if (code == WSAEADDRNOTAVAIL)
code = -1004; // NSURLErrorCannotConnectToHose;
}
result += L"domain " + domain;
result += L", code " + wstringFromInt(code);
BSTR failingURLSTR;
if (FAILED(error->failingURL(&failingURLSTR)))
return wstring();
wstring failingURL;
// If the error doesn't have a failing URL, we fake one by using the URL the resource had
// at creation time. This seems to work fine for now.
// See <rdar://problem/5064234> CFErrors should have failingURL key.
if (failingURLSTR)
failingURL = wstringFromBSTR(failingURLSTR);
else
failingURL = descriptionSuitableForTestResult(identifier);
::SysFreeString(failingURLSTR);
result += L", failing URL \"" + urlSuitableForTestResult(failingURL) + L"\">";
return result;
}
ResourceLoadDelegate::ResourceLoadDelegate()
: m_refCount(1)
{
}
ResourceLoadDelegate::~ResourceLoadDelegate()
{
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IWebResourceLoadDelegate*>(this);
else if (IsEqualGUID(riid, IID_IWebResourceLoadDelegate))
*ppvObject = static_cast<IWebResourceLoadDelegate*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE ResourceLoadDelegate::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE ResourceLoadDelegate::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::identifierForInitialRequest(
/* [in] */ IWebView* webView,
/* [in] */ IWebURLRequest* request,
/* [in] */ IWebDataSource* dataSource,
/* [in] */ unsigned long identifier)
{
if (!done && gLayoutTestController->dumpResourceLoadCallbacks()) {
BSTR urlStr;
if (FAILED(request->URL(&urlStr)))
return E_FAIL;
urlMap().set(identifier, wstringFromBSTR(urlStr));
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::willSendRequest(
/* [in] */ IWebView* webView,
/* [in] */ unsigned long identifier,
/* [in] */ IWebURLRequest* request,
/* [in] */ IWebURLResponse* redirectResponse,
/* [in] */ IWebDataSource* dataSource,
/* [retval][out] */ IWebURLRequest **newRequest)
{
if (!done && gLayoutTestController->dumpResourceLoadCallbacks()) {
printf("%S - willSendRequest %S redirectResponse %S\n",
descriptionSuitableForTestResult(identifier).c_str(),
descriptionSuitableForTestResult(request).c_str(),
descriptionSuitableForTestResult(redirectResponse).c_str());
}
if (!done && gLayoutTestController->willSendRequestReturnsNull()) {
*newRequest = 0;
return S_OK;
}
if (!done && gLayoutTestController->willSendRequestReturnsNullOnRedirect() && redirectResponse) {
printf("Returning null for this redirect\n");
*newRequest = 0;
return S_OK;
}
IWebMutableURLRequest* requestCopy = 0;
request->mutableCopy(&requestCopy);
const set<string>& clearHeaders = gLayoutTestController->willSendRequestClearHeaders();
for (set<string>::const_iterator header = clearHeaders.begin(); header != clearHeaders.end(); ++header) {
BSTR bstrHeader = BSTRFromString(*header);
requestCopy->setValue(0, bstrHeader);
SysFreeString(bstrHeader);
}
*newRequest = requestCopy;
return S_OK;
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::didReceiveAuthenticationChallenge(
/* [in] */ IWebView *webView,
/* [in] */ unsigned long identifier,
/* [in] */ IWebURLAuthenticationChallenge *challenge,
/* [in] */ IWebDataSource *dataSource)
{
if (!gLayoutTestController->handlesAuthenticationChallenges())
return E_FAIL;
const char* user = gLayoutTestController->authenticationUsername().c_str();
const char* password = gLayoutTestController->authenticationPassword().c_str();
printf("%S - didReceiveAuthenticationChallenge - Responding with %s:%s\n", descriptionSuitableForTestResult(identifier).c_str(), user, password);
COMPtr<IWebURLAuthenticationChallengeSender> sender;
if (!challenge || FAILED(challenge->sender(&sender)))
return E_FAIL;
COMPtr<IWebURLCredential> credential;
if (FAILED(WebKitCreateInstance(CLSID_WebURLCredential, 0, IID_IWebURLCredential, (void**)&credential)))
return E_FAIL;
credential->initWithUser(_bstr_t(user), _bstr_t(password), WebURLCredentialPersistenceForSession);
sender->useCredential(credential.get(), challenge);
return S_OK;
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::didReceiveResponse(
/* [in] */ IWebView* webView,
/* [in] */ unsigned long identifier,
/* [in] */ IWebURLResponse* response,
/* [in] */ IWebDataSource* dataSource)
{
if (!done && gLayoutTestController->dumpResourceLoadCallbacks()) {
printf("%S - didReceiveResponse %S\n",
descriptionSuitableForTestResult(identifier).c_str(),
descriptionSuitableForTestResult(response).c_str());
}
if (!done && gLayoutTestController->dumpResourceResponseMIMETypes()) {
BSTR mimeTypeBSTR;
if (FAILED(response->MIMEType(&mimeTypeBSTR)))
E_FAIL;
wstring mimeType = wstringFromBSTR(mimeTypeBSTR);
::SysFreeString(mimeTypeBSTR);
BSTR urlBSTR;
if (FAILED(response->URL(&urlBSTR)))
E_FAIL;
wstring url = urlSuitableForTestResult(wstringFromBSTR(urlBSTR));
::SysFreeString(urlBSTR);
printf("%S has MIME type %S\n", url.c_str(), mimeType.c_str());
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::didFinishLoadingFromDataSource(
/* [in] */ IWebView* webView,
/* [in] */ unsigned long identifier,
/* [in] */ IWebDataSource* dataSource)
{
if (!done && gLayoutTestController->dumpResourceLoadCallbacks()) {
printf("%S - didFinishLoading\n",
descriptionSuitableForTestResult(identifier).c_str()),
urlMap().remove(identifier);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE ResourceLoadDelegate::didFailLoadingWithError(
/* [in] */ IWebView* webView,
/* [in] */ unsigned long identifier,
/* [in] */ IWebError* error,
/* [in] */ IWebDataSource* dataSource)
{
if (!done && gLayoutTestController->dumpResourceLoadCallbacks()) {
printf("%S - didFailLoadingWithError: %S\n",
descriptionSuitableForTestResult(identifier).c_str(),
descriptionSuitableForTestResult(error, identifier).c_str());
urlMap().remove(identifier);
}
return S_OK;
}
| 32.363388 | 149 | 0.686788 | [
"vector"
] |
2e0e9b3626788426392448b13304e09fa111a62a | 17,233 | cpp | C++ | bsengine/src/bstorm/renderer.cpp | Frenticpony/bstorm | 4f6a02008d7bddb8d149b15f428cacdd54a2debd | [
"MIT"
] | null | null | null | bsengine/src/bstorm/renderer.cpp | Frenticpony/bstorm | 4f6a02008d7bddb8d149b15f428cacdd54a2debd | [
"MIT"
] | null | null | null | bsengine/src/bstorm/renderer.cpp | Frenticpony/bstorm | 4f6a02008d7bddb8d149b15f428cacdd54a2debd | [
"MIT"
] | null | null | null | #include <bstorm/renderer.hpp>
#include <bstorm/vertex.hpp>
#include <bstorm/color_rgb.hpp>
#include <bstorm/dnh_const.hpp>
#include <bstorm/ptr_util.hpp>
#include <bstorm/camera2D.hpp>
#include <bstorm/shader.hpp>
#include <bstorm/texture.hpp>
#include <bstorm/mesh.hpp>
#include <bstorm/logger.hpp>
#include <algorithm>
static const char prim2DVertexShaderSrc[] =
"float4x4 worldMatrix : register(c0);"
"float4x4 viewProjMatrix : register(c4);"
"struct VS_INPUT {"
" float4 pos : POSITION;"
" float4 diffuse : COLOR;"
" float2 texCoord0 : TEXCOORD0;"
"};"
"struct VS_OUTPUT {"
" float4 pos : POSITION;"
" float4 diffuse : COLOR;"
" float2 texCoord0 : TEXCOORD0;"
"};"
"VS_OUTPUT main(VS_INPUT In) {"
" VS_OUTPUT Out;"
" Out.pos = mul(mul(In.pos, worldMatrix), viewProjMatrix);"
" Out.pos.z = 0;"
" Out.diffuse = In.diffuse;"
" Out.texCoord0 = In.texCoord0;"
" return Out;"
"}";
static const char prim3DVertexShaderSrc[] =
"float4x4 worldViewProjMatrix : register(c0);"
"float fogStart : register(c12);"
"float fogEnd : register(c13);"
"struct VS_INPUT {"
" float4 pos : POSITION;"
" float4 diffuse : COLOR;"
" float2 texCoord0 : TEXCOORD0;"
"};"
"struct VS_OUTPUT {"
" float4 pos : POSITION;"
" float4 diffuse : COLOR;"
" float2 texCoord0 : TEXCOORD0;"
" float fog : FOG;"
"};"
"VS_OUTPUT main(VS_INPUT In) {"
" VS_OUTPUT Out;"
" Out.pos = mul(In.pos, worldViewProjMatrix);"
" Out.diffuse = In.diffuse;"
" Out.texCoord0 = In.texCoord0;"
" Out.fog = (fogEnd - Out.pos.w) / (fogEnd - fogStart);"
" return Out;"
"}";
static const char meshVertexShaderSrc[] =
"float4x4 worldViewProjMatrix : register(c0);"
"float4x4 normalMatrix : register(c4);"
"float4 materialAmbient : register(c8);"
"float4 materialDiffuse : register(c9);"
"float4 lightDir : register(c10);"
"float fogStart : register(c12);"
"float fogEnd : register(c13);"
"struct VS_INPUT {"
" float4 pos : POSITION;"
" float3 normal : NORMAL;"
" float2 texCoord0 : TEXCOORD0;"
"};"
"struct VS_OUTPUT {"
" float4 pos : POSITION;"
" float4 diffuse : COLOR;"
" float2 texCoord0 : TEXCOORD0;"
" float fog : FOG;"
"};"
"VS_OUTPUT main(VS_INPUT In) {"
" VS_OUTPUT Out;"
" Out.pos = mul(In.pos, worldViewProjMatrix);"
" In.normal = normalize(mul(In.normal, normalMatrix));"
" Out.diffuse.xyz = materialAmbient.xyz + max(0.0f, dot(In.normal, lightDir.xyz)) * materialDiffuse.xyz;"
" Out.diffuse.w = materialAmbient.w * materialDiffuse.w;"
" Out.texCoord0 = In.texCoord0;"
" Out.fog = (fogEnd - Out.pos.w) / (fogEnd - fogStart);"
" return Out;"
"}";
namespace bstorm
{
Renderer::Renderer(IDirect3DDevice9* dev) :
d3DDevice_(dev),
prim2DVertexShader_(nullptr),
prim3DVertexShader_(nullptr),
meshVertexShader_(nullptr),
currentBlendType_(BLEND_NONE),
currentFilterType_(FILTER_LINEAR), //FP FILTER
fogEnable_(false),
fogStart_(0),
fogEnd_(0)
{
ID3DXBuffer* code = nullptr;
ID3DXBuffer* error = nullptr;
try
{
// create vertex shader 2D
if (FAILED(D3DXCompileShader(prim2DVertexShaderSrc, sizeof(prim2DVertexShaderSrc) - 1, nullptr, nullptr, "main", "vs_1_1", D3DXSHADER_PACKMATRIX_ROWMAJOR, &code, &error, nullptr)))
{
throw Log(LogLevel::LV_ERROR)
.Msg("Internal shader compile error.")
.Param(LogParam(LogParam::Tag::TEXT, (const char*)error->GetBufferPointer()));
}
d3DDevice_->CreateVertexShader((const DWORD*)code->GetBufferPointer(), &prim2DVertexShader_);
safe_release(code);
safe_release(error);
// create vertex shader 3D
if (FAILED(D3DXCompileShader(prim3DVertexShaderSrc, sizeof(prim3DVertexShaderSrc) - 1, nullptr, nullptr, "main", "vs_1_1", D3DXSHADER_PACKMATRIX_ROWMAJOR, &code, &error, nullptr)))
{
throw Log(LogLevel::LV_ERROR)
.Msg("Internal shader compile error.")
.Param(LogParam(LogParam::Tag::TEXT, (const char*)error->GetBufferPointer()));
}
d3DDevice_->CreateVertexShader((const DWORD*)code->GetBufferPointer(), &prim3DVertexShader_);
safe_release(code);
safe_release(error);
// create vertex shader mesh
if (FAILED(D3DXCompileShader(meshVertexShaderSrc, sizeof(meshVertexShaderSrc) - 1, nullptr, nullptr, "main", "vs_1_1", D3DXSHADER_PACKMATRIX_ROWMAJOR, &code, &error, nullptr)))
{
throw Log(LogLevel::LV_ERROR)
.Msg("Internal shader compile error.")
.Param(LogParam(LogParam::Tag::TEXT, (const char*)error->GetBufferPointer()));
}
d3DDevice_->CreateVertexShader((const DWORD*)code->GetBufferPointer(), &meshVertexShader_);
safe_release(code);
safe_release(error);
} catch (...)
{
safe_release(code);
safe_release(error);
throw;
}
D3DXMatrixTranslation(&halfPixelOffsetMatrix_, -0.5f, -0.5f, 0.0f);
}
Renderer::~Renderer()
{
prim2DVertexShader_->Release();
prim3DVertexShader_->Release();
meshVertexShader_->Release();
}
void Renderer::InitRenderState()
{
// カリング無効化
d3DDevice_->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
// 固定機能パイプラインのピクセルシェーダ用
currentFilterType_ = FILTER_LINEAR; //FP FILTER
d3DDevice_->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3DDevice_->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
d3DDevice_->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
d3DDevice_->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
d3DDevice_->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
d3DDevice_->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
// 透明度0を描画しないようにする
// NOTE : ObjTextが乗算合成されたときに、背景部分が真っ黒にならないようにするため
d3DDevice_->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3DDevice_->SetRenderState(D3DRS_ALPHAREF, 0);
d3DDevice_->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
currentBlendType_ = BLEND_ALPHA;
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
// light off
d3DDevice_->SetRenderState(D3DRS_LIGHTING, FALSE);
}
static int calcPolygonNum(D3DPRIMITIVETYPE primType, int vertexCount)
{
if (primType == D3DPT_TRIANGLELIST)
{
return vertexCount / 3;
} else
{
return vertexCount - 2;
}
}
void Renderer::RenderPrim2D(D3DPRIMITIVETYPE primType, int vertexCount, const Vertex* vertices, IDirect3DTexture9* texture, int blendType, int filterType, const D3DXMATRIX & worldMatrix, const std::shared_ptr<Shader>& pixelShader, bool permitCamera, bool insertHalfPixelOffset)
{
// disable z-buffer-write, z-test, fog
d3DDevice_->SetRenderState(D3DRS_ZENABLE, FALSE);
d3DDevice_->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
d3DDevice_->SetRenderState(D3DRS_FOGENABLE, FALSE);
// set blend type
SetBlendType(blendType);
// set filter type
SetFilterType(filterType); //FP FILTER
// set vertex shader
d3DDevice_->SetVertexShader(prim2DVertexShader_);
// set shader constant
d3DDevice_->SetVertexShaderConstantF(0, (const float*)&(insertHalfPixelOffset ? (halfPixelOffsetMatrix_ * worldMatrix) : worldMatrix), 4);
d3DDevice_->SetVertexShaderConstantF(4, (const float*)&(permitCamera ? viewProjMatrix2D_ : forbidCameraViewProjMatrix2D_), 4);
// set vertex format
d3DDevice_->SetFVF(Vertex::Format);
// set texture
d3DDevice_->SetTexture(0, texture);
// set pixel shader
if (pixelShader)
{
ID3DXEffect* effect = pixelShader->getEffect();
UINT passCnt;
effect->Begin(&passCnt, D3DXFX_DONOTSAVESTATE);
for (int i = 0; i < passCnt; i++)
{
effect->BeginPass(i);
d3DDevice_->DrawPrimitiveUP(primType, calcPolygonNum(primType, vertexCount), vertices, sizeof(Vertex));
effect->EndPass();
}
effect->End();
} else
{
d3DDevice_->SetPixelShader(nullptr);
d3DDevice_->DrawPrimitiveUP(primType, calcPolygonNum(primType, vertexCount), vertices, sizeof(Vertex));
}
d3DDevice_->SetVertexShader(nullptr);
d3DDevice_->SetPixelShader(nullptr);
}
void Renderer::RenderPrim3D(D3DPRIMITIVETYPE primType, int vertexCount, const Vertex* vertices, IDirect3DTexture9* texture, int blendType, const D3DXMATRIX & worldMatrix, const std::shared_ptr<Shader>& pixelShader, bool zWriteEnable, bool zTestEnable, bool useFog, bool billboardEnable_)
{
// set z-buffer-write, z-test, fog
d3DDevice_->SetRenderState(D3DRS_ZENABLE, zTestEnable ? TRUE : FALSE);
d3DDevice_->SetRenderState(D3DRS_ZWRITEENABLE, zWriteEnable ? TRUE : FALSE);
d3DDevice_->SetRenderState(D3DRS_FOGENABLE, useFog && fogEnable_ ? TRUE : FALSE);
d3DDevice_->SetRenderState(D3DRS_FOGCOLOR, fogColor_);
// set blend type
SetBlendType(blendType);
// set vertex shader
d3DDevice_->SetVertexShader(prim3DVertexShader_);
// set shader constant
// 3Dオブジェクトは頂点数が多いので、予め行列を全て掛けておく
const D3DXMATRIX worldViewProjMatrix = worldMatrix * (billboardEnable_ ? billboardViewProjMatrix3D_ : viewProjMatrix3D_);
d3DDevice_->SetVertexShaderConstantF(0, (const float*)&worldViewProjMatrix, 4);
d3DDevice_->SetVertexShaderConstantF(12, &fogStart_, 1);
d3DDevice_->SetVertexShaderConstantF(13, &fogEnd_, 1);
// set vertex format
d3DDevice_->SetFVF(Vertex::Format);
// set texture
d3DDevice_->SetTexture(0, texture);
// set pixel shader
if (pixelShader)
{
ID3DXEffect* effect = pixelShader->getEffect();
UINT passCnt;
effect->Begin(&passCnt, D3DXFX_DONOTSAVESTATE);
for (int i = 0; i < passCnt; i++)
{
effect->BeginPass(i);
d3DDevice_->DrawPrimitiveUP(primType, calcPolygonNum(primType, vertexCount), vertices, sizeof(Vertex));
effect->EndPass();
}
effect->End();
} else
{
d3DDevice_->SetPixelShader(nullptr);
d3DDevice_->DrawPrimitiveUP(primType, calcPolygonNum(primType, vertexCount), vertices, sizeof(Vertex));
}
d3DDevice_->SetVertexShader(nullptr);
d3DDevice_->SetPixelShader(nullptr);
}
void Renderer::RenderMesh(const std::shared_ptr<Mesh>& mesh, const D3DCOLORVALUE& col, int blendType, const D3DXMATRIX & worldMatrix, const std::shared_ptr<Shader>& pixelShader, bool zWriteEnable, bool zTestEnable, bool useFog)
{
// set z-buffer-write, z-test, fog
d3DDevice_->SetRenderState(D3DRS_ZENABLE, zTestEnable ? TRUE : FALSE);
d3DDevice_->SetRenderState(D3DRS_ZWRITEENABLE, zWriteEnable ? TRUE : FALSE);
d3DDevice_->SetRenderState(D3DRS_FOGENABLE, useFog && fogEnable_ ? TRUE : FALSE);
d3DDevice_->SetRenderState(D3DRS_FOGCOLOR, fogColor_);
// set blend type
SetBlendType(blendType);
// set vertex shader
d3DDevice_->SetVertexShader(meshVertexShader_);
// set shader constant
{
const D3DXMATRIX worldViewProjMatrix = worldMatrix * viewProjMatrix3D_;
d3DDevice_->SetVertexShaderConstantF(0, (const float*)&worldViewProjMatrix, 4);
}
{
D3DXMATRIX normalMatrix = worldMatrix;
normalMatrix._41 = normalMatrix._42 = normalMatrix._43 = 0.0f; // 平行移動成分を消去
if (D3DXMatrixInverse(&normalMatrix, nullptr, &normalMatrix))
{
D3DXMatrixTranspose(&normalMatrix, &normalMatrix);
} else
{
// 非正則のとき
// とりあえず単位行列入れておく
D3DXMatrixIdentity(&normalMatrix);
}
d3DDevice_->SetVertexShaderConstantF(4, (const float*)&normalMatrix, 4);
}
d3DDevice_->SetVertexShaderConstantF(12, &fogStart_, 1);
d3DDevice_->SetVertexShaderConstantF(13, &fogEnd_, 1);
// set vertex format
d3DDevice_->SetFVF(MeshVertex::Format);
for (const auto& mat : mesh->materials)
{
// set material
D3DXVECTOR4 amb = D3DXVECTOR4{ col.r * (mat.amb + mat.emi), col.g * (mat.amb + mat.emi), col.b * (mat.amb + mat.emi), col.a };
D3DXVECTOR4 dif = D3DXVECTOR4{ col.r * mat.dif, col.g * mat.dif, col.b * mat.dif, col.a };
d3DDevice_->SetVertexShaderConstantF(8, (const float*)&amb, 1);
d3DDevice_->SetVertexShaderConstantF(9, (const float*)&dif, 1);
// set light dir
D3DXVECTOR4 lightDir = { 0.0f, -1.0f, -1.0f, 0.0f };
D3DXVec4Normalize(&lightDir, &lightDir);
d3DDevice_->SetVertexShaderConstantF(10, (const float*)&lightDir, 1);
// set texture
d3DDevice_->SetTexture(0, mat.texture ? mat.texture->GetTexture() : nullptr);
// set pixel shader
if (pixelShader)
{
ID3DXEffect* effect = pixelShader->getEffect();
UINT passCnt;
effect->Begin(&passCnt, D3DXFX_DONOTSAVESTATE);
for (int i = 0; i < passCnt; i++)
{
effect->BeginPass(i);
d3DDevice_->DrawPrimitiveUP(D3DPT_TRIANGLELIST, mat.vertices.size() / 3, mat.vertices.data(), sizeof(MeshVertex));
effect->EndPass();
}
effect->End();
} else
{
d3DDevice_->SetPixelShader(nullptr);
d3DDevice_->DrawPrimitiveUP(D3DPT_TRIANGLELIST, mat.vertices.size() / 3, mat.vertices.data(), sizeof(MeshVertex));
}
}
d3DDevice_->SetVertexShader(nullptr);
d3DDevice_->SetPixelShader(nullptr);
}
void Renderer::SetViewProjMatrix2D(const D3DXMATRIX& view, const D3DXMATRIX& proj)
{
viewProjMatrix2D_ = view * proj;
}
void Renderer::SetForbidCameraViewProjMatrix2D(int screenWidth, int screenHeight)
{
Camera2D camera2D;
camera2D.Reset(0, 0);
D3DXMATRIX forbidCameraViewMatrix2D;
D3DXMATRIX forbidCameraProjMatrix2D;
camera2D.GenerateViewMatrix(&forbidCameraViewMatrix2D);
camera2D.GenerateProjMatrix(&forbidCameraProjMatrix2D, screenWidth, screenHeight, 0, 0);
forbidCameraViewProjMatrix2D_ = forbidCameraViewMatrix2D * forbidCameraProjMatrix2D;
}
void Renderer::SetViewProjMatrix3D(const D3DXMATRIX & view, const D3DXMATRIX & proj)
{
viewProjMatrix3D_ = view * proj;
}
void Renderer::SetViewProjMatrix3D(const D3DXMATRIX & view, const D3DXMATRIX & proj, const D3DXMATRIX & billboardMatrix)
{
viewProjMatrix3D_ = view * proj;
billboardViewProjMatrix3D_ = billboardMatrix * viewProjMatrix3D_;
}
void Renderer::SetBlendType(int type)
{
if (type == currentBlendType_) return;
switch (type)
{
case BLEND_ADD_RGB:
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
break;
case BLEND_ADD_ARGB:
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
break;
case BLEND_MULTIPLY:
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO);
break;
case BLEND_SUBTRACT:
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_REVSUBTRACT);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
break;
case BLEND_INV_DESTRGB:
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_INVDESTCOLOR);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
break;
case BLEND_ALPHA:
default:
d3DDevice_->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3DDevice_->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3DDevice_->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
break;
}
currentBlendType_ = type;
}
void Renderer::SetFilterType(int type) //FP FILTER
{
if (type == currentFilterType_) return;
switch (type)
{
case FILTER_NONE:
d3DDevice_->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_NONE);
d3DDevice_->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_NONE);
break;
case FILTER_LINEAR:
default:
d3DDevice_->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
d3DDevice_->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
break;
}
currentFilterType_ = type;
}
void Renderer::EnableScissorTest(const RECT& rect)
{
d3DDevice_->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
d3DDevice_->SetScissorRect(&rect);
}
void Renderer::DisableScissorTest()
{
d3DDevice_->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
}
void Renderer::SetFogEnable(bool enable)
{
fogEnable_ = enable;
if (enable) { SetFogParam(0, 0, 0, 0, 0); }
}
void Renderer::SetFogParam(float start, float end, int r, int g, int b)
{
fogEnable_ = true;
fogStart_ = start;
fogEnd_ = end;
fogColor_ = ColorRGB(r, g, b).ToD3DCOLOR(0xff);
}
}
| 37.381779 | 287 | 0.687982 | [
"mesh",
"3d"
] |
2e0fdef21fa17cedaff8105d65d1a91cf8bca7c4 | 5,601 | cpp | C++ | ExtremeCopy/App/UI/CptListBox.cpp | kevinwu1024/ExtremeCopy | de9ba1aef769d555d10916169ccf2570c69a8d01 | [
"Apache-2.0"
] | 67 | 2020-11-12T11:51:37.000Z | 2022-03-01T13:44:43.000Z | ExtremeCopy/App/UI/CptListBox.cpp | kevinwu1024/ExtremeCopy | de9ba1aef769d555d10916169ccf2570c69a8d01 | [
"Apache-2.0"
] | 4 | 2021-04-09T08:22:06.000Z | 2021-06-07T13:43:13.000Z | ExtremeCopy/App/UI/CptListBox.cpp | kevinwu1024/ExtremeCopy | de9ba1aef769d555d10916169ccf2570c69a8d01 | [
"Apache-2.0"
] | 12 | 2020-11-12T11:51:42.000Z | 2022-02-11T08:07:37.000Z | /****************************************************************************
Copyright (c) 2008-2020 Kevin Wu (Wu Feng)
github: https://github.com/kevinwu1024/ExtremeCopy
site: http://www.easersoft.com
Licensed under the Apache License, Version 2.0 License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/Apache-2.0
****************************************************************************/
#include "StdAfx.h"
#include "CptListBox.h"
#include <shellapi.h>
CptListBox::CptListBox(HWND hWnd)
{
}
CptListBox::~CptListBox(void)
{
}
void CptListBox::Attach(HWND hWnd)
{
CptCommCtrl::Attach(hWnd) ;
}
void CptListBox::UpdateHorizontalExtent()
{
if(m_hWnd!=NULL)
{
const int nItemCount = this->GetItemCount() ;
if(nItemCount==0)
{
::SendMessage(m_hWnd,LB_SETHORIZONTALEXTENT,0,0) ;
}
else
{
HDC hDevDC = ::GetDC(m_hWnd) ;
SIZE size ;
::memset(&size,0,sizeof(size)) ;
TCHAR* pStrBuf = new TCHAR[512] ;
pStrBuf[0] = 0;
int nWidth = 0 ;
int nLen = 0 ;
for(int i=0;i<nItemCount;++i)
{
if(this->GetString(i,pStrBuf)
&& ::GetTextExtentPoint32(hDevDC,pStrBuf,(int)::_tcslen(pStrBuf),&size))
{
if(size.cx>nWidth)
{
nWidth = size.cx ;
}
}
}
if(nWidth>0)
{
::SendMessage(m_hWnd,LB_SETHORIZONTALEXTENT,nWidth,0) ;
//SptRect rt ;
//::GetWindowRect(m_hWnd,rt.GetRECTPointer()) ;
//const int nOffset = nWidth-rt.GetWidth() ;
//if(nOffset>0)
//{
// ::SendMessage(m_hWnd,LB_SETHORIZONTALEXTENT,nOffset+10,0) ;
//}
//else
//{
// ::SendMessage(m_hWnd,LB_SETHORIZONTALEXTENT,0,0) ;
//}
}
delete [] pStrBuf ;
pStrBuf = NULL ;
::ReleaseDC(m_hWnd,hDevDC) ;
}
}
}
bool CptListBox::AddString(const TCHAR* pStr)
{
bool bRet = false ;
if(m_hWnd!=NULL && pStr!=NULL)
{
bRet = (CB_ERR!=::SendMessage(m_hWnd,LB_ADDSTRING,NULL,(LPARAM)pStr)) ;
if(bRet)
{
this->UpdateHorizontalExtent() ;
}
}
return bRet ;
}
bool CptListBox::DeleteString(const int nIndex)
{
bool bRet = false ;
if(m_hWnd!=NULL)
{
bRet = (CB_ERR!=::SendMessage(m_hWnd,LB_DELETESTRING,nIndex,NULL)) ;
if(bRet)
{
this->UpdateHorizontalExtent() ;
}
}
return bRet ;
}
bool CptListBox::GetString(int nIndex,TCHAR* pStr)
{
bool bRet = false ;
if(m_hWnd!=NULL && pStr!=NULL)
{
bRet = (CB_ERR!=::SendMessage(m_hWnd,LB_GETTEXT,nIndex,(LPARAM)pStr)) ;
}
return bRet ;
}
bool CptListBox::UpdateString(int nIndex,const TCHAR* lpStr)
{
bool bRet = false ;
if(nIndex>=0 && lpStr!=NULL)
{
const int nCount = this->GetItemCount() ;
if(nCount>=0 && nIndex<nCount)
{
if(this->DeleteString(nIndex))
{
bRet = InsertString(nIndex,lpStr) ;
}
}
}
if(bRet)
{
this->UpdateHorizontalExtent() ;
}
return bRet ;
}
bool CptListBox::InsertString(int nIndex,const TCHAR* lpStr)
{
bool bRet = false ;
if(m_hWnd!=NULL && lpStr!=NULL)
{
bRet = (CB_ERR!=::SendMessage(m_hWnd,LB_INSERTSTRING,nIndex,(LPARAM)lpStr)) ;
if(bRet)
{
this->UpdateHorizontalExtent() ;
}
}
return bRet ;
}
//bool CptListBox::SetString(int nIndex,const TCHAR* pStr)
//{
// bool bRet = false ;
//
// if(m_hWnd!=NULL && pStr!=NULL)
// {
// //bRet = (CB_ERR!=::SendMessage(m_hWnd,LB_SETTEXT,nIndex,(LPARAM)pStr)) ;
// }
//
// return bRet ;
//}
void CptListBox::Clear()
{
if(m_hWnd!=NULL)
{
::SendMessage(m_hWnd,LB_RESETCONTENT,NULL,NULL) ;
}
}
int CptListBox::GetSelectIndex()
{
int nRet = LB_ERR ;
if(m_hWnd!=NULL)
{
nRet = (int)::SendMessage(m_hWnd,LB_GETCURSEL,NULL,NULL) ;
}
return nRet ;
}
bool CptListBox::SetSelectIndex(int nIndex)
{
bool bRet = false ;
if(m_hWnd!=NULL)
{
bRet = (CB_ERR!=::SendMessage(m_hWnd,LB_SETCURSEL,nIndex,NULL)) ;
}
return bRet ;
}
int CptListBox::GetSelectCount()
{
int nRet = LB_ERR ;
if(m_hWnd!=NULL)
{
nRet = (int)::SendMessage(m_hWnd,LB_GETSELCOUNT,NULL,NULL) ;
}
return nRet ;
}
bool CptListBox::GetMultipleSelIndex(std::vector<int>& IndexVer)
{
bool bRet = false ;
int nSelCount = this->GetSelectCount() ;
if(nSelCount>0)
{
IndexVer.resize(nSelCount) ;
bRet = (::SendMessage(m_hWnd,LB_GETSELITEMS,nSelCount,(LPARAM)IndexVer.data())!=LB_ERR) ;
}
return bRet ;
}
int CptListBox::GetItemCount()
{
int nRet = -1 ;
if(m_hWnd!=NULL)
{
nRet = (int)::SendMessage(m_hWnd,LB_GETCOUNT,NULL,NULL) ;
}
return nRet ;
}
/**
int CptListBox::PreProcCtrlMsg(HWND hWnd,UINT nMsg,WPARAM wParam, LPARAM lParam)
{
int nRet = CptCommCtrl::PreProcCtrlMsg(hWnd,nMsg,wParam,lParam) ;
switch(nMsg)
{
//case WM_DROPFILES:
//{
// HDROP hDropInfo = (HDROP)wParam ;
// const int fileCount = ::DragQueryFile(hDropInfo, (UINT)-1, NULL, 0);
// TCHAR szFileName[MAX_PATH] = { 0 };
// TCHAR szListString[MAX_PATH] = { 0 };
// //if(hWnd==this->GetDlgItem(IDC_LIST_SOURCEFILE))
// {
// for (int i = 0; i < fileCount; ++i)
// {
// ::DragQueryFile(hDropInfo, i, szFileName, sizeof(szFileName));
// const int nListCount = this->GetItemCount() ;
// int j = 0 ;
// for(j=0;j<nListCount;++j)
// {
// szListString[0] = 0 ;
// this->GetString(j,szListString) ;
// CptString str1 = szListString ;
// CptString str2 = szFileName ;
// if(str1.CompareNoCase(str2)==0)
// {
// break ;
// }
// }
// if(j==nListCount)
// {
// this->AddString(szFileName) ;
// }
// }
// }
//
// ::DragFinish(hDropInfo) ;
//}
//return 0 ;
}
return nRet ;
}
/**/
| 17.448598 | 104 | 0.607927 | [
"vector"
] |
2e11d00f34ae845eb200b6f74e7cbf9772eaa728 | 2,439 | cpp | C++ | CHAPTER12/C12E12.cpp | lrpinnto/stroustrup-exercises | a471a0d7b49b51b7c26e005ff9e66f3f6db199dd | [
"MIT"
] | null | null | null | CHAPTER12/C12E12.cpp | lrpinnto/stroustrup-exercises | a471a0d7b49b51b7c26e005ff9e66f3f6db199dd | [
"MIT"
] | null | null | null | CHAPTER12/C12E12.cpp | lrpinnto/stroustrup-exercises | a471a0d7b49b51b7c26e005ff9e66f3f6db199dd | [
"MIT"
] | null | null | null | //CHAPTER 12 EX 12
//Needs debugging
#include "../sourcesgui/Graph.h"
#include "../sourcesgui/Simple_window.h"
#include <stdexcept>
#include <cmath>
//using namespace Graph_lib;
constexpr double PI {3.14159265};
//how to get expressions: https://fractional-calculus.com/super_ellipse.pdf
//http://www.cpp.re/forum/general/212070/
//parametric representation of an ellipse
//sin2(alfa)+cos2(alfa)=1
// |x/a|^m+|y/b|^n = 1 m,n >0 <=> x^m/a^m + y^n/b^n = 1
// sin2(rads) = x^m/a^m <=> x = asin(rads)^2/m , y = bcos(rads)^2/n (assuming positive x, y ,m,n)
vector<Point> get_points(double a, double b, double m, double n, int N)
{
double smallest_rad_division = 2*PI/N; //dividing full circle into N amount of points
vector<Point> list; //make a list of all the calculated points
for (int i = 0; i < N; i++) //go through all rad angles of the full circle
{
double radangle = smallest_rad_division * i;
list.push_back(Point{pow(a*sin(radangle),2/m),pow(b*cos(radangle),2/n)});
}
return list;
}
int main()
try
{
Point tl {0,0};
Simple_window win {tl,1600,900,"Window"};
int center_x {1600/2};
int center_y {900/2};
double a,b,m,n;
int N;
cout<<"Enter a,b (more means a larger radius),m,n (more increases \"squariness\"),N where N is the superellipse resolution for |x/a|^m+|y/b|^n = 1. All ints separated by space: ";
cin>>a>>b>>m>>n>>N;
if ((a <= 0 || b <= 0) || (m <= 0 || n <= 0)) error("Positive args required.");
//Axis
Axis xa {Axis::x, Point{center_x,center_y},280,10,"x axis"}; //for some reason, the x axis label is set to move according to
xa.label.move(970,0); //fixes said issue
win.attach(xa); //the length of the axis divided by 3 unlike the y axis which moves
win.set_label("Canvas #2"); //according to the Point coordinate. Probably a bug
Axis ya {Axis::y, Point{center_x,center_y},280,10,"y axis"};
ya.set_color(Color::cyan);
ya.label.set_color(Color::dark_red);
win.attach(ya);
win.set_label("Canvas #3");
Closed_polyline poly_rect;
for(Point p : get_points(a,b,m,n,N)) poly_rect.add({p.x+center_x,p.y+center_y});
win.attach(poly_rect);
win.wait_for_button();
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
catch(...)
{
// some more error reporting
return 2;
}
| 34.352113 | 183 | 0.616646 | [
"vector"
] |
2e165e7670b003e50ed77f5fc75e20aa6698b0d3 | 1,639 | cpp | C++ | src/SFML-utils/map/Tile.cpp | Krozark/SFML-utils | c2f169faa7f3ce0aa6e23991d21796dca01944be | [
"BSD-2-Clause"
] | 23 | 2016-03-05T11:27:53.000Z | 2021-05-29T19:08:26.000Z | src/SFML-utils/map/Tile.cpp | Krozark/SFML-utils | c2f169faa7f3ce0aa6e23991d21796dca01944be | [
"BSD-2-Clause"
] | 11 | 2015-03-12T10:14:06.000Z | 2017-11-24T14:34:41.000Z | src/SFML-utils/map/Tile.cpp | Krozark/SFML-utils | c2f169faa7f3ce0aa6e23991d21796dca01944be | [
"BSD-2-Clause"
] | 9 | 2016-04-10T22:28:45.000Z | 2021-11-27T08:48:21.000Z | #include <SFML-utils/map/Tile.hpp>
#include <SFML-utils/map/geometry/Geometry.hpp>
namespace sfutils
{
namespace map
{
Tile::Tile(const geometry::Geometry& geometry,const sf::Vector2i& pos)
{
_shape = geometry.getShape();
_shape.setOutlineColor(sf::Color(128,128,128,100));
_shape.setOutlineThickness(2.f/geometry.getScale());
sf::Vector2f p = geometry.mapCoordsToPixel(pos);
_shape.setPosition(p);
}
Tile::~Tile()
{
}
void Tile::setFillColor(const sf::Color& color)
{
_shape.setFillColor(color);
}
void Tile::setPosition(float x,float y)
{
_shape.setPosition(x,y);
}
void Tile::setPosition(const sf::Vector2f& pos)
{
_shape.setPosition(pos);
}
sf::Vector2f Tile::getPosition()const
{
return _shape.getPosition();
}
void Tile::setTexture(const sf::Texture *texture,bool resetRect)
{
_shape.setTexture(texture,resetRect);
}
void Tile::setTextureRect(const sf::IntRect& rect)
{
_shape.setTextureRect(rect);
}
sf::FloatRect Tile::getGlobalBounds()const
{
return _shape.getGlobalBounds();
}
sf::FloatRect Tile::getLocalBounds()const
{
return _shape.getLocalBounds();
}
void Tile::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(_shape,states);
}
}
}
| 23.753623 | 80 | 0.539963 | [
"geometry"
] |
2e1823a264c292ad9dfb385b9d8d860e516fbea2 | 24,582 | hpp | C++ | kernel/src/utils/SiconosTools/SiconosGraph.hpp | fperignon/sandbox | 649f09d6db7bbd84c2418de74eb9453c0131f070 | [
"Apache-2.0"
] | null | null | null | kernel/src/utils/SiconosTools/SiconosGraph.hpp | fperignon/sandbox | 649f09d6db7bbd84c2418de74eb9453c0131f070 | [
"Apache-2.0"
] | null | null | null | kernel/src/utils/SiconosTools/SiconosGraph.hpp | fperignon/sandbox | 649f09d6db7bbd84c2418de74eb9453c0131f070 | [
"Apache-2.0"
] | null | null | null | /* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2020 INRIA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file SiconosGraph.hpp
Template class to define a graph of Siconos object.
Note: this needs documentation
*/
#ifndef SICONOS_GRAPH_HPP
#define SICONOS_GRAPH_HPP
#ifndef BOOST_NO_HASH
#define BOOST_NO_HASH
#endif
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <SiconosConfig.h>
#if !defined(SICONOS_USE_MAP_FOR_HASH)
#include <unordered_map>
#else
#include <map>
#endif
#include <limits>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/graph/directed_graph.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/static_assert.hpp>
#include "SiconosSerialization.hpp"
enum vertex_properties_t { vertex_properties };
enum edge_properties_t { edge_properties };
enum graph_properties_t { graph_properties };
// We need those with Boost >= 1.51
// vertex_bundle_t and edge_bundle_t are already defined in
// boost/pending/property.hpp
enum vertex_siconos_bundle_t { vertex_siconos_bundle };
enum edge_siconos_bundle_t { edge_siconos_bundle };
namespace boost
{
using std::size_t;
BOOST_INSTALL_PROPERTY(vertex, properties);
BOOST_INSTALL_PROPERTY(edge, properties);
BOOST_INSTALL_PROPERTY(graph, properties);
BOOST_INSTALL_PROPERTY(vertex, siconos_bundle);
BOOST_INSTALL_PROPERTY(edge, siconos_bundle);
}
template < class V, class E, class VProperties,
class EProperties, class GProperties >
class SiconosGraph
{
public:
/* note : OutEdgeList as multisetS => cannot compile remove_out_edge_if :
/usr/include/boost/graph/detail/adjacency_list.hpp:440: error: passing 'const ... */
typedef boost::adjacency_list < boost::listS, boost::listS,
boost::undirectedS > proxy_graph_t;
typedef typename
boost::graph_traits<proxy_graph_t>::edge_descriptor EDescriptor;
typedef typename
boost::graph_traits<proxy_graph_t>::vertex_descriptor VDescriptor;
typedef boost::adjacency_list <
boost::listS, boost::listS, boost::undirectedS,
boost::property
< vertex_siconos_bundle_t, V,
boost::property <
boost::vertex_color_t ,
boost::default_color_type ,
boost::property < boost::vertex_index_t,
size_t,
boost::property < vertex_properties_t,
VProperties
> > > > ,
boost::property
< edge_siconos_bundle_t, E,
boost::property <
boost::edge_color_t ,
boost::default_color_type ,
boost::property < boost::edge_index_t,
size_t,
boost::property < edge_properties_t ,
EProperties
> > > > ,
boost::property < graph_properties_t, GProperties > >
graph_t;
typedef V vertex_t;
typedef E edge_t;
typedef typename
boost::graph_traits<graph_t>::edge_iterator EIterator;
typedef typename
boost::graph_traits<graph_t>::vertex_iterator VIterator;
// typedef typename
// graph_traits<graph_t>::edge_descriptor EDescriptor;
// typedef typename
// graph_traits<graph_t>::vertex_descriptor VDescriptor;
typedef typename
boost::graph_traits<graph_t>::out_edge_iterator OEIterator;
typedef typename
boost::graph_traits<graph_t>::adjacency_iterator AVIterator;
typedef typename
boost::property_map<graph_t, edge_siconos_bundle_t >::type EBundleAccess;
typedef typename
boost::property_map<graph_t, vertex_siconos_bundle_t >::type VBundleAccess;
typedef typename
boost::property_map<graph_t, boost::edge_color_t >::type EColorAccess;
typedef typename
boost::property_map<graph_t, boost::vertex_color_t >::type VColorAccess;
typedef typename
boost::property_map<graph_t, boost::edge_index_t >::type EIndexAccess;
typedef typename
boost::property_map<graph_t, boost::vertex_index_t >::type VIndexAccess;
typedef typename
boost::property_map<graph_t, edge_properties_t >::type EPropertiesAccess;
typedef typename
boost::property_map<graph_t, vertex_properties_t >::type VPropertiesAccess;
// Need some Base, otherwise, we have a compile error with boost >= 1.51
// typedef typename
// boost::property_map<graph_t, graph_properties_t >::type GraphPropertiesAccess;
#if !defined(SICONOS_USE_MAP_FOR_HASH)
typedef typename std::unordered_map<V, VDescriptor> VMap;
#else
typedef typename std::map<V, VDescriptor> VMap;
#endif
int _stamp;
VMap vertex_descriptor;
protected:
/** serialization hooks
*/
typedef void serializable;
template<typename Archive>
friend void siconos_io(Archive&, SiconosGraph < V, E, VProperties, EProperties,
GProperties > &,
const unsigned int);
friend class boost::serialization::access;
graph_t g;
private:
SiconosGraph(const SiconosGraph&);
public:
/** default constructor
*/
SiconosGraph() : _stamp(0)
{
};
~SiconosGraph()
{
g.clear();
};
const graph_t& storage() const
{
return g;
}
std::pair<EDescriptor, bool>
edge(VDescriptor u, VDescriptor v) const
{
return boost::edge(u, v, g);
}
bool edge_exists(const VDescriptor& vd1, const VDescriptor& vd2) const
{
bool ret = false;
EDescriptor tmped;
std::tie(tmped, ret) = edge(vd1, vd2);
#ifndef NDEBUG
bool check_ret = false;
AVIterator avi, aviend;
for (std::tie(avi, aviend) = adjacent_vertices(vd1);
avi != aviend; ++avi)
{
if (*avi == vd2)
{
check_ret = true;
break;
}
assert(is_vertex(bundle(*avi)));
assert(bundle(descriptor(bundle(*avi))) == bundle(*avi));
}
assert(ret == check_ret);
#endif
return ret;
}
/* parallel edges : edge_range needs multisetS as
OutEdgesList and with multisetS remove_out_edges_if cannot
compile as with listS.
This is only needed for AdjointGraph where only 2 edges may be in
common which correspond to the source and target in primal graph
*/
std::pair<EDescriptor, EDescriptor>
edges(VDescriptor u, VDescriptor v) const
{
// BOOST_STATIC_ASSERT((GProperties::is_adjoint_graph));
OEIterator oei, oeiend;
bool ifirst = false;
bool isecond = false;
EDescriptor first, second;
for (std::tie(oei, oeiend) = out_edges(u); oei != oeiend; ++oei)
{
if (target(*oei) == v)
{
if (!ifirst)
{
ifirst = true;
first = *oei;
}
else
{
isecond = true;
second = *oei;
break;
}
}
}
if (ifirst && isecond)
{
if (index(first) < index(second))
{
return std::pair<EDescriptor, EDescriptor>(first, second);
}
else
{
return std::pair<EDescriptor, EDescriptor>(second, first);
}
}
else if (ifirst)
{
return std::pair<EDescriptor, EDescriptor>(first, first);
}
else
{
throw(1);
}
}
bool is_edge(const VDescriptor& vd1, const VDescriptor& vd2,
const E& e_bundle) const
{
bool found = false;
OEIterator oei, oeiend;
for (std::tie(oei, oeiend) = out_edges(vd1);
oei != oeiend; ++oei)
{
if (target(*oei) == vd2 && bundle(*oei) == e_bundle)
{
found = true;
break;
}
}
return found;
}
bool adjacent_vertex_exists(const VDescriptor& vd) const
{
bool ret = false;
VIterator vi, viend;
for (std::tie(vi, viend) = vertices(); vi != viend; ++vi)
{
assert(is_vertex(bundle(*vi)));
assert(bundle(descriptor(bundle(*vi))) == bundle(*vi));
ret = edge_exists(vd, *vi);
if (ret) break;
}
return ret;
}
size_t size() const
{
return boost::num_vertices(g);
};
size_t vertices_number() const
{
return boost::num_vertices(g);
};
size_t edges_number() const
{
return boost::num_edges(g);
};
inline V& bundle(const VDescriptor& vd)
{
return boost::get(vertex_siconos_bundle, g)[vd];
};
inline const V& bundle(const VDescriptor& vd) const
{
return boost::get(vertex_siconos_bundle, g)[vd];
};
inline E& bundle(const EDescriptor& ed)
{
return boost::get(edge_siconos_bundle, g)[ed];
};
inline const E& bundle(const EDescriptor& ed) const
{
return boost::get(edge_siconos_bundle, g)[ed];
};
inline boost::default_color_type& color(const VDescriptor& vd)
{
return boost::get(boost::vertex_color, g)[vd];
};
inline const boost::default_color_type& color(const VDescriptor& vd) const
{
return boost::get(boost::vertex_color, g)[vd];
};
inline boost::default_color_type& color(const EDescriptor& ed)
{
return boost::get(boost::edge_color, g)[ed];
};
inline const boost::default_color_type& color(const EDescriptor& ed) const
{
return boost::get(boost::edge_color, g)[ed];
};
inline GProperties& properties()
{
return boost::get_property(g, graph_properties);
};
inline size_t& index(const VDescriptor& vd)
{
return boost::get(boost::vertex_index, g)[vd];
};
inline const size_t& index(const VDescriptor& vd) const
{
return boost::get(boost::vertex_index, g)[vd];
};
inline size_t& index(const EDescriptor& ed)
{
return boost::get(boost::edge_index, g)[ed];
};
inline const size_t& index(const EDescriptor& ed) const
{
return boost::get(boost::edge_index, g)[ed];
};
inline VProperties& properties(const VDescriptor& vd)
{
return boost::get(vertex_properties, g)[vd];
};
inline EProperties& properties(const EDescriptor& ed)
{
return boost::get(edge_properties, g)[ed];
};
// inline VDescriptor& descriptor0(const VDescriptor& vd)
// {
// return get(vertex_descriptor0, g)[vd];
// }
// inline EDescriptor& descriptor0(const EDescriptor& ed)
// {
// return get(edge_descriptor0, g)[ed];
// }
inline bool is_vertex(const V& vertex) const
{
return (vertex_descriptor.find(vertex) != vertex_descriptor.end());
}
inline const VDescriptor& descriptor(const V& vertex) const
{
assert(size() == vertex_descriptor.size());
assert(vertex_descriptor.find(vertex) != vertex_descriptor.end());
return (*vertex_descriptor.find(vertex)).second;
}
inline std::pair<VIterator, VIterator> vertices() const
{
return boost::vertices(g);
};
inline VIterator begin() const
{
VIterator vi, viend;
std::tie(vi, viend) = vertices();
return vi;
}
inline VIterator end() const
{
VIterator vi, viend;
std::tie(vi, viend) = vertices();
return viend;
}
inline std::pair<AVIterator, AVIterator> adjacent_vertices(const VDescriptor& vd) const
{
return boost::adjacent_vertices(vd, g);
};
inline std::pair<EIterator, EIterator> edges() const
{
return boost::edges(g);
};
inline std::pair<OEIterator, OEIterator> out_edges(const VDescriptor& vd) const
{
return boost::out_edges(vd, g);
};
inline VDescriptor target(const EDescriptor& ed) const
{
return boost::target(ed, g);
};
inline VDescriptor source(const EDescriptor& ed) const
{
return boost::source(ed, g);
};
VDescriptor add_vertex(const V& vertex_bundle)
{
assert(vertex_descriptor.size() == size()) ;
VDescriptor new_vertex_descriptor;
typename VMap::iterator current_vertex_iterator =
vertex_descriptor.find(vertex_bundle);
if (current_vertex_iterator == vertex_descriptor.end())
{
new_vertex_descriptor = boost::add_vertex(g);
assert(vertex(size() - 1, g) == new_vertex_descriptor);
assert(size() == vertex_descriptor.size() + 1);
vertex_descriptor[vertex_bundle] = new_vertex_descriptor;
assert(size() == vertex_descriptor.size());
bundle(new_vertex_descriptor) = vertex_bundle;
assert(descriptor(vertex_bundle) == new_vertex_descriptor);
assert(bundle(descriptor(vertex_bundle)) == vertex_bundle);
index(new_vertex_descriptor) = std::numeric_limits<size_t>::max() ;
return new_vertex_descriptor;
}
else
{
assert(descriptor(vertex_bundle) == current_vertex_iterator->second);
assert(bundle(descriptor(vertex_bundle)) == vertex_bundle);
return current_vertex_iterator->second;
}
assert(false) ;
}
template<class G> void copy_vertex(const V& vertex_bundle, G& og)
{
// is G similar ?
BOOST_STATIC_ASSERT((boost::is_same
<typename G::vertex_t, vertex_t>::value));
BOOST_STATIC_ASSERT((boost::is_same
<typename G::edge_t, edge_t>::value));
assert(og.is_vertex(vertex_bundle));
VDescriptor descr = add_vertex(vertex_bundle);
properties(descr) = og.properties(og.descriptor(vertex_bundle));
// descriptor0(descr) = og.descriptor(vertex_bundle);
assert(bundle(descr) == vertex_bundle);
// edges copy as in boost::subgraph
typename G::OEIterator ogoei, ogoeiend;
for (std::tie(ogoei, ogoeiend) =
og.out_edges(og.descriptor(vertex_bundle));
ogoei != ogoeiend; ++ogoei)
{
typename G::VDescriptor ognext_descr = og.target(*ogoei);
assert(og.is_vertex(og.bundle(ognext_descr)));
// target in graph ?
if (is_vertex(og.bundle(ognext_descr)))
{
assert(bundle(descriptor(og.bundle(ognext_descr)))
== og.bundle(ognext_descr));
EDescriptor edescr =
add_edge(descr, descriptor(og.bundle(ognext_descr)),
og.bundle(*ogoei));
properties(edescr) = og.properties(*ogoei);
// descriptor0(edescr) = *ogoei;
assert(bundle(edescr) == og.bundle(*ogoei));
}
}
}
void remove_vertex(const V& vertex_bundle)
{
assert(is_vertex(vertex_bundle));
assert(vertex_descriptor.size() == size());
assert(bundle(descriptor(vertex_bundle)) == vertex_bundle);
VDescriptor vd = descriptor(vertex_bundle);
/* debug */
#ifndef NDEBUG
assert(adjacent_vertices_ok());
#endif
boost::clear_vertex(vd, g);
/* debug */
#ifndef NDEBUG
assert(adjacent_vertices_ok());
assert(!adjacent_vertex_exists(vd));
#endif
boost::remove_vertex(vd, g);
assert(vertex_descriptor.size() == (size() + 1));
vertex_descriptor.erase(vertex_bundle);
/* debug */
#ifndef NDEBUG
assert(adjacent_vertices_ok());
assert(vertex_descriptor.size() == size());
assert(!is_vertex(vertex_bundle));
assert(state_assert());
#endif
}
EDescriptor add_edge(const VDescriptor& vd1,
const VDescriptor& vd2,
const E& e_bundle)
{
EDescriptor new_edge;
bool inserted;
assert(is_vertex(bundle(vd1)));
assert(is_vertex(bundle(vd2)));
assert(descriptor(bundle(vd1)) == vd1);
assert(descriptor(bundle(vd2)) == vd2);
assert(!is_edge(vd1, vd2, e_bundle));
std::tie(new_edge, inserted) = boost::add_edge(vd1, vd2, g);
// During a gdb session, I saw that inserted is always going to be true ...
// This check is therefore unnecessary.
assert(inserted);
index(new_edge) = std::numeric_limits<size_t>::max();
bundle(new_edge) = e_bundle;
assert(is_edge(vd1, vd2, e_bundle));
return new_edge;
}
/* note : bgl self loop are a nightmare
seg fault with self-loop ...
https://svn.boost.org/trac/boost/ticket/4622
try a patch r65198 on clear vertex but loop remains and stranges
things occur...
solution => put self loop info in VProperties (i.e outside graph
structure)
*/
template<class AdjointG>
std::pair<EDescriptor, typename AdjointG::VDescriptor>
add_edge(const VDescriptor& vd1,
const VDescriptor& vd2,
const E& e_bundle,
AdjointG& ag)
{
// adjoint static assertions
BOOST_STATIC_ASSERT((boost::is_same
<typename AdjointG::vertex_t, edge_t>::value));
BOOST_STATIC_ASSERT((boost::is_same
<typename AdjointG::edge_t, vertex_t>::value));
EDescriptor new_ed = add_edge(vd1, vd2, e_bundle);
typename AdjointG::VDescriptor new_ve = ag.add_vertex(e_bundle);
assert(bundle(new_ed) == ag.bundle(new_ve));
assert(ag.size() == edges_number());
// better to build a range [vd1,vd2] or [vd1]...
bool endl = false;
for (VDescriptor vdx = vd1; !endl; vdx = vd2)
{
assert(vdx == vd1 || vdx == vd2);
if (vdx == vd2) endl = true;
#if !defined(SICONOS_USE_MAP_FOR_HASH)
std::unordered_map<E, EDescriptor> Edone;
#else
std::map<E, EDescriptor> Edone;
#endif
OEIterator ied, iedend;
for (std::tie(ied, iedend) = out_edges(vdx);
ied != iedend; ++ied)
{
if (Edone.find(bundle(*ied)) == Edone.end())
{
Edone[bundle(*ied)] = *ied;
assert(source(*ied) == vdx);
if (*ied != new_ed)
// so this is another edge
{
assert(bundle(*ied) != e_bundle);
assert(ag.bundle(ag.descriptor(bundle(*ied))) == bundle(*ied));
assert(ag.is_vertex(bundle(*ied)));
assert(new_ve != ag.descriptor(bundle(*ied)));
assert(!ag.is_edge(new_ve, ag.descriptor(bundle(*ied)),
bundle(vdx)));
typename AdjointG::EDescriptor aed =
ag.add_edge(new_ve, ag.descriptor(bundle(*ied)),
bundle(vdx));
assert(ag.bundle(aed) == bundle(vdx));
// assert(ag.bundle(ag.add_edge(new_ve, ag.descriptor(bundle(*ied)), bundle(vdx))) == bundle(vdx));
}
}
}
}
assert(ag.size() == edges_number());
return std::pair<EDescriptor, typename AdjointG::VDescriptor>(new_ed,
new_ve);
}
void remove_edge(const EDescriptor& ed)
{
assert(adjacent_vertex_exists(target(ed)));
assert(adjacent_vertex_exists(source(ed)));
boost::remove_edge(ed, g);
/* debug */
#ifndef NDEBUG
assert(state_assert());
#endif
}
template<class AdjointG>
void remove_edge(const EDescriptor& ed, AdjointG& ag)
{
// adjoint static assertions
BOOST_STATIC_ASSERT((boost::is_same
<typename AdjointG::vertex_t, edge_t>::value));
BOOST_STATIC_ASSERT((boost::is_same
<typename AdjointG::edge_t, vertex_t>::value));
assert(ag.size() == edges_number());
assert(bundle(ed) == ag.bundle(ag.descriptor(bundle(ed))));
remove_vertex(ag.bundle(ag.descriptor(bundle(ed))));
remove_edge(ed);
assert(ag.size() == edges_number());
/* debug */
#ifndef NDEBUG
assert(state_assert());
#endif
}
/** Remove all the out-edges of vertex u for which the predicate p
* returns true. This expression is only required when the graph
* also models IncidenceGraph.
*/
template<class Predicate>
void remove_out_edge_if(const VDescriptor& vd,
const Predicate& pred)
// Predicate pred)
{
BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<graph_t>));
BOOST_CONCEPT_ASSERT((boost::MutableGraphConcept<graph_t>));
boost::remove_out_edge_if(vd, pred, g);
/* workaround on multisetS (tested on Disks : ok)
multiset allows for member removal without invalidating iterators
OEIterator oei,oeiend;
for(std::tie(oei,oeiend)=out_edges(vd); oei!=oeiend; ++oei)
{
if (pred(*oei))
{
remove_edge(*oei);
}
}
*/
/* debug */
#ifndef NDEBUG
assert(state_assert());
#endif
}
/** Remove all the in-edges of vertex u for which the predicate p
* returns true. This expression is only required when the graph
* also models IncidenceGraph.
*/
template<class Predicate>
void remove_in_edge_if(const VDescriptor& vd,
const Predicate& pred)
// Predicate pred)
{
BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<graph_t>));
BOOST_CONCEPT_ASSERT((boost::MutableGraphConcept<graph_t>));
boost::remove_in_edge_if(vd, pred, g);
/* debug */
#ifndef NDEBUG
assert(state_assert());
#endif
}
/** Remove all the in-edges of vertex u for which the predicate p
* returns true. This expression is only required when the graph
* also models IncidenceGraph.
*/
template<class Predicate>
void remove_edge_if(const VDescriptor& vd,
const Predicate& pred)
// Predicate pred)
{
BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<graph_t>));
BOOST_CONCEPT_ASSERT((boost::MutableGraphConcept<graph_t>));
boost::remove_edge_if(pred, g);
/* debug */
#ifndef NDEBUG
assert(state_assert());
#endif
}
int stamp() const
{
return _stamp;
}
void update_vertices_indices()
{
VIterator vi, viend;
size_t i;
for (std::tie(vi, viend) = boost::vertices(g), i = 0;
vi != viend; ++vi, ++i)
{
index(*vi) = i;
}
_stamp++;
};
void update_edges_indices()
{
EIterator ei, eiend;
size_t i;
for (std::tie(ei, eiend) = boost::edges(g), i = 0;
ei != eiend; ++ei, ++i)
{
index(*ei) = i;
}
_stamp++;
};
void clear()
{
g.clear();
vertex_descriptor.clear();
};
VMap vertex_descriptor_map() const
{
return vertex_descriptor;
};
void display() const
{
std::cout << "vertices number :" << vertices_number() << std::endl;
std::cout << "edges number :" << edges_number() << std::endl;
VIterator vi, viend;
for (std::tie(vi, viend) = vertices();
vi != viend; ++vi)
{
std::cout << "vertex :"
<< *vi
<< ", bundle :"
<< bundle(*vi)
<< ", index : "
<< index(*vi)
<< ", color : "
<< color(*vi);
OEIterator oei, oeiend, next;
for (std::tie(oei, oeiend) = out_edges(*vi);
oei != oeiend; ++oei)
{
std::cout << "---"
<< bundle(*oei)
<< "-->"
<< "bundle : "
<< bundle(target(*oei))
<< ", index : "
<< index(target(*oei))
<< ", color : "
<< color(target(*oei));
}
std::cout << std::endl;
}
}
/* debug */
#ifndef SWIG
#ifndef NDEBUG
bool state_assert() const
{
VIterator vi, viend;
for (std::tie(vi, viend) = vertices(); vi != viend; ++vi)
{
assert(is_vertex(bundle(*vi)));
assert(bundle(descriptor(bundle(*vi))) == bundle(*vi));
OEIterator ei, eiend;
for (std::tie(ei, eiend) = out_edges(*vi);
ei != eiend; ++ei)
{
assert(is_vertex(bundle(target(*ei))));
assert(source(*ei) == *vi);
}
AVIterator avi, aviend;
for (std::tie(avi, aviend) = adjacent_vertices(*vi);
avi != aviend; ++avi)
{
assert(is_vertex(bundle(*avi)));
assert(bundle(descriptor(bundle(*avi))) == bundle(*avi));
}
}
return true;
}
bool adjacent_vertices_ok() const
{
VIterator vi, viend;
for (std::tie(vi, viend) = vertices(); vi != viend; ++vi)
{
assert(is_vertex(bundle(*vi)));
assert(bundle(descriptor(bundle(*vi))) == bundle(*vi));
AVIterator avi, aviend;
for (std::tie(avi, aviend) = adjacent_vertices(*vi);
avi != aviend; ++avi)
{
assert(is_vertex(bundle(*avi)));
assert(bundle(descriptor(bundle(*avi))) == bundle(*avi));
}
}
return true;
}
#endif
#endif
};
#endif
| 25.290123 | 115 | 0.622122 | [
"object"
] |
2e1a47bf3341dcc44c3c33bf68e1e66ea3556bb4 | 955 | cpp | C++ | CH03/06.cpp | hassec/cracking_the_coding_interview_4thED | 446ab759fb2bc9d2236521cc71e4de9a1aead2c7 | [
"MIT"
] | null | null | null | CH03/06.cpp | hassec/cracking_the_coding_interview_4thED | 446ab759fb2bc9d2236521cc71e4de9a1aead2c7 | [
"MIT"
] | null | null | null | CH03/06.cpp | hassec/cracking_the_coding_interview_4thED | 446ab759fb2bc9d2236521cc71e4de9a1aead2c7 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <random>
#include <stack>
void sort_stack( std::stack<int>& stack )
{
std::stack<int> buffer{};
while ( !stack.empty() ) {
int val = stack.top();
stack.pop();
while ( !buffer.empty() && buffer.top() < val ) {
stack.push( buffer.top() );
buffer.pop();
}
buffer.push( val );
}
stack = std::move( buffer );
}
int main()
{
std::stack<int> to_sort{};
// no need to seed with random_device for this
std::mt19937 g( 1234 );
// a bit more complicated but this way I know I should get 0..9 as result
// instead of random numbers in sorted order
std::vector<int> vec( 10 );
std::iota( begin( vec ), end( vec ), 0 );
std::shuffle( begin( vec ), end( vec ), g );
for ( auto const val : vec ) {
to_sort.push( val );
}
sort_stack( to_sort );
while ( !to_sort.empty() ) {
std::cout << to_sort.top() << std::endl;
to_sort.pop();
}
}
| 19.895833 | 75 | 0.581152 | [
"vector"
] |
2e1b306bdf6b0e1732b4a609929c521dd3901df8 | 893 | cpp | C++ | common.cpp | JohnGlassmyer/esp-watergate | d9d9e62828106372ce1b52902f1ac49246e81171 | [
"MIT"
] | 1 | 2021-05-24T19:43:47.000Z | 2021-05-24T19:43:47.000Z | common.cpp | JohnGlassmyer/esp-watergate | d9d9e62828106372ce1b52902f1ac49246e81171 | [
"MIT"
] | null | null | null | common.cpp | JohnGlassmyer/esp-watergate | d9d9e62828106372ce1b52902f1ac49246e81171 | [
"MIT"
] | null | null | null | #include <string>
#include "common.h"
std::vector<std::string>
splitString(std::string const &string, char const *delimiterChars) {
std::vector<std::string> segmentStrings;
if (string.find_first_of(delimiterChars) == 0) {
// recognize zero-length segment at start of string
segmentStrings.push_back("");
}
size_t start = 0;
size_t end = 0;
while (start != std::string::npos) {
start = string.find_first_not_of(delimiterChars, end);
if (start != std::string::npos) {
// recognize delimited segment
end = string.find_first_of(delimiterChars, start);
if (end == std::string::npos) {
end = string.length();
}
segmentStrings.push_back(string.substr(start, end - start));
}
}
if (string.find_last_of(delimiterChars) == string.length() - 1) {
// recognize zero-length segment at end of string
segmentStrings.push_back("");
}
return segmentStrings;
}
| 24.805556 | 68 | 0.690929 | [
"vector"
] |
2e1c91e4407080fb747c82c75725f3651b06450e | 21,548 | cpp | C++ | blingfiretools/blingfiretokdll/blingfiretokdll.cpp | mauna-ai/BlingFire | f55425c6c1bae92bcf5cafd35a1ea9e66218a2fe | [
"MIT"
] | null | null | null | blingfiretools/blingfiretokdll/blingfiretokdll.cpp | mauna-ai/BlingFire | f55425c6c1bae92bcf5cafd35a1ea9e66218a2fe | [
"MIT"
] | null | null | null | blingfiretools/blingfiretokdll/blingfiretokdll.cpp | mauna-ai/BlingFire | f55425c6c1bae92bcf5cafd35a1ea9e66218a2fe | [
"MIT"
] | null | null | null | #include "FAConfig.h"
#include "FALimits.h"
#include "FAUtf8Utils.h"
#include "FAImageDump.h"
#include "FAWbdConfKeeper.h"
#include "FALDB.h"
#include "FALexTools_t.h"
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <mutex>
#include <assert.h>
/*
This library provides easy interface to sentence and word-breaking functionality
which can be used in C#, Python, Perl, etc.
Also the goal is to reduce dependecies and provide the same library available
on Windows, Linux, etc.
*/
// defines g_dumpBlingFireTokLibWbdData, the sources of this data is SearchGold\deploy\builds\data\IndexGenData\ldbsrc\ldb\tp3\wbd
#include "BlingFireTokLibWbdData.cxx"
// defines g_dumpBlingFireTokLibSbdData, the sources of this data is SearchGold\deploy\builds\data\IndexGenData\ldbsrc\ldb\tp3\sbd
#include "BlingFireTokLibSbdData.cxx"
// version of this binary and the algo logic
#define BLINGFIRETOK_MAJOR_VERSION_NUM 5
#define BLINGFIRETOK_MINOR_VERSION_NUM 4
// constant data objects
FALDB g_WbdLdb;
FALDB g_SbdLdb;
FAWbdConfKeeper g_WbdConf;
FAWbdConfKeeper g_SbdConf;
// constant processors
FALexTools_t < int > g_Wbd;
FALexTools_t < int > g_Sbd;
const int WBD_IGNORE_TAG = 4;
// flag indicating the one-time initialization is done
volatile bool g_fInitialized = false;
std::mutex g_InitializationMutex;
//
// returns the current version of the algo
//
extern "C"
const int GetBlingFireTokVersion()
{
return (BLINGFIRETOK_MAJOR_VERSION_NUM * 1000) + BLINGFIRETOK_MINOR_VERSION_NUM;
}
// does initialization
void InitializeWbdSbd()
{
const int * pValues = NULL;
int iSize = 0;
// initialize WBD
g_WbdLdb.SetImage(g_dumpBlingFireTokLibWbdData);
pValues = NULL;
iSize = g_WbdLdb.GetHeader()->Get(FAFsmConst::FUNC_WBD, &pValues);
g_WbdConf.Initialize(&g_WbdLdb, pValues, iSize);
g_Wbd.SetConf(&g_WbdConf);
// initialize SBD
g_SbdLdb.SetImage(g_dumpBlingFireTokLibSbdData);
pValues = NULL;
iSize = g_SbdLdb.GetHeader()->Get(FAFsmConst::FUNC_WBD, &pValues);
g_SbdConf.Initialize(&g_SbdLdb, pValues, iSize);
g_Sbd.SetConf(&g_SbdConf);
}
inline int FAGetFirstNonWhiteSpace(int * pStr, const int StrLen)
{
for (int i = 0; i < StrLen; ++i)
{
int C = pStr[i];
// WHITESPACE [\x0004-\x0020\x007F-\x009F\x00A0\x2000-\x200B\x200E\x200F\x202F\x205F\x2060\x2420\x2424\x3000\xFEFF]
if (C <= 0x20 || (C >= 0x7f && C <= 0x9f) || C == 0xa0 || (C >= 0x2000 && C <= 0x200b) ||
C == 0x200e || C == 0x200f || C == 0x202f || C == 0x205f || C == 0x2060 || C == 0x2420 ||
C == 0x2424 || C == 0x3000 || C == 0xfeff) {
continue;
}
return i;
}
return StrLen;
}
//
// See TextToSentences description below, this one also returns original offsets from the input buffer for each sentence.
//
// pStartOffsets is an array of integers (first character of each sentence) with upto MaxOutUtf8StrByteCount elements
// pEndOffsets is an array of integers (last character of each sentence) with upto MaxOutUtf8StrByteCount elements
//
extern "C"
const int TextToSentencesWithOffsets(const char * pInUtf8Str, int InUtf8StrByteCount,
char * pOutUtf8Str, int * pStartOffsets, int * pEndOffsets, const int MaxOutUtf8StrByteCount)
{
// check if the initilization is needed
if (false == g_fInitialized) {
// make sure only one thread can get the mutex
std::lock_guard<std::mutex> guard(g_InitializationMutex);
// see if the g_fInitialized is still false
if (false == g_fInitialized) {
InitializeWbdSbd();
g_fInitialized = true;
}
}
// validate the parameters
if (0 == InUtf8StrByteCount) {
return 0;
}
if (0 > InUtf8StrByteCount || InUtf8StrByteCount > FALimits::MaxArrSize) {
return -1;
}
if (NULL == pInUtf8Str) {
return -1;
}
// allocate buffer for UTF-32, sentence breaking results, word-breaking results
std::vector< int > utf32input(InUtf8StrByteCount);
int * pBuff = utf32input.data();
if (NULL == pBuff) {
return -1;
}
std::vector< int > utf32offsets(InUtf8StrByteCount);
int * pOffsets = utf32offsets.data();
if (NULL == pOffsets) {
return -1;
}
// make sure there are no uninitialized offsets
if (pStartOffsets) {
memset(pStartOffsets, 0, MaxOutUtf8StrByteCount * sizeof(int));
}
if (pEndOffsets) {
memset(pEndOffsets, 0, MaxOutUtf8StrByteCount * sizeof(int));
}
// convert input to UTF-32
const int MaxBuffSize = ::FAStrUtf8ToArray(pInUtf8Str, InUtf8StrByteCount, pBuff, pOffsets, InUtf8StrByteCount);
if (MaxBuffSize <= 0 || MaxBuffSize > InUtf8StrByteCount) {
return -1;
}
// make sure the utf32input does not contain 'U+0000' elements
std::replace(pBuff, pBuff + MaxBuffSize, 0, 0x20);
// allocated a buffer for UTF-8 output
std::vector< char > utf8output(InUtf8StrByteCount + 1);
char * pTmpUtf8 = utf8output.data();
if (NULL == pTmpUtf8) {
return -1;
}
// keep sentence boundary information here
std::vector< int > SbdRes(MaxBuffSize * 3);
int * pSbdRes = SbdRes.data();
if (NULL == pSbdRes) {
return -1;
}
// get the sentence breaking results
const int SbdOutSize = g_Sbd.Process(pBuff, MaxBuffSize, pSbdRes, MaxBuffSize * 3);
if (SbdOutSize > MaxBuffSize * 3 || 0 != SbdOutSize % 3) {
return -1;
}
// number of sentences
int SentCount = 0;
// accumulate the output here
std::ostringstream Os;
// keep track if a sentence was already added
bool fAdded = false;
// set previous sentence end to -1
int PrevEnd = -1;
for (int i = 0; i < SbdOutSize; i += 3) {
// we don't care about Tag or From for p2s task
const int From = PrevEnd + 1;
const int To = pSbdRes[i + 2];
const int Len = To - From + 1;
PrevEnd = To;
// adjust sentence start if needed
const int Delta = FAGetFirstNonWhiteSpace(pBuff + From, Len);
if (Delta < Len) {
// convert buffer to a UTF-8 string, we temporary use pOutUtf8Str, MaxOutUtf8StrByteCount
const int StrOutSize = ::FAArrayToStrUtf8(pBuff + From + Delta, Len - Delta, pTmpUtf8, InUtf8StrByteCount);
if (pStartOffsets && SentCount < MaxOutUtf8StrByteCount) {
pStartOffsets[SentCount] = pOffsets[From + Delta];
}
if (pEndOffsets && SentCount < MaxOutUtf8StrByteCount) {
const int ToCharSize = ::FAUtf8Size(pInUtf8Str + pOffsets[To]);
pEndOffsets[SentCount] = pOffsets[To] + (0 < ToCharSize ? ToCharSize - 1 : 0);
}
SentCount++;
// check the output size
if (0 > StrOutSize || StrOutSize > InUtf8StrByteCount) {
// should never happen, but happened :-(
return -1;
}
else {
// add a new line separator
if (fAdded) {
Os << '\n';
}
// make sure this buffer does not contain '\n' since it is a delimiter
std::replace(pTmpUtf8, pTmpUtf8 + StrOutSize, '\n', ' ');
// actually copy the data into the string builder
pTmpUtf8[StrOutSize] = 0;
Os << pTmpUtf8;
fAdded = true;
}
}
}
// always use the end of paragraph as the end of sentence
if (PrevEnd + 1 < MaxBuffSize) {
const int From = PrevEnd + 1;
const int To = MaxBuffSize - 1;
const int Len = To - From + 1;
// adjust sentence start if needed
const int Delta = FAGetFirstNonWhiteSpace(pBuff + From, Len);
if (Delta < Len) {
// convert buffer to a UTF-8 string, we temporary use pOutUtf8Str, MaxOutUtf8StrByteCount
const int StrOutSize = ::FAArrayToStrUtf8(pBuff + From + Delta, Len - Delta, pTmpUtf8, InUtf8StrByteCount);
if (pStartOffsets && SentCount < MaxOutUtf8StrByteCount) {
pStartOffsets[SentCount] = pOffsets[From + Delta];
}
if (pEndOffsets && SentCount < MaxOutUtf8StrByteCount) {
const int ToCharSize = ::FAUtf8Size(pInUtf8Str + pOffsets[To]);
pEndOffsets[SentCount] = pOffsets[To] + (0 < ToCharSize ? ToCharSize - 1 : 0);
}
SentCount++;
// check the output size
if (0 > StrOutSize || StrOutSize > InUtf8StrByteCount) {
// should never happen, but happened :-(
return -1;
}
else {
// add a new line separator
if (fAdded) {
Os << '\n';
}
// make sure this buffer does not contain '\n' since it is a delimiter
std::replace(pTmpUtf8, pTmpUtf8 + StrOutSize, '\n', ' ');
// actually copy the data into the string builder
pTmpUtf8[StrOutSize] = 0;
Os << pTmpUtf8;
}
}
}
// we will include the 0 just in case some scriping languages expect 0-terminated buffers and cannot use the size
Os << char(0);
// get the actual output buffer as one string
const std::string & OsStr = Os.str();
const char * pStr = OsStr.c_str();
const int StrLen = (int)OsStr.length();
if (StrLen <= MaxOutUtf8StrByteCount) {
memcpy(pOutUtf8Str, pStr, StrLen);
}
return StrLen;
}
//
// Splits plain-text in UTF-8 encoding into sentences.
//
// Input: UTF-8 string of one paragraph or document
// Output: Size in bytes of the output string and UTF-8 string of '\n' delimited sentences, if the return size <= MaxOutUtf8StrByteCount
//
// Notes:
//
// 1. The return value is -1 in case of an error (make sure your input is a valid UTF-8, BOM is not required)
// 2. We do not use "\r\n" to delimit sentences, it is always '\n'
// 3. It is not necessary to remove '\n' from the input paragraph, sentence breaking algorithm will take care of them
// 4. The output sentences will not contain '\n' in them
//
extern "C"
const int TextToSentences(const char * pInUtf8Str, int InUtf8StrByteCount, char * pOutUtf8Str, const int MaxOutUtf8StrByteCount)
{
return TextToSentencesWithOffsets(pInUtf8Str, InUtf8StrByteCount, pOutUtf8Str, NULL, NULL, MaxOutUtf8StrByteCount);
}
//
// Same as TextToWords, but also returns original offsets from the input buffer for each word.
//
// pStartOffsets is an array of integers (first character of each word) with upto MaxOutUtf8StrByteCount elements
// pEndOffsets is an array of integers (last character of each word) with upto MaxOutUtf8StrByteCount elements
//
extern "C"
const int TextToWordsWithOffsets(const char * pInUtf8Str, int InUtf8StrByteCount,
char * pOutUtf8Str, int * pStartOffsets, int * pEndOffsets, const int MaxOutUtf8StrByteCount)
{
// check if the initilization is needed
if (false == g_fInitialized) {
// make sure only one thread can get the mutex
std::lock_guard<std::mutex> guard(g_InitializationMutex);
// see if the g_fInitialized is still false
if (false == g_fInitialized) {
InitializeWbdSbd();
g_fInitialized = true;
}
}
// validate the parameters
if (0 == InUtf8StrByteCount) {
return 0;
}
if (0 > InUtf8StrByteCount || InUtf8StrByteCount > FALimits::MaxArrSize) {
return -1;
}
if (NULL == pInUtf8Str) {
return -1;
}
// allocate buffer for UTF-32, sentence breaking results, word-breaking results
std::vector< int > utf32input(InUtf8StrByteCount);
int * pBuff = utf32input.data();
if (NULL == pBuff) {
return -1;
}
std::vector< int > utf32offsets(InUtf8StrByteCount);
int * pOffsets = utf32offsets.data();
if (NULL == pOffsets) {
return -1;
}
// make sure there are no uninitialized offsets
if (pStartOffsets) {
memset(pStartOffsets, 0, MaxOutUtf8StrByteCount * sizeof(int));
}
if (pEndOffsets) {
memset(pEndOffsets, 0, MaxOutUtf8StrByteCount * sizeof(int));
}
// convert input to UTF-32
const int MaxBuffSize = ::FAStrUtf8ToArray(pInUtf8Str, InUtf8StrByteCount, pBuff, pOffsets, InUtf8StrByteCount);
if (MaxBuffSize <= 0 || MaxBuffSize > InUtf8StrByteCount) {
return -1;
}
// make sure the utf32input does not contain 'U+0000' elements
std::replace(pBuff, pBuff + MaxBuffSize, 0, 0x20);
// allocated a buffer for UTF-8 output
std::vector< char > utf8output(InUtf8StrByteCount + 1);
char * pTmpUtf8 = utf8output.data();
if (NULL == pTmpUtf8) {
return -1;
}
// keep sentence boundary information here
std::vector< int > WbdRes(MaxBuffSize * 3);
int * pWbdRes = WbdRes.data();
if (NULL == pWbdRes) {
return -1;
}
// get the sentence breaking results
const int WbdOutSize = g_Wbd.Process(pBuff, MaxBuffSize, pWbdRes, MaxBuffSize * 3);
if (WbdOutSize > MaxBuffSize * 3 || 0 != WbdOutSize % 3) {
return -1;
}
// keep track of the word count
int WordCount = 0;
// accumulate the output here
std::ostringstream Os;
// keep track if a word was already added
bool fAdded = false;
for (int i = 0; i < WbdOutSize; i += 3) {
// ignore tokens with IGNORE tag
const int Tag = pWbdRes[i];
if (WBD_IGNORE_TAG == Tag) {
continue;
}
const int From = pWbdRes[i + 1];
const int To = pWbdRes[i + 2];
const int Len = To - From + 1;
// convert buffer to a UTF-8 string, we temporary use pOutUtf8Str, MaxOutUtf8StrByteCount
const int StrOutSize = ::FAArrayToStrUtf8(pBuff + From, Len, pTmpUtf8, InUtf8StrByteCount);
if (pStartOffsets && WordCount < MaxOutUtf8StrByteCount) {
pStartOffsets[WordCount] = pOffsets[From];
}
if (pEndOffsets && WordCount < MaxOutUtf8StrByteCount) {
// offset of last UTF-32 character plus its length in bytes in the original string - 1
const int ToCharSize = ::FAUtf8Size(pInUtf8Str + pOffsets[To]);
pEndOffsets[WordCount] = pOffsets[To] + (0 < ToCharSize ? ToCharSize - 1 : 0);
}
WordCount++;
// check the output size
if (0 > StrOutSize || StrOutSize > InUtf8StrByteCount) {
// should never happen, but happened :-(
return -1;
}
else {
// add a new line separator
if (fAdded) {
Os << ' ';
}
// make sure this buffer does not contain ' ' since it is a delimiter
std::replace(pTmpUtf8, pTmpUtf8 + StrOutSize, ' ', '_');
// actually copy the data into the string builder
pTmpUtf8[StrOutSize] = 0;
Os << pTmpUtf8;
fAdded = true;
}
}
// we will include the 0 just in case some scriping languages expect 0-terminated buffers and cannot use the size
Os << char(0);
// get the actual output buffer as one string
const std::string & OsStr = Os.str();
const char * pStr = OsStr.c_str();
const int StrLen = (int)OsStr.length();
if (StrLen <= MaxOutUtf8StrByteCount) {
memcpy(pOutUtf8Str, pStr, StrLen);
}
return StrLen;
}
//
// Splits plain-text in UTF-8 encoding into words.
//
// Input: UTF-8 string of one sentence or paragraph or document
// Output: Size in bytes of the output string and UTF-8 string of ' ' delimited words, if the return size <= MaxOutUtf8StrByteCount
//
// Notes:
//
// 1. The return value is -1 in case of an error (make sure your input is a valid UTF-8, BOM is not required)
// 2. Words from the word-breaker will not contain spaces
//
extern "C"
const int TextToWords(const char * pInUtf8Str, int InUtf8StrByteCount, char * pOutUtf8Str, const int MaxOutUtf8StrByteCount)
{
return TextToWordsWithOffsets(pInUtf8Str, InUtf8StrByteCount, pOutUtf8Str, NULL, NULL, MaxOutUtf8StrByteCount);
}
// This function implements the fasttext hashing function
inline const uint32_t GetHash(const char * str, size_t strLen) {
uint32_t h = 2166136261;
for (size_t i = 0; i < strLen; i++) {
h = h ^ uint32_t(str[i]);
h = h * 16777619;
}
return h;
}
// EOS symbol
int32_t EOS_HASH = GetHash("</s>", 4);
const void AddWordNgrams(int32_t * hashArray, int& hashCount, int32_t wordNgrams, int32_t bucket) {
// hash size
const int tokenCount = hashCount;
for (int32_t i = 0; i < tokenCount; i++) {
uint64_t h = hashArray[i];
for (int32_t j = i + 1; j < i + wordNgrams; j++) {
uint64_t tempHash = (j < tokenCount) ? hashArray[j] : EOS_HASH; // for computing ngram, we pad by EOS_HASH to allow each word has ngram which begins at itself.
h = h * 116049371 + tempHash;
hashArray[hashCount] = (h % bucket);
++hashCount;
}
}
}
// Get the tokens count by inspecting the spaces in input buffer
inline const int GetTokenCount(const char * input, const int bufferSize)
{
if (bufferSize == 0)
{
return 0;
}
else
{
int spaceCount = 0;
for (int i = 0; i < bufferSize; ++i)
{
if (input[i] == ' ')
{
spaceCount++;
}
}
return spaceCount + 1;
}
}
// Port the fast text getline function with modifications
// 1. do not have vocab
// 2. do not compute subwords info
const int ComputeHashes(const char * input, const int strLen, int32_t * hashArr, int wordNgrams, int bucketSize)
{
int hashCount = 0;
char * pTemp = (char *)input;
char * pWordStart = &pTemp[0];
size_t wordLength = 0;
// add unigram hash first while reading the tokens. Unlike fasttext, there's no EOS padding here.
for (int pos = 0; pos < strLen; pos++)
{
if (pTemp[pos] == ' ' || pos == strLen - 1) // if we hit word boundary pushback wordhash or end of sentence
{
uint32_t wordhash = GetHash(pWordStart, wordLength);
hashArr[hashCount] = wordhash;
++hashCount;
// move pointer to next word and reset length
pWordStart = &pTemp[pos + 1];
wordLength = 0;
}
else // otherwise keep moving temp pointer
{
++wordLength;
}
}
//Add higher order ngrams (bigrams and up), each token has a ngram starting from itself makes the size ngram * ntokens.
AddWordNgrams(hashArr, hashCount, wordNgrams, bucketSize);
return hashCount;
}
// memory cap for stack memory allocation
const int MAX_ALLOCA_SIZE = 204800;
//
// This function implements the fasttext-like hashing logics. It first calls the tokenizer and then convert them into ngram hashes
//
// Example: input : "This is ok."
// output (bigram): hash(this), hash(is), hash(ok), hash(.), hash(this is), hash(is ok), hash(ok .), hash(. EOS)
//
// This is different from fasttext hashing:
// 1. no EOS padding by default for unigram.
// 2. do not take vocab as input, all unigrams are hashed too.
// and ngram hashes are not shifted.
//
extern "C"
const int TextToHashes(const char * pInUtf8Str, int InUtf8StrByteCount, int32_t * pHashArr, const int MaxHashArrLength, int wordNgrams, int bucketSize = 2000000)
{
// must have positive ngram
if (wordNgrams <= 0)
{
return -1;
}
//first we call tokenizer to get word arr
int maxOutputSize = InUtf8StrByteCount * 2 + 1;
int hashArrSize = 0;
char * pTokenizedStr = nullptr;
// cap memory usage
if (maxOutputSize < MAX_ALLOCA_SIZE)
{
pTokenizedStr = (char*)alloca(maxOutputSize);
}
else
{
pTokenizedStr = new char[maxOutputSize];
}
// tokenize the string
int strLen = TextToWords(pInUtf8Str, InUtf8StrByteCount, pTokenizedStr, maxOutputSize);
// if tokenizer has errors,
if (0 > strLen)
{
return strLen;
}
// get tokensize
int tokenCount = GetTokenCount(pTokenizedStr, strLen);
// if memory allocation is not enough for current output, return requested memory amount
if (tokenCount * wordNgrams >= MaxHashArrLength)
{
return strLen * wordNgrams;
}
// if correctly tokenized and the memory usage is within the limit
hashArrSize = ComputeHashes(pTokenizedStr, strLen, pHashArr, wordNgrams, bucketSize);
assert(hashArrSize == wordNgrams * tokenCount);
// clean up heap memo if allocated
if (maxOutputSize >= MAX_ALLOCA_SIZE)
{
delete[] pTokenizedStr;
}
return hashArrSize;
}
| 34.257552 | 173 | 0.607063 | [
"vector"
] |
2e209ece9e6e755d590b1cbf7ed2ab4fd9721120 | 1,891 | cpp | C++ | UVA/796.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | 1 | 2019-09-07T15:56:05.000Z | 2019-09-07T15:56:05.000Z | UVA/796.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | UVA/796.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void tarjan(vector<unordered_set<int>> &graph, vector<int> &order,
vector<int> &scc, set<pair<int, int>> &ans, const int parent,
const int node) {
static int accumulate = 0;
order[node] = scc[node] = ++accumulate;
for (const auto &x : graph[node]) {
if (!order[x]) { // new node
tarjan(graph, order, scc, ans, node, x);
scc[node] = scc[x] < scc[node] ? scc[x] : scc[node];
if (scc[x] > order[node]) { // subtree not in node SCC or ancestor SCC
node < x ? ans.insert({node, x}) : ans.insert({x, node});
}
} else if (x != parent) // ancestor
scc[node] = order[x] < scc[node] ? order[x] : scc[node];
}
}
void solve(vector<unordered_set<int>> &graph) {
// for (int i = 0; i < graph.size(); ++i) {
// cerr << i << ":";
// for (const auto &x: graph[i])
// cerr << " " << x;
// cerr << "\n";
// }
vector<int> order(graph.size()), scc(graph.size());
set<pair<int, int>> ans;
for (int i = 0; i < graph.size(); ++i) {
if (order[i]) continue;
tarjan(graph, order, scc, ans, i, i);
}
// for (const auto &x: order) cerr << x << " ";
// cerr << "\n";
// for (const auto &x: scc) cerr << x << " ";
// cerr << "\n";
cout << ans.size() << " critical links\n";
for (const auto &x : ans) cout << x.first << " - " << x.second << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int node_cnt;
char ignore;
while (cin >> node_cnt) {
vector<unordered_set<int>> graph(node_cnt);
for (int i = 0, from, to_cnt, to; i < node_cnt; ++i) {
cin >> from >> ignore >> to_cnt >> ignore;
for (int j = 0; j < to_cnt; ++j) {
cin >> to;
graph[from].insert(to);
graph[to].insert(from);
}
}
solve(graph);
cout << "\n";
}
return 0;
} | 29.092308 | 77 | 0.521417 | [
"vector"
] |
2e253c7735734efc5b1b05e7635d31385fd1cd54 | 35,394 | hpp | C++ | DarkBit/include/gambit/DarkBit/DarkBit_rollcall.hpp | williamjameshandley/gambit_1.1 | 8f52b2b3ee6876485baa5a9a76015cf51073e194 | [
"Unlicense"
] | null | null | null | DarkBit/include/gambit/DarkBit/DarkBit_rollcall.hpp | williamjameshandley/gambit_1.1 | 8f52b2b3ee6876485baa5a9a76015cf51073e194 | [
"Unlicense"
] | null | null | null | DarkBit/include/gambit/DarkBit/DarkBit_rollcall.hpp | williamjameshandley/gambit_1.1 | 8f52b2b3ee6876485baa5a9a76015cf51073e194 | [
"Unlicense"
] | null | null | null | // GAMBIT: Global and Modular BSM Inference Tool
// *********************************************
/// \file
///
/// Rollcall header for module DarkBit
///
/// Compile-time registration of available obser-
/// vables and likelihoods, as well as their
/// dependencies.
///
/// Add to this if you want to add an observable
/// or likelihood to this module.
///
/// *********************************************
///
/// Authors (add name and date if you modify):
///
/// \author Christoph Weniger
/// (c.weniger@uva.nl)
/// \date 2013 Jul - 2015 May
///
/// \author Torsten Bringmann
/// (torsten.bringmann@fys.uio.no)
/// \date 2013 Jun
/// \date 2014 Mar
///
/// \author Lars A. Dal
/// (l.a.dal@fys.uio.no)
/// \date 2014 Mar, Sep, Oct
///
/// \author Christopher Savage
/// (chris@savage.name)
/// \date 2014 Oct, Dec
/// \date 2015 June
///
/// \author Antje Putze
/// (antje.putze@lapth.cnrs.fr)
/// \date 2015 Jan
///
/// \author Pat Scott
/// (pscott@imperial.ac.uk)
/// \date 2014 Mar
/// \date 2015 Mar, Aug
///
/// \author Sebastian Wild
/// (sebastian.wild@ph.tum.de)
/// \date 2016 Aug
///
/// \author Felix Kahlhoefer
/// (felix.kahlhoefer@desy.de)
/// \date 2016 August
///
/// *********************************************
#ifndef __DarkBit_rollcall_hpp__
#define __DarkBit_rollcall_hpp__
#include "gambit/DarkBit/DarkBit_types.hpp"
#define MODULE DarkBit
START_MODULE
// Backend point initialization --------------------------
// Function to initialize DarkSUSY to a specific model point.
// The generic DarkSUSY initialization is done in the backend
// initialization; this is only necessary for other capabilities
// that make use of model-specific DarkSUSY routines.
#define CAPABILITY DarkSUSY_PointInit
START_CAPABILITY
// Function returns if point initialization is successful
// (probably always true)
#define FUNCTION DarkSUSY_PointInit_MSSM
START_FUNCTION(bool)
DEPENDENCY(MSSM_spectrum, Spectrum)
DEPENDENCY(decay_rates, DecayTable)
ALLOW_MODELS(MSSM63atQ,CMSSM)
// For debugging using DarkSUSY native interface to ISASUGRA
BACKEND_REQ(dsgive_model_isasugra, (), void, (double&,double&,double&,double&,double&))
BACKEND_REQ(dssusy_isasugra, (), void, (int&,int&))
// Initialize DarkSUSY with SLHA file
BACKEND_REQ(dsSLHAread, (), void, (const char*, int&, int))
BACKEND_REQ(dsprep, (), void, ())
// Initialize DarkSUSY with SLHA object (convenience function)
BACKEND_REQ(initFromSLHAeaAndDecayTable, (), int, (const SLHAstruct&, const DecayTable&))
#undef FUNCTION
#undef CAPABILITY
// Function to initialize LocalHalo model in DarkSUSY
#define CAPABILITY DarkSUSY_PointInit_LocalHalo
START_CAPABILITY
#define FUNCTION DarkSUSY_PointInit_LocalHalo_func
START_FUNCTION(bool)
DEPENDENCY(RD_fraction, double)
DEPENDENCY(LocalHalo, LocalMaxwellianHalo)
BACKEND_REQ(dshmcom,(),DS_HMCOM)
BACKEND_REQ(dshmisodf,(),DS_HMISODF)
BACKEND_REQ(dshmframevelcom,(),DS_HMFRAMEVELCOM)
BACKEND_REQ(dshmnoclue,(),DS_HMNOCLUE)
#undef FUNCTION
#undef CAPABILITY
// Relic density -----------------------------------------
#define CAPABILITY RD_spectrum
START_CAPABILITY
#define FUNCTION RD_spectrum_SUSY
START_FUNCTION(DarkBit::RD_spectrum_type)
DEPENDENCY(DarkSUSY_PointInit, bool)
BACKEND_REQ(mspctm, (), DS_MSPCTM)
BACKEND_REQ(widths, (), DS_WIDTHS)
BACKEND_REQ(intdof, (), DS_INTDOF)
BACKEND_REQ(pacodes, (), DS_PACODES)
BACKEND_REQ(particle_code, (), int, (const str&))
#undef FUNCTION
#define FUNCTION RD_spectrum_from_ProcessCatalog
START_FUNCTION(DarkBit::RD_spectrum_type)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(DarkMatter_ID, std::string)
ALLOW_MODELS(SingletDM)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY RD_spectrum_ordered
START_CAPABILITY
#define FUNCTION RD_spectrum_ordered_func
START_FUNCTION(DarkBit::RD_spectrum_type)
DEPENDENCY(RD_spectrum, DarkBit::RD_spectrum_type)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY RD_eff_annrate_DSprep
START_CAPABILITY
#define FUNCTION RD_annrate_DSprep_func
START_FUNCTION(int)
DEPENDENCY(RD_spectrum, DarkBit::RD_spectrum_type)
BACKEND_REQ(rdmgev, (), DS_RDMGEV)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY RD_eff_annrate
START_CAPABILITY
#define FUNCTION RD_eff_annrate_SUSY
START_FUNCTION(fptr_dd)
DEPENDENCY(RD_eff_annrate_DSprep, int)
BACKEND_REQ(dsanwx, (), double, (double&))
#undef FUNCTION
#define FUNCTION RD_eff_annrate_from_ProcessCatalog
START_FUNCTION(fptr_dd)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(DarkMatter_ID, std::string)
ALLOW_MODELS(SingletDM)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY RD_oh2
START_CAPABILITY
#define FUNCTION RD_oh2_general
START_FUNCTION(double)
DEPENDENCY(RD_spectrum_ordered, DarkBit::RD_spectrum_type)
DEPENDENCY(RD_eff_annrate, fptr_dd)
#ifdef DARKBIT_RD_DEBUG
DEPENDENCY(MSSM_spectrum, Spectrum)
#endif
BACKEND_REQ(dsrdthlim, (), void, ())
BACKEND_REQ(dsrdtab, (), void, (double(*)(double&), double&))
BACKEND_REQ(dsrdeqn, (), void, (double(*)(double&),double&,double&,double&,double&,int&))
BACKEND_REQ(dsrdwintp, (), double, (double&))
BACKEND_REQ(particle_code, (), int, (const str&))
BACKEND_REQ(widths, (), DS_WIDTHS)
BACKEND_REQ(rdmgev, (), DS_RDMGEV)
BACKEND_REQ(rdpth, (), DS_RDPTH)
BACKEND_REQ(rdpars, (), DS_RDPARS)
BACKEND_REQ(rdswitch, (), DS_RDSWITCH)
BACKEND_REQ(rdlun, (), DS_RDLUN)
BACKEND_REQ(rdpadd, (), DS_RDPADD)
BACKEND_REQ(rddof, (), DS_RDDOF)
BACKEND_REQ(rderrors, (), DS_RDERRORS)
#undef FUNCTION
// Routine for cross checking RD density results
#define FUNCTION RD_oh2_DarkSUSY
START_FUNCTION(double)
ALLOW_MODELS(MSSM63atQ)
DEPENDENCY(DarkSUSY_PointInit, bool)
BACKEND_REQ(dsrdomega, (), double, (int&,int&,double&,int&,int&,int&))
#undef FUNCTION
// Routine for cross checking RD density results
#define FUNCTION RD_oh2_MicrOmegas
START_FUNCTION(double)
BACKEND_REQ(oh2, (MicrOmegas_MSSM, MicrOmegas_SingletDM), double, (double*,int,double))
ALLOW_MODELS(MSSM63atQ,SingletDM)
#undef FUNCTION
#undef CAPABILITY
// Fraction of the relic density constituted by the DM candidate under investigation
#define CAPABILITY RD_fraction
START_CAPABILITY
#define FUNCTION RD_fraction_one
START_FUNCTION(double)
#undef FUNCTION
#define FUNCTION RD_fraction_leq_one
START_FUNCTION(double)
DEPENDENCY(RD_oh2, double)
#undef FUNCTION
#define FUNCTION RD_fraction_rescaled
START_FUNCTION(double)
DEPENDENCY(RD_oh2, double)
#undef FUNCTION
#undef CAPABILITY
// Cascade decays --------------------------------------------
// Function for retrieving list of final states for cascade decays
#define CAPABILITY cascadeMC_FinalStates
START_CAPABILITY
#define FUNCTION cascadeMC_FinalStates
START_FUNCTION(std::vector<std::string>)
#undef FUNCTION
#undef CAPABILITY
// Function setting up the decay table used in decay chains
#define CAPABILITY cascadeMC_DecayTable
START_CAPABILITY
#define FUNCTION cascadeMC_DecayTable
START_FUNCTION(DarkBit::DecayChain::DecayTable)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(SimYieldTable, DarkBit::SimYieldTable)
#undef FUNCTION
#undef CAPABILITY
// Loop manager for cascade decays
#define CAPABILITY cascadeMC_LoopManagement
START_CAPABILITY
#define FUNCTION cascadeMC_LoopManager
START_FUNCTION(void, CAN_MANAGE_LOOPS)
DEPENDENCY(GA_missingFinalStates, std::vector<std::string>)
#undef FUNCTION
#undef CAPABILITY
// Function selecting initial state for decay chain
#define CAPABILITY cascadeMC_InitialState
START_CAPABILITY
#define FUNCTION cascadeMC_InitialState
START_FUNCTION(std::string)
DEPENDENCY(GA_missingFinalStates, std::vector<std::string>)
NEEDS_MANAGER_WITH_CAPABILITY(cascadeMC_LoopManagement)
#undef FUNCTION
#undef CAPABILITY
// Event counter for cascade decays
#define CAPABILITY cascadeMC_EventCount
START_CAPABILITY
#define FUNCTION cascadeMC_EventCount
START_FUNCTION(DarkBit::stringIntMap)
DEPENDENCY(cascadeMC_InitialState, std::string)
NEEDS_MANAGER_WITH_CAPABILITY(cascadeMC_LoopManagement)
#undef FUNCTION
#undef CAPABILITY
// Function for generating decay chains
#define CAPABILITY cascadeMC_ChainEvent
START_CAPABILITY
#define FUNCTION cascadeMC_GenerateChain
START_FUNCTION(DarkBit::DecayChain::ChainContainer)
DEPENDENCY(cascadeMC_InitialState, std::string)
DEPENDENCY(cascadeMC_DecayTable, DarkBit::DecayChain::DecayTable)
NEEDS_MANAGER_WITH_CAPABILITY(cascadeMC_LoopManagement)
#undef FUNCTION
#undef CAPABILITY
// Function responsible for histogramming and evaluating end conditions for event loop
#define CAPABILITY cascadeMC_Histograms
START_CAPABILITY
#define FUNCTION cascadeMC_Histograms
START_FUNCTION(DarkBit::simpleHistContainter)
DEPENDENCY(cascadeMC_InitialState, std::string)
DEPENDENCY(cascadeMC_ChainEvent, DarkBit::DecayChain::ChainContainer)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(SimYieldTable, DarkBit::SimYieldTable)
DEPENDENCY(cascadeMC_FinalStates,std::vector<std::string>)
NEEDS_MANAGER_WITH_CAPABILITY(cascadeMC_LoopManagement)
#undef FUNCTION
#undef CAPABILITY
// Function requesting and returning gamma ray spectra from cascade decays.
#define CAPABILITY cascadeMC_gammaSpectra
START_CAPABILITY
#define FUNCTION cascadeMC_gammaSpectra
START_FUNCTION(DarkBit::stringFunkMap)
DEPENDENCY(GA_missingFinalStates, std::vector<std::string>)
DEPENDENCY(cascadeMC_FinalStates,std::vector<std::string>)
DEPENDENCY(cascadeMC_Histograms, DarkBit::simpleHistContainter)
DEPENDENCY(cascadeMC_EventCount, DarkBit::stringIntMap)
#undef FUNCTION
#undef CAPABILITY
/*
// Function for printing test result of cascade decays
#define CAPABILITY cascadeMC_PrintResult
START_CAPABILITY
#define FUNCTION cascadeMC_PrintResult
START_FUNCTION(bool)
DEPENDENCY(cascadeMC_Histograms, DarkBit::simpleHistContainter)
DEPENDENCY(cascadeMC_EventCount, DarkBit::stringIntMap)
#undef FUNCTION
#undef CAPABILITY
*/
/*
// Process catalog for testing purposes
#define CAPABILITY cascadeMC_test_TH_ProcessCatalog
START_CAPABILITY
#define FUNCTION cascadeMC_test_TH_ProcessCatalog
START_FUNCTION(DarkBit::TH_ProcessCatalog)
#undef FUNCTION
#undef CAPABILITY
// Unit test for decay chains
#define CAPABILITY cascadeMC_UnitTest
START_CAPABILITY
#define FUNCTION cascadeMC_UnitTest
START_FUNCTION(bool)
DEPENDENCY(cascadeMC_test_TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(SimYieldTable, DarkBit::SimYieldTable)
#undef FUNCTION
#undef CAPABILITY
*/
// Gamma rays --------------------------------------------
//
#define CAPABILITY GA_missingFinalStates
START_CAPABILITY
#define FUNCTION GA_missingFinalStates
START_FUNCTION(std::vector<std::string>)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(SimYieldTable, DarkBit::SimYieldTable)
DEPENDENCY(DarkMatter_ID, std::string)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY GA_AnnYield
START_CAPABILITY
#define FUNCTION GA_AnnYield_General
START_FUNCTION(daFunk::Funk)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(SimYieldTable, DarkBit::SimYieldTable)
DEPENDENCY(cascadeMC_gammaSpectra, DarkBit::stringFunkMap)
DEPENDENCY(DarkMatter_ID, std::string)
#undef FUNCTION
/*
#define FUNCTION GA_AnnYield_DarkSUSY
START_FUNCTION(daFunk::Funk)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(DarkMatter_ID, std::string)
BACKEND_REQ(dshayield, (), double, (double&,double&,int&,int&,int&))
#undef FUNCTION
*/
#undef CAPABILITY
#define CAPABILITY TH_ProcessCatalog
START_CAPABILITY
#define FUNCTION TH_ProcessCatalog_MSSM
START_FUNCTION(DarkBit::TH_ProcessCatalog)
//ALLOW_MODELS(MSSM63atQ)
DEPENDENCY(DarkSUSY_PointInit, bool)
DEPENDENCY(MSSM_spectrum, Spectrum)
DEPENDENCY(DarkMatter_ID, std::string)
DEPENDENCY(decay_rates,DecayTable)
//BACKEND_REQ(mspctm, (), DS_MSPCTM)
BACKEND_REQ(dssigmav, (), double, (int&))
BACKEND_REQ(dsIBffdxdy, (), double, (int&, double&, double&))
BACKEND_REQ(dsIBhhdxdy, (), double, (int&, double&, double&))
BACKEND_REQ(dsIBwhdxdy, (), double, (int&, double&, double&))
BACKEND_REQ(dsIBwwdxdy, (), double, (int&, double&, double&))
BACKEND_REQ(IBintvars, (), DS_IBINTVARS)
#undef FUNCTION
#define FUNCTION TH_ProcessCatalog_SingletDM
START_FUNCTION(DarkBit::TH_ProcessCatalog)
DEPENDENCY(decay_rates,DecayTable)
DEPENDENCY(SingletDM_spectrum, Spectrum)
ALLOW_MODELS(SingletDM)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY set_gamLike_GC_halo
START_CAPABILITY
#define FUNCTION set_gamLike_GC_halo
START_FUNCTION(bool)
DEPENDENCY(GalacticHalo, GalacticHaloProperties)
BACKEND_REQ(set_halo_profile, (gamLike), void, (int, const std::vector<double> &, const std::vector<double> &, double))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_FermiLATdwarfs
START_CAPABILITY
#define FUNCTION lnL_FermiLATdwarfs_gamLike
START_FUNCTION(double)
DEPENDENCY(GA_AnnYield, daFunk::Funk)
DEPENDENCY(RD_fraction, double)
BACKEND_REQ(lnL, (gamLike), double, (int, const std::vector<double> &, const std::vector<double> &))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_FermiGC
START_CAPABILITY
#define FUNCTION lnL_FermiGC_gamLike
START_FUNCTION(double)
DEPENDENCY(GA_AnnYield, daFunk::Funk)
DEPENDENCY(RD_fraction, double)
DEPENDENCY(set_gamLike_GC_halo, bool)
BACKEND_REQ(lnL, (gamLike), double, (int, const std::vector<double> &, const std::vector<double> &))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_CTAGC
START_CAPABILITY
#define FUNCTION lnL_CTAGC_gamLike
START_FUNCTION(double)
DEPENDENCY(GA_AnnYield, daFunk::Funk)
DEPENDENCY(RD_fraction, double)
//DEPENDENCY(set_gamLike_GC_halo, bool)
BACKEND_REQ(lnL, (gamLike), double, (int, const std::vector<double> &, const std::vector<double> &))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_HESSGC
START_CAPABILITY
#define FUNCTION lnL_HESSGC_gamLike
START_FUNCTION(double)
DEPENDENCY(GA_AnnYield, daFunk::Funk)
DEPENDENCY(RD_fraction, double)
DEPENDENCY(set_gamLike_GC_halo, bool)
BACKEND_REQ(lnL, (gamLike), double, (int, const std::vector<double> &, const std::vector<double> &))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY dump_GammaSpectrum
START_CAPABILITY
#define FUNCTION dump_GammaSpectrum
START_FUNCTION(double)
DEPENDENCY(GA_AnnYield, daFunk::Funk)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_oh2
START_CAPABILITY
#define FUNCTION lnL_oh2_Simple
START_FUNCTION(double)
DEPENDENCY(RD_oh2, double)
#undef FUNCTION
#define FUNCTION lnL_oh2_upperlimit
START_FUNCTION(double)
DEPENDENCY(RD_oh2, double)
#undef FUNCTION
#undef CAPABILITY
// Local DM density likelihood
#define CAPABILITY lnL_rho0
START_CAPABILITY
#define FUNCTION lnL_rho0_lognormal
START_FUNCTION(double)
DEPENDENCY(LocalHalo, LocalMaxwellianHalo)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_vrot
START_CAPABILITY
#define FUNCTION lnL_vrot_gaussian
START_FUNCTION(double)
DEPENDENCY(LocalHalo, LocalMaxwellianHalo)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_v0
START_CAPABILITY
#define FUNCTION lnL_v0_gaussian
START_FUNCTION(double)
DEPENDENCY(LocalHalo, LocalMaxwellianHalo)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_vesc
START_CAPABILITY
#define FUNCTION lnL_vesc_gaussian
START_FUNCTION(double)
DEPENDENCY(LocalHalo, LocalMaxwellianHalo)
#undef FUNCTION
#undef CAPABILITY
// Simple WIMP property extractors =======================================
// Retrieve the DM mass in GeV for generic models
QUICK_FUNCTION(DarkBit, mwimp, NEW_CAPABILITY, mwimp_generic, double, (),
(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog), (DarkMatter_ID, std::string))
// Retrieve the total thermally-averaged annihilation cross-section for indirect detection (cm^3 / s)
QUICK_FUNCTION(DarkBit, sigmav, NEW_CAPABILITY, sigmav_late_universe, double, (),
(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog), (DarkMatter_ID, std::string))
// DIRECT DETECTION ==================================================
// Determine the DM-nucleon couplings
#define CAPABILITY DD_couplings
START_CAPABILITY
#define FUNCTION DD_couplings_DarkSUSY
START_FUNCTION(DM_nucleon_couplings)
DEPENDENCY(DarkSUSY_PointInit, bool)
BACKEND_REQ(dsddgpgn, (), void, (double&, double&, double&, double&))
BACKEND_REQ(mspctm, (), DS_MSPCTM)
BACKEND_REQ(ddcom, (DarkSUSY), DS_DDCOM)
ALLOW_MODELS(nuclear_params_fnq)
#undef FUNCTION
#define FUNCTION DD_couplings_MicrOmegas
START_FUNCTION(DM_nucleon_couplings)
BACKEND_REQ(nucleonAmplitudes, (gimmemicro), int, (double(*)(double,double,double,double), double*, double*, double*, double*))
BACKEND_REQ(FeScLoop, (gimmemicro), double, (double, double, double, double))
BACKEND_REQ(MOcommon, (gimmemicro), MicrOmegas::MOcommonSTR)
ALLOW_MODEL_DEPENDENCE(nuclear_params_fnq, MSSM63atQ, SingletDM)
MODEL_GROUP(group1, (nuclear_params_fnq))
MODEL_GROUP(group2, (MSSM63atQ, SingletDM))
ALLOW_MODEL_COMBINATION(group1, group2)
BACKEND_OPTION((MicrOmegas_MSSM),(gimmemicro))
BACKEND_OPTION((MicrOmegas_SingletDM),(gimmemicro))
FORCE_SAME_BACKEND(gimmemicro)
#undef FUNCTION
#define FUNCTION DD_couplings_SingletDM
START_FUNCTION(DM_nucleon_couplings)
DEPENDENCY(SingletDM_spectrum, Spectrum)
ALLOW_JOINT_MODEL(nuclear_params_fnq, SingletDM)
#undef FUNCTION
#undef CAPABILITY
// Simple calculators of the spin-(in)dependent WIMP-proton and WIMP-neutron cross-sections
QUICK_FUNCTION(DarkBit, sigma_SI_p, NEW_CAPABILITY, sigma_SI_p_simple, double, (), (DD_couplings, DM_nucleon_couplings), (mwimp, double))
QUICK_FUNCTION(DarkBit, sigma_SI_n, NEW_CAPABILITY, sigma_SI_n_simple, double, (), (DD_couplings, DM_nucleon_couplings), (mwimp, double))
QUICK_FUNCTION(DarkBit, sigma_SD_p, NEW_CAPABILITY, sigma_SD_p_simple, double, (), (DD_couplings, DM_nucleon_couplings), (mwimp, double))
QUICK_FUNCTION(DarkBit, sigma_SD_n, NEW_CAPABILITY, sigma_SD_n_simple, double, (), (DD_couplings, DM_nucleon_couplings), (mwimp, double))
// Likelihoods for nuclear parameters:
#define CAPABILITY lnL_SI_nuclear_parameters
START_CAPABILITY
#define FUNCTION lnL_sigmas_sigmal
START_FUNCTION(double)
ALLOW_MODEL(nuclear_params_sigmas_sigmal)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY lnL_SD_nuclear_parameters
START_CAPABILITY
#define FUNCTION lnL_deltaq
START_FUNCTION(double)
ALLOW_MODELS(nuclear_params_fnq)
#undef FUNCTION
#undef CAPABILITY
// DD rate and likelihood calculations. Don't try this one at home kids.
#define DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,TYPE,NAME) \
LONG_START_CAPABILITY(MODULE, CAT_3(EXPERIMENT,_,NAME)) \
LONG_DECLARE_FUNCTION(MODULE, CAT_3(EXPERIMENT,_,NAME), \
CAT_3(EXPERIMENT,_Get,NAME), TYPE, 0) \
LONG_DEPENDENCY(MODULE, CAT_3(EXPERIMENT,_Get,NAME), \
CAT(EXPERIMENT,_Calculate), bool) \
LONG_BACKEND_REQ(MODULE, CAT_3(EXPERIMENT,_,NAME), \
CAT_3(EXPERIMENT,_Get,NAME), DD_Experiment, (DDCalc), int, (const str&)) \
LONG_BACKEND_REQ(MODULE, CAT_3(EXPERIMENT,_,NAME), \
CAT_3(EXPERIMENT,_Get,NAME), CAT(DD_,NAME), (DDCalc), TYPE, (const int&))
#define DD_DECLARE_EXPERIMENT(EXPERIMENT) \
LONG_START_CAPABILITY(MODULE, CAT(EXPERIMENT,_Calculate)) \
LONG_DECLARE_FUNCTION(MODULE, CAT(EXPERIMENT,_Calculate), \
CAT(EXPERIMENT,_Calc), bool, 0) \
LONG_BACKEND_REQ(MODULE, CAT(EXPERIMENT,_Calculate), \
CAT(EXPERIMENT,_Calc), DD_Experiment, (DDCalc), int, (const str&)) \
LONG_BACKEND_REQ(MODULE, CAT(EXPERIMENT,_Calculate), \
CAT(EXPERIMENT,_Calc), DD_CalcRates, (DDCalc), void, (const int&)) \
DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,int,Events) \
DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,double,Background) \
DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,double,Signal) \
DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,double,SignalSI) \
DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,double,SignalSD) \
DD_DECLARE_RESULT_FUNCTION(EXPERIMENT,double,LogLikelihood) \
// Declare different DD experiments that exist in DDCalc.
DD_DECLARE_EXPERIMENT(XENON100_2012)
DD_DECLARE_EXPERIMENT(XENON1T_2017)
DD_DECLARE_EXPERIMENT(LUX_2013)
DD_DECLARE_EXPERIMENT(SuperCDMS_2014)
DD_DECLARE_EXPERIMENT(SIMPLE_2014)
DD_DECLARE_EXPERIMENT(DARWIN_Ar)
DD_DECLARE_EXPERIMENT(DARWIN_Xe)
DD_DECLARE_EXPERIMENT(LUX_2016)
DD_DECLARE_EXPERIMENT(PandaX_2016)
DD_DECLARE_EXPERIMENT(LUX_2015)
DD_DECLARE_EXPERIMENT(PICO_2L)
DD_DECLARE_EXPERIMENT(PICO_60_F)
DD_DECLARE_EXPERIMENT(PICO_60_I)
DD_DECLARE_EXPERIMENT(PICO_60_2017)
// INDIRECT DETECTION: NEUTRINOS =====================================
// Solar capture ------------------------
// Capture rate of regular dark matter in the Sun (no v-dependent or q-dependent cross-sections) (s^-1).
#define CAPABILITY capture_rate_Sun
START_CAPABILITY
#define FUNCTION capture_rate_Sun_const_xsec
START_FUNCTION(double)
BACKEND_REQ(cap_Sun_v0q0_isoscalar, (DarkSUSY), double, (const double&, const double&, const double&))
DEPENDENCY(mwimp, double)
DEPENDENCY(sigma_SI_p, double)
DEPENDENCY(sigma_SD_p, double)
#define CONDITIONAL_DEPENDENCY DarkSUSY_PointInit_LocalHalo
START_CONDITIONAL_DEPENDENCY(bool)
ACTIVATE_FOR_BACKEND(cap_Sun_v0q0_isoscalar, DarkSUSY)
#undef CONDITIONAL_DEPENDENCY
#undef FUNCTION
#undef CAPABILITY
// Equilibration time for capture and annihilation of dark matter in the Sun (s)
#define CAPABILITY equilibration_time_Sun
START_CAPABILITY
#define FUNCTION equilibration_time_Sun
START_FUNCTION(double)
DEPENDENCY(sigmav, double)
DEPENDENCY(mwimp, double)
DEPENDENCY(capture_rate_Sun, double)
#undef FUNCTION
#undef CAPABILITY
// Annihilation rate of dark matter in the Sun (s^-1)
#define CAPABILITY annihilation_rate_Sun
START_CAPABILITY
#define FUNCTION annihilation_rate_Sun
START_FUNCTION(double)
DEPENDENCY(equilibration_time_Sun, double)
DEPENDENCY(capture_rate_Sun, double)
#undef FUNCTION
#undef CAPABILITY
/// Neutrino yield function pointer and setup
#define CAPABILITY nuyield_ptr
START_CAPABILITY
#define FUNCTION nuyield_from_DS
START_FUNCTION(nuyield_info)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(mwimp, double)
DEPENDENCY(sigmav, double)
DEPENDENCY(sigma_SI_p, double)
DEPENDENCY(sigma_SD_p, double)
DEPENDENCY(DarkMatter_ID, std::string)
BACKEND_REQ(nuyield_setup, (needs_DS), void, (const double(&)[29],
const double(&)[29][3], const double(&)[15], const double(&)[3], const double&,
const double&, const double&, const double&, const double&))
BACKEND_REQ(nuyield, (needs_DS), double, (const double&, const int&, void*&))
BACKEND_REQ(get_DS_neutral_h_decay_channels, (needs_DS), std::vector< std::vector<str> >, ())
BACKEND_REQ(get_DS_charged_h_decay_channels, (needs_DS), std::vector< std::vector<str> >, ())
BACKEND_OPTION((DarkSUSY, 5.1.1, 5.1.2, 5.1.3), (needs_DS))
#undef FUNCTION
#undef CAPABILITY
// Neutrino telescope likelihoods ------------------------
#define CAPABILITY IC22_data
START_CAPABILITY
#define FUNCTION IC22_full
START_FUNCTION(nudata)
DEPENDENCY(mwimp, double)
DEPENDENCY(annihilation_rate_Sun, double)
DEPENDENCY(nuyield_ptr, nuyield_info)
BACKEND_REQ(nubounds, (), void, (const char&, const double&, const double&,
nuyield_function_pointer, double&, double&, int&,
double&, double&, const int&, const double&,
const int&, const bool&, const double&,
const double&, void*&, const bool&))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC22_signal
START_CAPABILITY
#define FUNCTION IC22_signal
START_FUNCTION(double)
DEPENDENCY(IC22_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC22_bg
START_CAPABILITY
#define FUNCTION IC22_bg
START_FUNCTION(double)
DEPENDENCY(IC22_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC22_loglike
START_CAPABILITY
#define FUNCTION IC22_loglike
START_FUNCTION(double)
DEPENDENCY(IC22_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC22_bgloglike
START_CAPABILITY
#define FUNCTION IC22_bgloglike
START_FUNCTION(double)
DEPENDENCY(IC22_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC22_pvalue
START_CAPABILITY
#define FUNCTION IC22_pvalue
START_FUNCTION(double)
DEPENDENCY(IC22_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC22_nobs
START_CAPABILITY
#define FUNCTION IC22_nobs
START_FUNCTION(int)
DEPENDENCY(IC22_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_data
START_CAPABILITY
#define FUNCTION IC79WH_full
START_FUNCTION(nudata)
DEPENDENCY(mwimp, double)
DEPENDENCY(annihilation_rate_Sun, double)
DEPENDENCY(nuyield_ptr, nuyield_info)
BACKEND_REQ(nubounds, (), void, (const char&, const double&, const double&,
nuyield_function_pointer, double&, double&, int&,
double&, double&, const int&, const double&,
const int&, const bool&, const double&,
const double&, void*&, const bool&))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_signal
START_CAPABILITY
#define FUNCTION IC79WH_signal
START_FUNCTION(double)
DEPENDENCY(IC79WH_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_bg
START_CAPABILITY
#define FUNCTION IC79WH_bg
START_FUNCTION(double)
DEPENDENCY(IC79WH_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_loglike
START_CAPABILITY
#define FUNCTION IC79WH_loglike
START_FUNCTION(double)
DEPENDENCY(IC79WH_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_bgloglike
START_CAPABILITY
#define FUNCTION IC79WH_bgloglike
START_FUNCTION(double)
DEPENDENCY(IC79WH_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_pvalue
START_CAPABILITY
#define FUNCTION IC79WH_pvalue
START_FUNCTION(double)
DEPENDENCY(IC79WH_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WH_nobs
START_CAPABILITY
#define FUNCTION IC79WH_nobs
START_FUNCTION(int)
DEPENDENCY(IC79WH_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_data
START_CAPABILITY
#define FUNCTION IC79WL_full
START_FUNCTION(nudata)
DEPENDENCY(mwimp, double)
DEPENDENCY(annihilation_rate_Sun, double)
DEPENDENCY(nuyield_ptr, nuyield_info)
BACKEND_REQ(nubounds, (), void, (const char&, const double&, const double&,
nuyield_function_pointer, double&, double&, int&,
double&, double&, const int&, const double&,
const int&, const bool&, const double&,
const double&, void*&, const bool&))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_signal
START_CAPABILITY
#define FUNCTION IC79WL_signal
START_FUNCTION(double)
DEPENDENCY(IC79WL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_bg
START_CAPABILITY
#define FUNCTION IC79WL_bg
START_FUNCTION(double)
DEPENDENCY(IC79WL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_loglike
START_CAPABILITY
#define FUNCTION IC79WL_loglike
START_FUNCTION(double)
DEPENDENCY(IC79WL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_bgloglike
START_CAPABILITY
#define FUNCTION IC79WL_bgloglike
START_FUNCTION(double)
DEPENDENCY(IC79WL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_pvalue
START_CAPABILITY
#define FUNCTION IC79WL_pvalue
START_FUNCTION(double)
DEPENDENCY(IC79WL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79WL_nobs
START_CAPABILITY
#define FUNCTION IC79WL_nobs
START_FUNCTION(int)
DEPENDENCY(IC79WL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_data
START_CAPABILITY
#define FUNCTION IC79SL_full
START_FUNCTION(nudata)
DEPENDENCY(mwimp, double)
DEPENDENCY(annihilation_rate_Sun, double)
DEPENDENCY(nuyield_ptr, nuyield_info)
BACKEND_REQ(nubounds, (), void, (const char&, const double&, const double&,
nuyield_function_pointer, double&, double&, int&,
double&, double&, const int&, const double&,
const int&, const bool&, const double&,
const double&, void*&, const bool&))
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_signal
START_CAPABILITY
#define FUNCTION IC79SL_signal
START_FUNCTION(double)
DEPENDENCY(IC79SL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_bg
START_CAPABILITY
#define FUNCTION IC79SL_bg
START_FUNCTION(double)
DEPENDENCY(IC79SL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_loglike
START_CAPABILITY
#define FUNCTION IC79SL_loglike
START_FUNCTION(double)
DEPENDENCY(IC79SL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_bgloglike
START_CAPABILITY
#define FUNCTION IC79SL_bgloglike
START_FUNCTION(double)
DEPENDENCY(IC79SL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_pvalue
START_CAPABILITY
#define FUNCTION IC79SL_pvalue
START_FUNCTION(double)
DEPENDENCY(IC79SL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79SL_nobs
START_CAPABILITY
#define FUNCTION IC79SL_nobs
START_FUNCTION(int)
DEPENDENCY(IC79SL_data, nudata)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IC79_loglike
START_CAPABILITY
#define FUNCTION IC79_loglike
START_FUNCTION(double)
DEPENDENCY(IC79WH_loglike, double)
DEPENDENCY(IC79WL_loglike, double)
DEPENDENCY(IC79SL_loglike, double)
DEPENDENCY(IC79WH_bgloglike, double)
DEPENDENCY(IC79WL_bgloglike, double)
DEPENDENCY(IC79SL_bgloglike, double)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY IceCube_likelihood
START_CAPABILITY
#define FUNCTION IC_loglike
START_FUNCTION(double)
DEPENDENCY(IC22_loglike, double)
DEPENDENCY(IC79WH_loglike, double)
DEPENDENCY(IC79WL_loglike, double)
DEPENDENCY(IC79SL_loglike, double)
DEPENDENCY(IC22_bgloglike, double)
DEPENDENCY(IC79WH_bgloglike, double)
DEPENDENCY(IC79WL_bgloglike, double)
DEPENDENCY(IC79SL_bgloglike, double)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY UnitTest_DarkBit
START_CAPABILITY
#define FUNCTION UnitTest_DarkBit
START_FUNCTION(int)
DEPENDENCY(DD_couplings, DM_nucleon_couplings)
DEPENDENCY(RD_oh2, double)
DEPENDENCY(GA_AnnYield, daFunk::Funk)
DEPENDENCY(TH_ProcessCatalog, DarkBit::TH_ProcessCatalog)
DEPENDENCY(DarkMatter_ID, std::string)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY SimYieldTable
START_CAPABILITY
#define FUNCTION SimYieldTable_DarkSUSY
START_FUNCTION(DarkBit::SimYieldTable)
BACKEND_REQ(dshayield, (), double, (double&,double&,int&,int&,int&))
#undef FUNCTION
#define FUNCTION SimYieldTable_MicrOmegas
START_FUNCTION(DarkBit::SimYieldTable)
BACKEND_REQ(dNdE, (), double, (double,double,int,int))
#undef FUNCTION
#define FUNCTION SimYieldTable_PPPC
START_FUNCTION(DarkBit::SimYieldTable)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY DarkMatter_ID
START_CAPABILITY
#define FUNCTION DarkMatter_ID_SingletDM
START_FUNCTION(std::string)
ALLOW_MODELS(SingletDM, SingletDM_running)
#undef FUNCTION
#define FUNCTION DarkMatter_ID_MSSM
START_FUNCTION(std::string)
DEPENDENCY(MSSM_spectrum, Spectrum)
#undef FUNCTION
#undef CAPABILITY
// --- Functions related to the local and global properties of the DM halo ---
#define CAPABILITY GalacticHalo
START_CAPABILITY
#define FUNCTION GalacticHalo_gNFW
START_FUNCTION(GalacticHaloProperties)
ALLOW_MODEL(Halo_gNFW)
#undef FUNCTION
#define FUNCTION GalacticHalo_Einasto
START_FUNCTION(GalacticHaloProperties)
ALLOW_MODEL(Halo_Einasto)
#undef FUNCTION
#undef CAPABILITY
#define CAPABILITY LocalHalo
START_CAPABILITY
#define FUNCTION ExtractLocalMaxwellianHalo
START_FUNCTION(LocalMaxwellianHalo)
ALLOW_MODELS(Halo_gNFW, Halo_Einasto)
#undef FUNCTION
#undef CAPABILITY
#undef MODULE
#endif /* defined(__DarkBit_rollcall_hpp__) */
| 34.836614 | 139 | 0.708482 | [
"object",
"vector",
"model"
] |
2e29d5e58aee683a0f8d496cb3c0650228b7152f | 655 | cpp | C++ | cpp/ATourOfC++/p24.cpp | xiongxin/playground | 9f23862b35c00b810e20f2e1e661142c024baa33 | [
"MIT"
] | null | null | null | cpp/ATourOfC++/p24.cpp | xiongxin/playground | 9f23862b35c00b810e20f2e1e661142c024baa33 | [
"MIT"
] | null | null | null | cpp/ATourOfC++/p24.cpp | xiongxin/playground | 9f23862b35c00b810e20f2e1e661142c024baa33 | [
"MIT"
] | null | null | null | #include <iostream>
double sqrt(double);
class Vector {
public:
Vector(int s);
double &operator[](int i);
int size();
private:
double *elem;
int sz;
};
Vector::Vector(int s) : elem{new double[s]}, sz{s} {}
double &Vector::operator[](int i) {
static_assert(i <= 0, "integer are to large");
return elem[i];
}
int Vector::size() {
return sz;
}
int main() {
std::cout << sqrt(10.0) << std::endl;
Vector v(10);
try {
std::cout << v[10] << std::endl;
} catch (std::out_of_range) {
std::cout << "out_range" << std::endl;
}
return 0;
}
double sqrt(double d) {
return d * d;
} | 16.375 | 53 | 0.546565 | [
"vector"
] |
2e2b24d589b10b1142a88416530a734dda10ec9c | 38,636 | cc | C++ | wkhtmltox/src/wkhtmltox/pdfconverter.cc | uribbas/latexpp | ae3138613a83bcca64e56f816c721489e6bbd0fe | [
"MIT"
] | null | null | null | wkhtmltox/src/wkhtmltox/pdfconverter.cc | uribbas/latexpp | ae3138613a83bcca64e56f816c721489e6bbd0fe | [
"MIT"
] | null | null | null | wkhtmltox/src/wkhtmltox/pdfconverter.cc | uribbas/latexpp | ae3138613a83bcca64e56f816c721489e6bbd0fe | [
"MIT"
] | null | null | null | // -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
// vi:set ts=4 sts=4 sw=4 noet :
//
// Copyright 2010-2020 wkhtmltopdf authors
//
// This file is part of wkhtmltopdf.
//
// wkhtmltopdf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wkhtmltopdf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with wkhtmltopdf. If not, see <http://www.gnu.org/licenses/>.
#include "pdfconverter_p.hh"
#include <QAuthenticator>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QPair>
#include <QPrintEngine>
#include <QTimer>
#include <QWebFrame>
#include <QWebPage>
#include <QWebSettings>
#include <QXmlQuery>
#include <algorithm>
#include <qapplication.h>
#include <qfileinfo.h>
#ifdef Q_OS_WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "dllbegin.inc"
using namespace wkhtmltopdf;
using namespace wkhtmltopdf::settings;
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)
const qreal PdfConverter::millimeterToPointMultiplier = 2.83464567;
DLL_LOCAL QMap<QWebPage *, PageObject *> PageObject::webPageToObject;
struct DLL_LOCAL StreamDumper {
QFile out;
QTextStream stream;
StreamDumper(const QString & path): out(path), stream(&out) {
out.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
stream.setCodec("UTF-8");
}
};
/*!
\file pageconverter.hh
\brief Defines the PdfConverter class
*/
/*!
\file pageconverter_p.hh
\brief Defines the PdfConverterPrivate class
*/
bool DLL_LOCAL looksLikeHtmlAndNotAUrl(QString str) {
QString s = str.split("?")[0];
return s.count('<') > 0 || str.startsWith("data:", Qt::CaseInsensitive);
}
PdfConverterPrivate::PdfConverterPrivate(PdfGlobal & s, PdfConverter & o) :
settings(s), pageLoader(s.load, settings.dpi, true),
out(o), printer(0), painter(0)
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
, measuringHFLoader(s.load, settings.dpi), hfLoader(s.load, settings.dpi), tocLoader1(s.load, settings.dpi), tocLoader2(s.load, settings.dpi)
, tocLoader(&tocLoader1), tocLoaderOld(&tocLoader2)
, outline(0), currentHeader(0), currentFooter(0)
#endif
{
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
phaseDescriptions.push_back("Loading pages");
phaseDescriptions.push_back("Counting pages");
phaseDescriptions.push_back("Loading TOC");
phaseDescriptions.push_back("Resolving links");
phaseDescriptions.push_back("Loading headers and footers");
#else
phaseDescriptions.push_back("Loading page");
#endif
phaseDescriptions.push_back("Printing pages");
phaseDescriptions.push_back("Done");
connect(&pageLoader, SIGNAL(loadProgress(int)), this, SLOT(loadProgress(int)));
connect(&pageLoader, SIGNAL(loadFinished(bool)), this, SLOT(pagesLoaded(bool)));
connect(&pageLoader, SIGNAL(error(QString)), this, SLOT(forwardError(QString)));
connect(&pageLoader, SIGNAL(warning(QString)), this, SLOT(forwardWarning(QString)));
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
connect(&measuringHFLoader, SIGNAL(loadProgress(int)), this, SLOT(loadProgress(int)));
connect(&measuringHFLoader, SIGNAL(loadFinished(bool)), this, SLOT(measuringHeadersLoaded(bool)));
connect(&measuringHFLoader, SIGNAL(error(QString)), this, SLOT(forwardError(QString)));
connect(&measuringHFLoader, SIGNAL(warning(QString)), this, SLOT(forwardWarning(QString)));
connect(&hfLoader, SIGNAL(loadProgress(int)), this, SLOT(loadProgress(int)));
connect(&hfLoader, SIGNAL(loadFinished(bool)), this, SLOT(headersLoaded(bool)));
connect(&hfLoader, SIGNAL(error(QString)), this, SLOT(forwardError(QString)));
connect(&hfLoader, SIGNAL(warning(QString)), this, SLOT(forwardWarning(QString)));
connect(&tocLoader1, SIGNAL(loadProgress(int)), this, SLOT(loadProgress(int)));
connect(&tocLoader1, SIGNAL(loadFinished(bool)), this, SLOT(tocLoaded(bool)));
connect(&tocLoader1, SIGNAL(error(QString)), this, SLOT(forwardError(QString)));
connect(&tocLoader1, SIGNAL(warning(QString)), this, SLOT(forwardWarning(QString)));
connect(&tocLoader2, SIGNAL(loadProgress(int)), this, SLOT(loadProgress(int)));
connect(&tocLoader2, SIGNAL(loadFinished(bool)), this, SLOT(tocLoaded(bool)));
connect(&tocLoader2, SIGNAL(error(QString)), this, SLOT(forwardError(QString)));
connect(&tocLoader2, SIGNAL(warning(QString)), this, SLOT(forwardWarning(QString)));
#endif
if ( ! settings.viewportSize.isEmpty())
{
QStringList viewportSizeList = settings.viewportSize.split("x");
int width = viewportSizeList.first().toInt();
int height = viewportSizeList.last().toInt();
viewportSize = QSize(width,height);
}
}
PdfConverterPrivate::~PdfConverterPrivate() {
clearResources();
}
void PdfConverterPrivate::beginConvert() {
error=false;
progressString = "0%";
currentPhase=0;
errorCode=0;
#ifndef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
if (objects.size() > 1) {
emit out.error("This version of wkhtmltopdf is built against an unpatched version of QT, and does not support more than one input document.");
fail();
return;
}
#else
bool headerHeightsCalcNeeded = false;
#endif
for (QList<PageObject>::iterator i=objects.begin(); i != objects.end(); ++i) {
PageObject & o=*i;
settings::PdfObject & s = o.settings;
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
if (!s.header.htmlUrl.isEmpty() ) {
if (looksLikeHtmlAndNotAUrl(s.header.htmlUrl)) {
emit out.error("--header-html should be a URL and not a string containing HTML code.");
fail();
return;
}
// we should auto calculate header if top margin is not specified
if (settings.margin.top.first == -1) {
headerHeightsCalcNeeded = true;
o.measuringHeader = &measuringHFLoader.addResource(
MultiPageLoader::guessUrlFromString(s.header.htmlUrl), s.load)->page;
} else {
// or just set static values
// add spacing to prevent moving header out of page
o.headerReserveHeight = settings.margin.top.first + s.header.spacing;
}
}
if (!s.footer.htmlUrl.isEmpty()) {
if (looksLikeHtmlAndNotAUrl(s.footer.htmlUrl)) {
emit out.error("--footer-html should be a URL and not a string containing HTML code.");
fail();
return;
}
if (settings.margin.bottom.first == -1) {
// we should auto calculate footer if top margin is not specified
headerHeightsCalcNeeded = true;
o.measuringFooter = &measuringHFLoader.addResource(
MultiPageLoader::guessUrlFromString(s.footer.htmlUrl), s.load)->page;
} else {
// or just set static values
// add spacing to prevent moving footer out of page
o.footerReserveHeight = settings.margin.bottom.first + s.footer.spacing;
}
}
#endif
if (!s.isTableOfContent) {
o.loaderObject = pageLoader.addResource(s.page, s.load, &o.data);
o.page = &o.loaderObject->page;
PageObject::webPageToObject[o.page] = &o;
updateWebSettings(o.page->settings(), s.web);
}
}
emit out.phaseChanged();
loadProgress(0);
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
if (headerHeightsCalcNeeded) {
// preload header/footer to check their heights
measuringHFLoader.load();
} else {
// set defaults if top or bottom mergin is not specified
if (settings.margin.top.first == -1) {
settings.margin.top.first = 10;
}
if (settings.margin.bottom.first == -1) {
settings.margin.bottom.first = 10;
}
for (QList<PageObject>::iterator i=objects.begin(); i != objects.end(); ++i) {
PageObject & o=*i;
o.headerReserveHeight = settings.margin.top.first;
o.footerReserveHeight = settings.margin.bottom.first;
}
pageLoader.load();
}
#else
pageLoader.load();
#endif
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
// calculates header/footer height
// returns millimeters
qreal PdfConverterPrivate::calculateHeaderHeight(PageObject & object, QWebPage & header) {
Q_UNUSED(object);
TempFile tempObj;
QString tempFile = tempObj.create(".pdf");
QPainter * testPainter = new QPainter();
QPrinter * testPrinter = createPrinter(tempFile);
if (!testPainter->begin(testPrinter)) {
emit out.error("Unable to write to temp location");
return 0.0;
}
QWebPrinter wp(header.mainFrame(), testPrinter, *testPainter);
qreal height = wp.elementLocation(header.mainFrame()->findFirstElement("body")).second.height();
delete testPainter;
delete testPrinter;
return (height / PdfConverter::millimeterToPointMultiplier);
}
#endif
QPrinter * PdfConverterPrivate::createPrinter(const QString & tempFile) {
QPrinter * printer = new QPrinter(settings.resolution);
//Tell the printer object to print the file <out>
printer->setOutputFileName(tempFile);
printer->setOutputFormat(QPrinter::PdfFormat);
printer->setResolution(settings.dpi);
if ((settings.size.height.first != -1) && (settings.size.width.first != -1)) {
printer->setPaperSize(QSizeF(settings.size.width.first,settings.size.height.first + 100), settings.size.height.second);
} else {
printer->setPaperSize(settings.size.pageSize);
}
printer->setOrientation(settings.orientation);
printer->setColorMode(settings.colorMode);
printer->setCreator("wkhtmltopdf " STRINGIZE(FULL_VERSION));
return printer;
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
void PdfConverterPrivate::preprocessPage(PageObject & obj) {
currentObject++;
if (obj.settings.isTableOfContent) {
obj.pageCount = 1;
pageCount += 1;
outline->addEmptyWebPage();
return;
}
if (!obj.loaderObject || obj.loaderObject->skip) return;
int tot = objects.size();
progressString = QString("Object ")+QString::number(currentObject)+QString(" of ")+QString::number(tot);
emit out.progressChanged((currentObject)*100 / tot);
painter->save();
if (viewportSize.isValid() && ! viewportSize.isEmpty()) {
obj.page->setViewportSize(viewportSize);
obj.page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff);
obj.page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff);
}
obj.web_printer = new QWebPrinter(obj.page->mainFrame(), printer, *painter);
obj.pageCount = obj.settings.pagesCount? obj.web_printer->pageCount(): 0;
pageCount += obj.pageCount;
if (obj.settings.includeInOutline)
outline->addWebPage(obj.page->mainFrame()->title(), *obj.web_printer, obj.page->mainFrame(),
obj.settings, obj.localLinks, obj.anchors);
else
outline->addEmptyWebPage();
painter->restore();
}
#endif
/*!
* Prepares printing out the document to the pdf file
*/
void PdfConverterPrivate::pagesLoaded(bool ok) {
if (errorCode == 0) errorCode = pageLoader.httpErrorCode();
if (!ok) {
fail();
return;
}
lout = settings.out;
if (settings.out == "-") {
#ifndef Q_OS_WIN32
if (QFile::exists("/dev/stdout"))
lout = "/dev/stdout";
else
#endif
lout = tempOut.create(".pdf");
}
if (settings.out.isEmpty())
lout = tempOut.create(".pdf");
printer = new QPrinter(settings.resolution);
//Tell the printer object to print the file <out>
printer->setOutputFileName(lout);
printer->setOutputFormat(QPrinter::PdfFormat);
printer->setResolution(settings.dpi);
//We currently only support margins with the same unit
if (settings.margin.left.second != settings.margin.right.second ||
settings.margin.left.second != settings.margin.top.second ||
settings.margin.left.second != settings.margin.bottom.second) {
emit out.error("Currently all margin units must be the same!");
fail();
return;
}
//Setup margins and papersize
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
double maxHeaderHeight = objects[0].headerReserveHeight;
double maxFooterHeight = objects[0].footerReserveHeight;
for (QList<PageObject>::iterator i=objects.begin(); i != objects.end(); ++i) {
PageObject & o=*i;
maxHeaderHeight = std::max(maxHeaderHeight, o.headerReserveHeight);
maxFooterHeight = std::max(maxFooterHeight, o.footerReserveHeight);
}
printer->setPageMargins(settings.margin.left.first, maxHeaderHeight,
settings.margin.right.first, maxFooterHeight,
settings.margin.left.second);
#else
printer->setPageMargins(settings.margin.left.first, settings.margin.top.first,
settings.margin.right.first, settings.margin.bottom.first,
settings.margin.left.second);
#endif
if ((settings.size.height.first != -1) && (settings.size.width.first != -1)) {
printer->setPaperSize(QSizeF(settings.size.width.first,settings.size.height.first), settings.size.height.second);
} else {
printer->setPaperSize(settings.size.pageSize);
}
printer->setOrientation(settings.orientation);
printer->setColorMode(settings.colorMode);
printer->setCreator("wkhtmltopdf " STRINGIZE(FULL_VERSION));
if (!printer->isValid()) {
emit out.error("Unable to write to destination");
fail();
return;
}
#ifndef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
//If you do not have the hacks you get this crappy solution
printer->setCopyCount(settings.copies);
printer->setCollateCopies(settings.collate);
printDocument();
#else
printer->printEngine()->setProperty(QPrintEngine::PPK_UseCompression, settings.useCompression);
printer->printEngine()->setProperty(QPrintEngine::PPK_ImageQuality, settings.imageQuality);
printer->printEngine()->setProperty(QPrintEngine::PPK_ImageDPI, settings.imageDPI);
painter = new QPainter();
title = settings.documentTitle;
for (int d=0; d < objects.size(); ++d) {
if (title != "") break;
if (!objects[d].loaderObject || objects[d].loaderObject->skip ||
objects[d].settings.isTableOfContent) continue;
title = objects[d].page->mainFrame()->title();
}
printer->setDocName(title);
if (!painter->begin(printer)) {
emit out.error("Unable to write to destination");
fail();
return;
}
currentPhase = 1;
emit out.phaseChanged();
outline = new Outline(settings);
//This is the first render face, it is done to calculate:
// * The number of pages of each document
// * A visual ordering of the header element
// * The location and page number of each header
pageCount = 0;
currentObject = 0;
for (int d=0; d < objects.size(); ++d)
preprocessPage(objects[d]);
actualPages = pageCount * settings.copies;
loadTocs();
#endif
}
void PdfConverterPrivate::loadHeaders() {
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
currentPhase = 4;
emit out.phaseChanged();
bool hf=false;
int pageNumber=1;
for (int d=0; d < objects.size(); ++d) {
PageObject & obj = objects[d];
if (!obj.loaderObject || obj.loaderObject->skip) continue;
settings::PdfObject & ps = obj.settings;
for (int op=0; op < obj.pageCount; ++op) {
if (!ps.header.htmlUrl.isEmpty() || !ps.footer.htmlUrl.isEmpty()) {
QHash<QString, QString> parms;
fillParms(parms, pageNumber, obj);
parms["sitepage"] = QString::number(op+1);
parms["sitepages"] = QString::number(obj.pageCount);
hf = true;
if (!ps.header.htmlUrl.isEmpty())
obj.headers.push_back(loadHeaderFooter(ps.header.htmlUrl, parms, ps) );
if (!ps.footer.htmlUrl.isEmpty()) {
obj.footers.push_back(loadHeaderFooter(ps.footer.htmlUrl, parms, ps) );
}
}
if (ps.pagesCount) ++pageNumber;
}
}
if (hf)
hfLoader.load();
else
printDocument();
#endif
}
void PdfConverterPrivate::loadTocs() {
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
std::swap(tocLoaderOld, tocLoader);
tocLoader->clearResources();
bool toc = false;
for (int d=0; d < objects.size(); ++d) {
PageObject & obj = objects[d];
settings::PdfObject & ps = obj.settings;
if (!ps.isTableOfContent) continue;
obj.clear();
QString style = ps.tocXsl;
if (style.isEmpty()) {
style = obj.tocFile.create(".xsl");
StreamDumper styleDump(style);
dumpDefaultTOCStyleSheet(styleDump.stream, ps.toc);
}
QString path = obj.tocFile.create(".xml");
StreamDumper sd(path);
outline->dump(sd.stream);
QFile styleFile(style);
if (!styleFile.open(QIODevice::ReadOnly)) {
emit out.error("Could not read the TOC XSL");
fail();
}
QFile xmlFile(path);
if (!xmlFile.open(QIODevice::ReadOnly)) {
emit out.error("Could not read the TOC XML");
fail();
}
QString htmlPath = obj.tocFile.create(".html");
QFile htmlFile(htmlPath);
if (!htmlFile.open(QIODevice::WriteOnly)) {
emit out.error("Could not open the TOC for writing");
fail();
}
QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(&xmlFile);
query.setQuery(&styleFile);
query.evaluateTo(&htmlFile);
obj.loaderObject = tocLoader->addResource(htmlPath, ps.load);
obj.page = &obj.loaderObject->page;
PageObject::webPageToObject[obj.page] = &obj;
updateWebSettings(obj.page->settings(), ps.web);
toc= true;
}
if (toc) {
if (currentPhase != 2) {
currentPhase = 2;
emit out.phaseChanged();
}
tocLoader->load();
} else
tocLoaded(true);
#endif
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
void PdfConverterPrivate::findLinks(QWebFrame * frame, QVector<QPair<QWebElement, QString> > & local, QVector<QPair<QWebElement, QString> > & external, QHash<QString, QWebElement> & anchors) {
bool ulocal=true, uexternal=true;
if (PageObject::webPageToObject.contains(frame->page())) {
ulocal = PageObject::webPageToObject[frame->page()]->settings.useLocalLinks;
uexternal = PageObject::webPageToObject[frame->page()]->settings.useExternalLinks;
}
if (!ulocal && !uexternal) return;
foreach (const QWebElement & elm, frame->findAllElements("a")) {
QString n=elm.attribute("name");
if (n.isEmpty()) n=elm.attribute("ns0:name");
if (n.startsWith("__WKANCHOR_")) anchors[n] = elm;
QString h=elm.attribute("href");
if (h.isEmpty()) h=elm.attribute("ns0:href");
if (h.startsWith("__WKANCHOR_")) {
local.push_back( qMakePair(elm, h) );
} else {
QUrl href(h);
if (href.isEmpty()) continue;
href=frame->baseUrl().resolved(href);
QString key = QUrl::fromPercentEncoding(href.toString(QUrl::RemoveFragment).toLocal8Bit());
if (urlToPageObj.contains(key)) {
if (ulocal) {
PageObject * p = urlToPageObj[key];
QWebElement e;
if (!href.hasFragment())
e = p->page->mainFrame()->findFirstElement("body");
else {
e = p->page->mainFrame()->findFirstElement("a[name=\""+href.fragment()+"\"]");
if (e.isNull())
e = p->page->mainFrame()->findFirstElement("*[id=\""+href.fragment()+"\"]");
if (e.isNull())
e = p->page->mainFrame()->findFirstElement("*[name=\""+href.fragment()+"\"]");
}
if (!e.isNull()) {
p->anchors[href.toString()] = e;
local.push_back( qMakePair(elm, href.toString()) );
}
}
} else if (uexternal) {
external.push_back( qMakePair(elm, settings.resolveRelativeLinks ? href.toString() : h) );
}
}
}
}
void PdfConverterPrivate::fillParms(QHash<QString, QString> & parms, int page, const PageObject & object) {
outline->fillHeaderFooterParms(page, parms, object.settings);
parms["doctitle"] = title;
parms["title"] = object.page?object.page->mainFrame()->title():"";
QDateTime t(QDateTime::currentDateTime());
parms["time"] = t.time().toString(Qt::SystemLocaleShortDate);
parms["date"] = t.date().toString(Qt::SystemLocaleShortDate);
parms["isodate"] = t.date().toString(Qt::ISODate);
}
void PdfConverterPrivate::endPage(PageObject & object, bool hasHeaderFooter, int objectPage, int pageNumber) {
typedef QPair<QWebElement, QString> p_t;
settings::PdfObject & s = object.settings;
// save margin values
qreal leftMargin, topMargin, rightMargin, bottomMargin;
printer->getPageMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin, settings.margin.left.second);
if (hasHeaderFooter) {
QHash<QString, QString> parms;
fillParms(parms, pageNumber, object);
parms["sitepage"] = QString::number(objectPage+1);
parms["sitepages"] = QString::number(object.pageCount);
//Webkit used all kinds of crazy coordinate transformation, and font setup
//We save it here and restore some sane defaults
painter->save();
painter->resetTransform();
int h=printer->height();
int w=printer->width();
double spacing = s.header.spacing * printer->height() / printer->heightMM();
//If needed draw the header line
if (s.header.line) painter->drawLine(0, -spacing, w, -spacing);
//Guess the height of the header text
painter->setFont(QFont(s.header.fontName, s.header.fontSize));
int dy = painter->boundingRect(0, 0, w, h, Qt::AlignTop, "M").height();
//Draw the header text
QRect r=QRect(0, 0-dy-spacing, w, h);
painter->drawText(r, Qt::AlignTop | Qt::AlignLeft, hfreplace(s.header.left, parms));
painter->drawText(r, Qt::AlignTop | Qt::AlignHCenter, hfreplace(s.header.center, parms));
painter->drawText(r, Qt::AlignTop | Qt::AlignRight, hfreplace(s.header.right, parms));
spacing = s.footer.spacing * printer->height() / printer->heightMM();
//IF needed draw the footer line
if (s.footer.line) painter->drawLine(0, h + spacing, w, h + spacing);
//Guess the height of the footer text
painter->setFont(QFont(s.footer.fontName, s.footer.fontSize));
dy = painter->boundingRect(0, 0, w, h, Qt::AlignTop, "M").height();
//Draw the footer text
r=QRect(0,0,w,h+dy+ spacing);
painter->drawText(r, Qt::AlignBottom | Qt::AlignLeft, hfreplace(s.footer.left, parms));
painter->drawText(r, Qt::AlignBottom | Qt::AlignHCenter, hfreplace(s.footer.center, parms));
painter->drawText(r, Qt::AlignBottom | Qt::AlignRight, hfreplace(s.footer.right, parms));
//Restore Webkit's crazy scaling and font settings
painter->restore();
}
//if (!object.headers.empty()) {
//object.headers[objectPage];
if (currentHeader) {
QWebPage * header = currentHeader;
updateWebSettings(header->settings(), object.settings.web);
painter->save();
painter->resetTransform();
QPalette pal = header->palette();
pal.setBrush(QPalette::Base, Qt::transparent);
header->setPalette(pal);
double spacing = s.header.spacing * printer->height() / printer->heightMM();
// clear vertical margins for proper header rendering
printer->setPageMargins(leftMargin, 0, rightMargin, 0, settings.margin.left.second);
painter->translate(0, -spacing);
QWebPrinter wp(header->mainFrame(), printer, *painter);
painter->translate(0,-wp.elementLocation(header->mainFrame()->findFirstElement("body")).second.height());
QVector<p_t> local;
QVector<p_t> external;
QHash<QString, QWebElement> anchors;
findLinks(header->mainFrame(), local, external, anchors);
foreach (const p_t & p, local) {
QRectF r = wp.elementLocation(p.first).second;
painter->addLink(r, p.second);
}
foreach (const p_t & p, external) {
QRectF r = wp.elementLocation(p.first).second;
painter->addHyperlink(r, QUrl(p.second));
}
wp.spoolPage(1);
// restore margins
printer->setPageMargins(leftMargin, topMargin, rightMargin, bottomMargin, settings.margin.left.second);
painter->restore();
}
if (currentFooter) {
QWebPage * footer=currentFooter;
updateWebSettings(footer->settings(), object.settings.web);
painter->save();
painter->resetTransform();
QPalette pal = footer->palette();
pal.setBrush(QPalette::Base, Qt::transparent);
footer->setPalette(pal);
double spacing = s.footer.spacing * printer->height() / printer->heightMM();
painter->translate(0, printer->height()+ spacing);
// clear vertical margins for proper header rendering
printer->setPageMargins(leftMargin, 0, rightMargin, 0, settings.margin.left.second);
QWebPrinter wp(footer->mainFrame(), printer, *painter);
QVector<p_t> local;
QVector<p_t> external;
QHash<QString, QWebElement> anchors;
findLinks(footer->mainFrame(), local, external, anchors);
foreach (const p_t & p, local) {
QRectF r = wp.elementLocation(p.first).second;
painter->addLink(r, p.second);
}
foreach (const p_t & p, external) {
QRectF r = wp.elementLocation(p.first).second;
painter->addHyperlink(r, QUrl(p.second));
}
wp.spoolPage(1);
// restore margins
printer->setPageMargins(leftMargin, topMargin, rightMargin, bottomMargin, settings.margin.left.second);
painter->restore();
}
}
void PdfConverterPrivate::handleTocPage(PageObject & obj) {
painter->save();
QWebPrinter wp(obj.page->mainFrame(), printer, *painter);
int pc = obj.settings.pagesCount? wp.pageCount(): 0;
if (pc != obj.pageCount) {
obj.pageCount = pc;
tocChanged=true;
}
pageCount += obj.pageCount;
tocChanged = outline->replaceWebPage(obj.number, obj.settings.toc.captionText, wp, obj.page->mainFrame(), obj.settings, obj.localLinks, obj.anchors) || tocChanged;
painter->restore();
}
#endif
void PdfConverterPrivate::tocLoaded(bool ok) {
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
if (errorCode == 0) errorCode = tocLoader->httpErrorCode();
#endif
if (!ok) {
fail();
return;
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
tocChanged = false;
pageCount = 0;
currentObject = 0;
for (int d=0; d < objects.size(); ++d) {
++currentObject;
if (!objects[d].loaderObject || objects[d].loaderObject->skip) continue;
if (!objects[d].settings.isTableOfContent) {
pageCount += objects[d].pageCount;
continue;
}
handleTocPage(objects[d]);
}
actualPages = pageCount * settings.copies;
if (tocChanged)
loadTocs();
else {
//Find and resolve all local links
currentPhase = 3;
emit out.phaseChanged();
QHash<QString, int> urlToDoc;
for (int d=0; d < objects.size(); ++d) {
if (!objects[d].loaderObject || objects[d].loaderObject->skip) continue;
if (objects[d].settings.isTableOfContent) continue;
urlToPageObj[ QUrl::fromPercentEncoding(objects[d].page->mainFrame()->url().toString(QUrl::RemoveFragment).toLocal8Bit()) ] = &objects[d];
}
for (int d=0; d < objects.size(); ++d) {
if (!objects[d].loaderObject || objects[d].loaderObject->skip) continue;
progressString = QString("Object ")+QString::number(d+1)+QString(" of ")+QString::number(objects.size());
emit out.progressChanged((d+1)*100 / objects.size());
findLinks(objects[d].page->mainFrame(), objects[d].localLinks, objects[d].externalLinks, objects[d].anchors );
}
loadHeaders();
}
#endif
}
void PdfConverterPrivate::measuringHeadersLoaded(bool ok) {
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
if (errorCode == 0) errorCode = measuringHFLoader.httpErrorCode();
#endif
if (!ok) {
fail();
return;
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
for (int d=0; d < objects.size(); ++d) {
PageObject & obj = objects[d];
if (obj.measuringHeader) {
// add spacing to prevent moving header out of page
obj.headerReserveHeight = calculateHeaderHeight(obj, *obj.measuringHeader) + obj.settings.header.spacing;
}
if (obj.measuringFooter) {
// add spacing to prevent moving footer out of page
obj.footerReserveHeight = calculateHeaderHeight(obj, *obj.measuringFooter) + obj.settings.footer.spacing;
}
}
#endif
pageLoader.load();
}
void PdfConverterPrivate::headersLoaded(bool ok) {
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
if (errorCode == 0) errorCode = hfLoader.httpErrorCode();
#endif
if (!ok) {
fail();
return;
}
printDocument();
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
void PdfConverterPrivate::spoolPage(int page) {
progressString = QString("Page ") + QString::number(actualPage) + QString(" of ") + QString::number(actualPages);
emit out.progressChanged(actualPage * 100 / actualPages);
if (actualPage != 1)
printer->newPage();
QWebPrinter *webPrinter = objects[currentObject].web_printer;
webPrinter->spoolPage(page+1);
foreach (QWebElement elm, pageFormElements[page+1]) {
QString type = elm.attribute("type");
QString tn = elm.tagName();
QString name = elm.attribute("name");
if (tn == "TEXTAREA" || type == "text" || type == "password") {
painter->addTextField(
webPrinter->elementLocation(elm).second,
tn == "TEXTAREA"?elm.toPlainText():elm.attribute("value"),
name,
tn == "TEXTAREA",
type == "password",
elm.evaluateJavaScript("this.readOnly;").toBool(),
elm.hasAttribute("maxlength")?elm.attribute("maxlength").toInt():-1
);
} else if (type == "checkbox") {
painter->addCheckBox(
webPrinter->elementLocation(elm).second,
elm.evaluateJavaScript("this.checked;").toBool(),
name,
elm.evaluateJavaScript("this.readOnly;").toBool());
}
}
for (QHash<QString, QWebElement>::iterator i=pageAnchors[page+1].begin();
i != pageAnchors[page+1].end(); ++i) {
QRectF r = webPrinter->elementLocation(i.value()).second;
painter->addAnchor(r, i.key());
}
for (QVector< QPair<QWebElement,QString> >::iterator i=pageLocalLinks[page+1].begin();
i != pageLocalLinks[page+1].end(); ++i) {
QRectF r = webPrinter->elementLocation(i->first).second;
painter->addLink(r, i->second);
}
for (QVector< QPair<QWebElement,QString> >::iterator i=pageExternalLinks[page+1].begin();
i != pageExternalLinks[page+1].end(); ++i) {
QRectF r = webPrinter->elementLocation(i->first).second;
painter->addHyperlink(r, QUrl(i->second));
}
endPage(objects[currentObject], pageHasHeaderFooter, page, pageNumber);
actualPage++;
}
void PdfConverterPrivate::spoolTo(int page) {
int pc=settings.collate?1:settings.copies;
const settings::PdfObject & ps = objects[currentObject].settings;
while (objectPage < page) {
for (int pc_=0; pc_ < pc; ++pc_)
spoolPage(objectPage);
if (ps.pagesCount) ++pageNumber;
++objectPage;
//TODO free header and footer
currentHeader=NULL;
currentFooter=NULL;
}
}
void PdfConverterPrivate::beginPrintObject(PageObject & obj) {
if (obj.number != 0)
endPrintObject(objects[obj.number-1]);
currentObject = obj.number;
if (!obj.loaderObject || obj.loaderObject->skip)
return;
QWebPrinter *webPrinter = objects[currentObject].web_printer;
if (webPrinter == 0)
webPrinter = objects[currentObject].web_printer = \
new QWebPrinter(obj.page->mainFrame(), printer, *painter);
QPalette pal = obj.loaderObject->page.palette();
pal.setBrush(QPalette::Base, Qt::transparent);
obj.loaderObject->page.setPalette(pal);
const settings::PdfObject & ps = obj.settings;
pageHasHeaderFooter = ps.header.line || ps.footer.line ||
!ps.header.left.isEmpty() || !ps.footer.left.isEmpty() ||
!ps.header.center.isEmpty() || !ps.footer.center.isEmpty() ||
!ps.header.right.isEmpty() || !ps.footer.right.isEmpty();
painter->save();
if (ps.produceForms) {
foreach (QWebElement elm, obj.page->mainFrame()->findAllElements("input"))
elm.setStyleProperty("color","white");
foreach (QWebElement elm, obj.page->mainFrame()->findAllElements("textarea"))
elm.setStyleProperty("color","white");
}
outline->fillAnchors(obj.number, obj.anchors);
//Sort anchors and links by page
for (QHash<QString, QWebElement>::iterator i=obj.anchors.begin();
i != obj.anchors.end(); ++i)
pageAnchors[webPrinter->elementLocation(i.value()).first][i.key()] = i.value();
for (QVector< QPair<QWebElement,QString> >::iterator i=obj.localLinks.begin();
i != obj.localLinks.end(); ++i)
pageLocalLinks[webPrinter->elementLocation(i->first).first].push_back(*i);
for (QVector< QPair<QWebElement,QString> >::iterator i=obj.externalLinks.begin();
i != obj.externalLinks.end(); ++i)
pageExternalLinks[webPrinter->elementLocation(i->first).first].push_back(*i);
if (ps.produceForms) {
foreach (const QWebElement & elm, obj.page->mainFrame()->findAllElements("input"))
pageFormElements[webPrinter->elementLocation(elm).first].push_back(elm);
foreach (const QWebElement & elm, obj.page->mainFrame()->findAllElements("textarea"))
pageFormElements[webPrinter->elementLocation(elm).first].push_back(elm);
}
emit out.producingForms(obj.settings.produceForms);
out.emitCheckboxSvgs(obj.settings.load);
objectPage = 0;
}
void PdfConverterPrivate::handleHeader(QWebPage * frame, int page) {
spoolTo(page);
currentHeader = frame;
}
void PdfConverterPrivate::handleFooter(QWebPage * frame, int page) {
spoolTo(page);
currentFooter = frame;
}
void PdfConverterPrivate::endPrintObject(PageObject & obj) {
Q_UNUSED(obj);
// If this page was skipped, we might not have
// anything to spool to printer..
if (obj.web_printer != 0) spoolTo(obj.web_printer->pageCount());
pageAnchors.clear();
pageLocalLinks.clear();
pageExternalLinks.clear();
pageFormElements.clear();
if (obj.web_printer != 0) {
delete obj.web_printer;
obj.web_printer = 0;
painter->restore();
}
}
#endif
void PdfConverterPrivate::printDocument() {
#ifndef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
currentPhase = 1;
emit out.phaseChanged();
objects[0].page->mainFrame()->print(printer);
progressString = "";
emit out.progressChanged(-1);
#else
actualPage=1;
int cc=settings.collate?settings.copies:1;
currentPhase = 5;
emit out.phaseChanged();
progressString = "Preparing";
emit out.progressChanged(0);
for (int cc_=0; cc_ < cc; ++cc_) {
pageNumber=1;
for (int d=0; d < objects.size(); ++d) {
beginPrintObject(objects[d]);
// XXX: In some cases nothing gets loaded at all,
// so we would get no webPrinter instance.
int pageCount = objects[d].web_printer != 0 ? objects[d].web_printer->pageCount() : 0;
//const settings::PdfObject & ps = objects[d].settings;
for(int i=0; i < pageCount; ++i) {
if (!objects[d].headers.empty())
handleHeader(objects[d].headers[i], i);
if (!objects[d].footers.empty())
handleFooter(objects[d].footers[i], i);
}
}
endPrintObject(objects[objects.size()-1]);
}
outline->printOutline(printer);
if (!settings.dumpOutline.isEmpty()) {
StreamDumper sd(settings.dumpOutline);
outline->dump(sd.stream);
}
painter->end();
#endif
if (settings.out == "-" && lout != "/dev/stdout") {
QFile i(lout);
QFile o;
#ifdef Q_OS_WIN32
_setmode(_fileno(stdout), _O_BINARY);
#endif
if ( !i.open(QIODevice::ReadOnly) ||
!o.open(stdout,QIODevice::WriteOnly) ||
!MultiPageLoader::copyFile(i,o) ) {
emit out.error("Count not write to stdout");
tempOut.removeAll();
fail();
return;
}
tempOut.removeAll();
}
if (settings.out.isEmpty()) {
QFile i(lout);
if (!i.open(QIODevice::ReadOnly)) {
emit out.error("Reading output failed");
tempOut.removeAll();
fail();
}
outputData = i.readAll();
i.close();
tempOut.removeAll();
}
clearResources();
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
currentPhase = 6;
#else
currentPhase = 2;
#endif
emit out.phaseChanged();
conversionDone = true;
emit out.finished(true);
qApp->exit(0); // quit qt's event handling
}
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
QWebPage * PdfConverterPrivate::loadHeaderFooter(QString url, const QHash<QString, QString> & parms, const settings::PdfObject & ps) {
QUrl u = MultiPageLoader::guessUrlFromString(url);
for (QHash<QString, QString>::const_iterator i=parms.begin(); i != parms.end(); ++i)
u.addQueryItem(i.key(), i.value());
return &hfLoader.addResource(u, ps.load)->page;
}
/*!
* Replace some variables in a string used in a header or footer
* \param q the string to substitute in
*/
QString PdfConverterPrivate::hfreplace(const QString & q, const QHash<QString, QString> & parms) {
QString r=q;
for (QHash<QString, QString>::const_iterator i=parms.begin(); i != parms.end(); ++i)
r=r.replace("["+i.key()+"]", i.value(), Qt::CaseInsensitive);
return r;
}
#endif
void PdfConverterPrivate::clearResources() {
objects.clear();
pageLoader.clearResources();
#ifdef __EXTENSIVE_WKHTMLTOPDF_QT_HACK__
hfLoader.clearResources();
tocLoader1.clearResources();
tocLoader2.clearResources();
if (outline) {
Outline * tmp = outline;
outline = 0;
delete tmp;
}
#endif
if (printer) {
QPrinter * tmp = printer;
printer = 0;
delete tmp;
}
if (painter) {
QPainter * tmp = painter;
painter = 0;
delete tmp;
}
}
Converter & PdfConverterPrivate::outer() {
return out;
}
/*!
\class PdfConverter
\brief Class responsible for converting html pages to pdf
\todo explain something about the conversion process here, and mention stages
*/
/*!
\brief Create a page converter object based on the supplied settings
\param settings Settings for the conversion
*/
PdfConverter::PdfConverter(settings::PdfGlobal & settings):
d(new PdfConverterPrivate(settings, *this)) {
}
/*!
\brief The destructor for the page converter object
*/
PdfConverter::~PdfConverter() {
PdfConverterPrivate *tmp = d;
d = 0;
tmp->deleteLater();;
}
/*!
\brief add a resource we want to convert
\param url The url of the object we want to convert
*/
void PdfConverter::addResource(const settings::PdfObject & page, const QString * data) {
d->objects.push_back( PageObject(page, data) );
d->objects.back().number = d->objects.size()-1;
}
const QByteArray & PdfConverter::output() {
return d->outputData;
}
/*!
\brief Returns the settings object associated with the page converter
*/
const settings::PdfGlobal & PdfConverter::globalSettings() const {
return d->settings;
}
/*!
\fn PdfConverter::warning(const QString & message)
\brief Signal emitted when some non fatal warning occurs during conversion
\param message The warning message
*/
/*!
\fn PdfConverter::error(const QString & message)
\brief Signal emitted when a fatal error has occurred during conversion
\param message A message describing the fatal error
*/
/*!
\fn PdfConverter::phaseChanged()
\brief Signal emitted when the converter has reached a new phase
*/
/*!
\fn PdfConverter::progressChanged()
\brief Signal emitted when some progress has been done in the conversion phase
*/
/*!
\fn PdfConverter::finised()
\brief Signal emitted when conversion has finished.
*/
ConverterPrivate & PdfConverter::priv() {
return *d;
}
| 32.358459 | 192 | 0.694637 | [
"render",
"object"
] |
2e2d8b61ae26d3168f1d27bb2d12bbf1fb364935 | 32,736 | cpp | C++ | processData.cpp | BossCuong/DSA2017-A02 | 6498169fe4522fad80c8336470eb0cbcf9fc1adb | [
"MIT"
] | null | null | null | processData.cpp | BossCuong/DSA2017-A02 | 6498169fe4522fad80c8336470eb0cbcf9fc1adb | [
"MIT"
] | null | null | null | processData.cpp | BossCuong/DSA2017-A02 | 6498169fe4522fad80c8336470eb0cbcf9fc1adb | [
"MIT"
] | null | null | null | /*
* ==========================================================================================
* Name : processData.cpp
* Description : student code for Assignment 2 - Data structures and Algorithms - Fall 2017
* ==========================================================================================
*/
#include <iostream>
#include <vector>
#include <functional>
#include <math.h>
#include "requestLib.h"
#include "dbLib.h"
using namespace std;
#define GPS_DISTANCE_ERROR 0.005
struct VM_database
{
char id[ID_MAX_LENGTH];
AVLTree<VM_Record> data;
bool isValid;
// default constructor
VM_database()
{
isValid = true;
id[0] = 0;
}
VM_database(const char *busID)
{
strcpy(id, busID);
isValid = true;
}
};
inline bool operator==(VM_database &lhs, char *rhs)
{
return strcmp(lhs.id, rhs) == 0;
}
inline bool operator==(char *lhs, VM_database &rhs)
{
return strcmp(rhs.id, lhs) == 0;
}
inline bool operator==(VM_database &lhs, VM_database &rhs)
{
return strcmp(lhs.id, rhs.id) == 0;
}
inline bool operator!=(VM_database &lhs, char *rhs)
{
return !(lhs == rhs);
}
inline bool operator!=(char *lhs, VM_database &rhs)
{
return !(rhs == lhs);
}
inline bool operator!=(VM_database &lhs, VM_database &rhs)
{
return !(lhs == rhs);
}
inline bool operator>(VM_database &lhs, char *rhs)
{
return strcmp(lhs.id, rhs) > 0;
}
inline bool operator>(char *lhs, VM_database &rhs)
{
return strcmp(rhs.id, lhs) > 0;
}
inline bool operator>(VM_database &lhs, VM_database &rhs)
{
return strcmp(lhs.id, rhs.id) > 0;
}
inline bool operator<(VM_database &lhs, char *rhs)
{
return strcmp(lhs.id, rhs) < 0;
}
inline bool operator<(char *lhs, VM_database &rhs)
{
return strcmp(rhs.id, lhs) < 0;
}
inline bool operator<(VM_database &lhs, VM_database &rhs)
{
return strcmp(lhs.id, rhs.id) < 0;
}
inline bool operator>=(VM_database &lhs, char *rhs)
{
return strcmp(lhs.id, rhs) >= 0;
}
inline bool operator>=(char *lhs, VM_database &rhs)
{
return strcmp(rhs.id, lhs) >= 0;
}
inline bool operator>=(VM_database &lhs, VM_database &rhs)
{
return strcmp(lhs.id, rhs.id) >= 0;
}
inline bool operator<=(VM_database &lhs, char *rhs)
{
return strcmp(lhs.id, rhs) <= 0;
}
inline bool operator<=(char *lhs, VM_database &rhs)
{
return strcmp(rhs.id, lhs) <= 0;
}
inline bool operator<=(VM_database &lhs, VM_database &rhs)
{
return strcmp(lhs.id, rhs.id) <= 0;
}
bool initVMGlobalData(void **pGData)
{
// TODO: allocate and initialize global data
*pGData = new AVLTree<VM_database>();
// return false if failed
return true;
}
void releaseVMGlobalData(void *pGData)
{
// TODO: do your cleanup, left this empty if you don't have any dynamically allocated data
delete (AVLTree<VM_database> *)pGData;
}
struct re7_database
{
char id[ID_MAX_LENGTH];
double distance;
re7_database()
{
id[0] = 0;
distance = 0;
}
};
inline bool operator<(re7_database &lhs, re7_database &rhs)
{
return lhs.distance < rhs.distance;
}
inline bool operator>=(re7_database &lhs, re7_database &rhs)
{
return lhs.distance >= rhs.distance;
}
struct request_data
{
void* pData;
double longitude;
double latitude;
int number_of_VM;
time_t t1,t2;
double radius;
int h1, h2;
bool isOutCircle;
int cnt;
int percent_cnt;
double min_distance;
L1List<string> lessThan2km;
L1List<string> lessThan2km_greatThan500m;
L1List<string> lessThan500m;
L1List<string> lessThan300m;
double max_distance;
AVLTree<string> lessThan1km_andStuck;
AVLTree<re7_database> lessThan2km_greatThan1km;
AVLTree<string> lessThan2km_greatThan1km_75;
request_data()
{
pData = NULL;
longitude = 0;
latitude = 0;
number_of_VM = 0;
t1 =0;
t2 = 0;
radius =0;
h1 = 0;
h2 = 0;
isOutCircle = true;
cnt = 0;
percent_cnt = 0;
min_distance = -1;
max_distance = -1;
}
};
bool process_request_1(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*re1_parseTime)(time_t &, string &, time_t &) = [](time_t &dest, string &src, time_t &scale) {
//parse time to tm
struct tm *tm = gmtime(&scale);
tm->tm_hour = stoi(src.substr(0, 2));
tm->tm_min = stoi(src.substr(2, 2));
tm->tm_sec = stoi(src.substr(4, 2));
dest = timegm(tm);
};
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
VM_database *x1, *x2;
stringstream stream(request.code);
string buf, time_src;
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
//Key contain ID to find ID in database
if (!getline(stream, buf, '_'))
return false;
VM_database list_key1((char *)buf.data());
if (!getline(stream, buf, '_'))
return false;
VM_database list_key2((char *)buf.data());
if (!getline(stream, buf, '_'))
return false;
time_src = buf;
if (!stream.eof() || time_src.length() != 6)
return false;
//Find ID of VM,return reference of ID database to x1,x2
if (database->find(list_key1, x1) && database->find(list_key2, x2))
{
if (x1->isValid == true && x2->isValid == true)
{
//Get time to key to find in AVL database
VM_Record avl_key;
try{
re1_parseTime(avl_key.timestamp, time_src, recordList[0].timestamp);
}
catch(exception& e)
{
return false;
}
VM_Record *record1, *record2;
//Use time key to find record have time in request,return reference of record to data1,data2
if (x1->data.find(avl_key, record1) && x2->data.find(avl_key, record2))
{
//Set relative of VM
string relative_long, relative_lat;
if ((record1->longitude - record2->longitude) >= 0)
relative_long = "E";
else
relative_long = "W";
if ((record1->latitude - record2->latitude) >= 0)
relative_lat = "N";
else
relative_lat = "S";
//Caculating distance of two VM
double distance = distanceEarth(record1->latitude, record1->longitude, record2->latitude, record2->longitude);
//Print result
cout << request.code[0] << ": " << relative_long << " " << relative_lat << " " << distance;
return true;
}
}
}
//If not find anything
cout << request.code[0] << ": " << "-1";
return true;
}
bool process_request_2(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*process_re2_E)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in East
void (*isNotEast)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
//If find it,set terminate to true to terminate traverse
if (!((record.longitude - ((request_data *)p)->longitude) >= 0))
terminate = true;
};
//Counting valid ID
if (record.isValid)
{
bool terminate = false;
record.data.traverseNLR(isNotEast, p, terminate);
if (!terminate)
((request_data *)p)->cnt++;
}
};
void (*process_re2_W)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in West
void (*isNotWest)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
if (!((record.longitude - ((request_data *)p)->longitude) <= 0))
terminate = true;
};
if (record.isValid)
{
//Counting valid ID
bool terminate = false;
record.data.traverseNLR(isNotWest, p, terminate);
if (!terminate)
((request_data *)p)->cnt++;
}
};
stringstream stream(request.code);
string buf, relative;
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
if(buf != "2") return false;
if (!getline(stream, buf, '_'))
return false;
try{
request.params[0] = stod(buf);
}
catch(exception& e)
{
request.params[0] = 0;
}
if (!getline(stream, buf, '_'))
return false;
relative = buf;
if (!stream.eof() || relative.length() != 1)
return false;
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
void *p = new request_data();
((request_data *)p)->longitude = request.params[0];
((request_data *)p)->cnt = 0;
if (relative == "E")
database->traverseLNR(process_re2_E, p);
else if (relative == "W")
database->traverseLNR(process_re2_W, p);
else
return false;
//Print result
cout << request.code[0] << ": " << ((request_data *)p)->cnt;
delete (request_data *)p;
return true;
}
bool process_request_3(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*process_re3_N)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in North
void (*re3_counting_N)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
if (!((record.latitude - ((request_data *)p)->latitude) >= 0))
terminate = true;
};
if (record.isValid)
{
//Check valid ID
bool terminate = false;
record.data.traverseNLR(re3_counting_N, p, terminate);
if (!terminate)
((request_data *)p)->cnt++;
}
};
void (*process_re3_S)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in South
void (*re3_counting_S)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
if (!((record.latitude - ((request_data *)p)->latitude) <= 0))
terminate = true;
};
if (record.isValid)
{
//Check valid ID
bool terminate = false;
record.data.traverseNLR(re3_counting_S, p, terminate);
if (!terminate)
((request_data *)p)->cnt++;
}
};
stringstream stream(request.code);
string buf, relative;
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
if(buf != "3") return false;
if (!getline(stream, buf, '_'))
return false;
try{
request.params[0] = stod(buf);
}
catch(exception& e)
{
return false;
}
if (!getline(stream, buf, '_'))
return false;
relative = buf;
if (!stream.eof() || relative.length() != 1)
return false;
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
void *p = new request_data();
((request_data *)p)->latitude = request.params[0];
((request_data *)p)->cnt = 0;
if (relative == "N")
database->traverseLNR(process_re3_N, p);
else if (relative == "S")
database->traverseLNR(process_re3_S, p);
else
return false;
//Print result
cout << request.code[0] << ": " << ((request_data *)p)->cnt;
delete (request_data *)p;
return true;
}
bool process_request_4(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*process_re4)(VM_database &, void *) = [](VM_database &record, void *p) {
//Function check if VM go in to circle
void (*re4_counting)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
request_data *re_data = (request_data *)p;
double distance = distanceEarth(re_data->latitude, re_data->longitude, record.latitude, record.longitude);
if (distance <= re_data->radius && record.timestamp >= re_data->h1 && record.timestamp <= re_data->h2)
{
//If true,out from traverse data of ID
((request_data *)p)->cnt++;
terminate = true;
}
};
//Check valid ID
if(record.isValid)
{
bool terminate = false;
record.data.traverseNLR(re4_counting, p, terminate);
}
};
//Get param
void *p = new request_data();
stringstream stream(request.code);
string buf;
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
try{
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->longitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->latitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->radius = stod(buf);
if (!getline(stream, buf, '_'))
return false;
request.params[0] = stoi(buf);
if (!getline(stream, buf, '_'))
return false;
request.params[1] = stoi(buf);
}
catch(exception& e)
{
return false;
}
if(!stream.eof()) return false;
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
//parse time to tm
struct tm *tm = gmtime(&recordList[0].timestamp);
tm->tm_min = 0;
tm->tm_sec = 0;
tm->tm_hour = request.params[0];
((request_data *)p)->h1 = timegm(tm);
tm->tm_hour = request.params[1];
((request_data *)p)->h2 = timegm(tm);
//
database->traverseLNR(process_re4, p);
//Print result
cout << request.code[0] << ": " << ((request_data *)p)->cnt;
delete (request_data *)p;
return true;
}
bool process_request_5(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*re5_counting)(VM_Record &, void *) = [](VM_Record &record, void *p) {
request_data *re_data = (request_data *)p;
double distance = distanceEarth(re_data->latitude, re_data->longitude, record.latitude, record.longitude);
if (distance <= re_data->radius && re_data->isOutCircle == true)
{
re_data->cnt++;
re_data->isOutCircle = false;
}
else if (distance > re_data->radius)
{
re_data->isOutCircle = true;
}
};
stringstream stream(&request.code[2]);
string buf, relative;
if(request.code[1] != '_') return false;
//Init key to find ID in database
if (!getline(stream, buf, '_'))
return false;
VM_database key((char *)buf.data());
int i = 0;
while (getline(stream, buf, '_'))
{
try{
request.params[i] = stod(buf);
}
catch(exception& e)
{
return false;
}
i++;
}
if (i != 3)
return false;
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
void *p = new request_data();
((request_data *)p)->longitude = request.params[0];
((request_data *)p)->latitude = request.params[1];
((request_data *)p)->radius = request.params[2];
((request_data *)p)->isOutCircle = true;
VM_database *x;
//Find VM_database and return it pointer of data to x by reference
if (database->find(key, x))
{
if (x->isValid)
{
//Traverse AVL in data have key ID
x->data.traverseLNR(re5_counting, p);
//Print result
cout << request.code[0] << ": " << ((request_data *)p)->cnt;
return true;
}
}
cout << request.code[0] << ": " << "-1";
delete (request_data *)p;
return true;
}
bool process_request_6(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*parseTime)(time_t &, string &, time_t &) = [](time_t &dest, string &src, time_t &scale) {
//parse time to tm
struct tm *tm = gmtime(&scale);
tm->tm_hour = stoi(src.substr(0, 2));
tm->tm_min = stoi(src.substr(2, 2));
tm->tm_sec = 0;
dest = timegm(tm);
};
void (*re6_counting)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in East
void (*inStation)(VM_Record &, void *,bool&) = [](VM_Record &record, void *p,bool& terminate) {
//If find it,set terminate to true to terminate traverse
request_data *re_data = (request_data *)p;
double distance = distanceEarth(re_data->latitude, re_data->longitude, record.latitude, record.longitude);
if (record.timestamp >= (re_data->t1 - 15*60) && record.timestamp <= (re_data->t1))
{
if(re_data->min_distance < 0) re_data->min_distance = distance;
else if (distance < re_data->min_distance)
{
re_data->min_distance = distance;
}
}
else if(record.timestamp > re_data->t1)
{
terminate = true;
}
};
request_data *re_data = (request_data *)p;
//Counting valid ID
if (record.isValid)
{
re_data->min_distance = -1;
bool terminate = false;
record.data.traverseLNR(inStation, p, terminate);
if (re_data->min_distance >= 0)
{
//cout << re_data->min_distance << endl;
string id = record.id;
if (re_data->min_distance <= 0.3)
re_data->lessThan300m.insertHead(id);
if (re_data->min_distance <= 0.5)
re_data->lessThan500m.insertHead(id);
if (re_data->min_distance <= 2)
re_data->lessThan2km.insertHead(id);
if (re_data->min_distance > 0.5 && re_data->min_distance <= 2)
re_data->lessThan2km_greatThan500m.insertHead(id);
re_data->min_distance = -1;
}
}
};
stringstream stream(request.code);
string buf, time_src;
void *p = new request_data();
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
try{
//Get data form request code
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->longitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->latitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->number_of_VM = stod(buf);
}
catch(exception& e)
{
return false;
}
if (!getline(stream, buf, '_'))
return false;
time_src = buf;
if (!stream.eof() && time_src.length() != 4)
return false;
try{
parseTime(((request_data *)p)->t1,time_src,recordList[0].timestamp);
}
catch(exception& e)
{
return false;
}
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
((request_data *)p)->pData = database;
database->traverseRNL(re6_counting,p);
void (*print_list)(string &) = [](string &id) {
cout << " " << id;
};
request_data *re_data = (request_data *)p;
cout << request.code[0] << ":";
if (re_data->lessThan2km.getSize() < re_data->number_of_VM)
{
re_data->lessThan2km.traverse(print_list);
cout << " - -1";
}
else if ((double(re_data->lessThan300m.getSize()) / re_data->number_of_VM) >= 0.75)
{
cout << " -1 -";
re_data->lessThan2km.traverse(print_list);
}
else
{
re_data->lessThan500m.traverse(print_list);
cout << " -";
re_data->lessThan2km_greatThan500m.traverse(print_list);
}
delete (request_data *)p;
return true;
}
bool process_request_7(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*parseTime)(time_t &, string &, time_t &) = [](time_t &dest, string &src, time_t &scale) {
//parse time to tm
struct tm *tm = gmtime(&scale);
tm->tm_hour = stoi(src.substr(0, 2));
tm->tm_min = stoi(src.substr(2, 2));
tm->tm_sec = 0;
dest = timegm(tm);
};
void (*re7_counting)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in East
void (*inStation)(VM_Record &, void *,bool&) = [](VM_Record &record, void *p,bool& terminate) {
//If find it,set terminate to true to terminate traverse
request_data *re_data = (request_data *)p;
double distance = distanceEarth(re_data->latitude, re_data->longitude, record.latitude, record.longitude);
if (record.timestamp >= re_data->t1 && record.timestamp <= (re_data->t1 + 30*60))
{
if(re_data->min_distance < 0) re_data->min_distance = distance;
else if (distance < re_data->min_distance)
{
re_data->min_distance = distance;
}
if(re_data->max_distance < 0 && distance >= 1 && distance <= 2) re_data->max_distance = distance;
else if (distance > re_data->max_distance && distance >= 1 && distance <= 2)
{
re_data->max_distance = distance;
}
}
else if(record.timestamp > (re_data->t1 + 30*60))
{
terminate = true;
}
};
request_data *re_data = (request_data *)p;
//Counting valid ID
if (record.isValid)
{
re_data->min_distance = re_data->max_distance = -1;
bool terminate = false;
record.data.traverseLNR(inStation, p, terminate);
if (re_data->min_distance >= 0)
{
re7_database re;
strcpy(re.id,record.id);
re.distance = re_data->max_distance;
//cout << re_data->min_distance << endl;
string id = record.id;
if (re_data->min_distance <= 0.5)
re_data->lessThan500m.insertHead(id);
if (re_data->min_distance < 1)
re_data->lessThan1km_andStuck.insert(id);
if(re_data->min_distance <= 2)
re_data->lessThan2km.insertHead(id);
if (re_data->min_distance >= 1 && re_data->min_distance <= 2 && re_data->max_distance > 0)
{
re_data->lessThan2km_greatThan1km.insert(re);
re_data->cnt++;
}
re_data->min_distance = re_data->max_distance = -1;
}
}
};
stringstream stream(request.code);
string buf, time_src;
void *p = new request_data();
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
try{
//Get data form request code
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->longitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->latitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->number_of_VM = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->radius = stod(buf);
}
catch(exception &e)
{
return false;
}
if (!getline(stream, buf, '_'))
return false;
time_src = buf;
if (!stream.eof() && time_src.length() != 4)
return false;
((request_data *)p)->cnt = 0;
try{
parseTime(((request_data *)p)->t1,time_src,recordList[0].timestamp);
}
catch(exception& e)
{
return false;
}
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
((request_data *)p)->pData = database;
database->traverseRNL(re7_counting,p);
void (*print_list)(string &) = [](string &id) {
cout << " " << id;
};
void (*sort_result)(re7_database&,void*) = [](re7_database &record,void* p) {
request_data *re_data = (request_data *)p;
string id = record.id;
if(re_data->percent_cnt > 0)
{
re_data->lessThan2km_greatThan1km_75.insert(id);
re_data->percent_cnt--;
}
else
{
re_data->lessThan1km_andStuck.insert(id);
}
};
request_data *re_data = (request_data *)p;
cout << request.code[0] << ":";
if ((double(re_data->lessThan500m.getSize()) / re_data->number_of_VM) < 0.7)
{
cout << " -1 -";
if(re_data->lessThan2km.getSize() == 0) cout << " -1";
else re_data->lessThan2km.traverse(print_list);
}
else
{
re_data->percent_cnt = 0.75*re_data->cnt;
re_data->lessThan2km_greatThan1km.traverseRNL(sort_result,p);
if(re_data->lessThan1km_andStuck.isEmpty()) cout << " -1";
else re_data->lessThan1km_andStuck.traverseLNR(print_list);
cout << " -";
if(re_data->lessThan2km_greatThan1km_75.isEmpty()) cout << " -1";
else re_data->lessThan2km_greatThan1km_75.traverseLNR(print_list);
}
delete (request_data *)p;
return true;
}
bool process_request_8(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*parseTime)(time_t &, string &, time_t &) = [](time_t &dest, string &src, time_t &scale) {
//parse time to tm
struct tm *tm = gmtime(&scale);
tm->tm_hour = stoi(src.substr(0, 2));
tm->tm_min = stoi(src.substr(2, 2));
tm->tm_sec = 0;
dest = timegm(tm);
};
void (*re8_counting)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in East
void (*isDelay)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
//If find it,set terminate to true to terminate traverse
request_data *re_data = (request_data *)p;
double distance = distanceEarth(re_data->latitude, re_data->longitude, record.latitude, record.longitude);
if (distance <= re_data->radius)
{
if(record.timestamp >= re_data->t1 && record.timestamp <= (re_data->t1 +59))
{
terminate = true;
}
}
};
//Counting valid ID
bool terminate = !record.isValid;
record.data.traverseNLR(isDelay, p, terminate);
if (terminate && record.isValid == true)
{
cout << " " << record.id;
record.isValid = false;
((request_data *)p)->cnt++;
}
};
stringstream stream(request.code);
string buf, time_src;
void *p = new request_data();
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
try{
//Get data form request code
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->longitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->latitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->radius = stod(buf);
if (!getline(stream, buf, '_'))
return false;
}
catch(exception &e)
{
return false;
}
time_src = buf;
if (!stream.eof() && time_src.length() != 4)
return false;
try{
parseTime(((request_data *)p)->t1,time_src,recordList[0].timestamp);
}
catch(exception& e)
{
return false;
}
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
((request_data *)p)->pData = database;
cout << request.code[0] << ":";
database->traverseLNR(re8_counting,p);
if(((request_data *)p)->cnt == 0) cout << " " << 0;
delete (request_data *)p;
return true;
}
bool process_request_9(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
void (*parseTime)(time_t &, string &, time_t &) = [](time_t &dest, string &src, time_t &scale) {
//parse time to tm
struct tm *tm = gmtime(&scale);
tm->tm_hour = stoi(src.substr(0, 2));
tm->tm_min = stoi(src.substr(2, 2));
tm->tm_sec = 0;
dest = timegm(tm);
};
void (*re9_counting)(VM_database &, void *) = [](VM_database &record, void *p) {
//Fucntion check if record coordinate not in East
void (*isRecover)(VM_Record &, void *, bool &) = [](VM_Record &record, void *p, bool &terminate) {
//If find it,set terminate to true to terminate traverse
request_data *re_data = (request_data *)p;
double distance = distanceEarth(re_data->latitude, re_data->longitude, record.latitude, record.longitude);
if (distance <= re_data->radius)
{
if(record.timestamp >= re_data->t1 && record.timestamp <= (re_data->t1 +59))
{
terminate = true;
}
}
};
//Counting valid ID
bool terminate = record.isValid;
record.data.traverseNLR(isRecover, p, terminate);
if (terminate && record.isValid == false)
{
cout << " " << record.id;
((request_data *)p)->cnt++;
record.isValid = true;
}
};
stringstream stream(request.code);
string buf, time_src;
void *p = new request_data();
if(request.code[1] != '_') return false;
if (!getline(stream, buf, '_'))
return false;
try{
//Get data form request code
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->longitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->latitude = stod(buf);
if (!getline(stream, buf, '_'))
return false;
((request_data *)p)->radius = stod(buf);
}
catch(exception &e)
{
return false;
}
if (!getline(stream, buf, '_'))
return false;
time_src = buf;
if (!stream.eof() && time_src.length() != 4)
return false;
try{
parseTime(((request_data *)p)->t1,time_src,recordList[0].timestamp);
}
catch(exception &e)
{
return false;
}
AVLTree<VM_database> *database = (AVLTree<VM_database> *)pGData;
((request_data *)p)->pData = database;
cout << request.code[0] << ":";
database->traverseLNR(re9_counting,p);
if(((request_data *)p)->cnt == 0) cout << " " << 0;
delete (request_data *)p;
return true;
}
bool processRequest(VM_Request &request, L1List<VM_Record> &recordList, void *pGData)
{
// TODO: Your code goes
//Init database for processRequest
if (((AVLTree<VM_database> *)pGData)->isEmpty())
{
//Function pointer to creat dabase
void (*initDatabase)(VM_Record &, void *) = [](VM_Record &record, void *pGData) {
VM_database key(record.id);
AVLTree<VM_database> *p = (AVLTree<VM_database> *)pGData;
VM_database *x;
if (!p->find(key, x))
{
p->insert(key);
p->find(key, x);
x->data.insert(record);
}
else
x->data.insert(record);
};
//Traverse LiList and creat database
recordList.traverse(initDatabase, pGData);
}
//Process requests
switch (request.code[0])
{
case '1':
return process_request_1(request, recordList, pGData);
break;
case '2':
return process_request_2(request, recordList, pGData);
break;
case '3':
return process_request_3(request, recordList, pGData);
break;
case '4':
return process_request_4(request, recordList, pGData);
break;
case '5':
return process_request_5(request, recordList, pGData);
break;
case '6':
return process_request_6(request, recordList, pGData);
break;
case '7':
return process_request_7(request, recordList, pGData);
break;
case '8':
return process_request_8(request, recordList, pGData);
break;
case '9':
return process_request_9(request, recordList, pGData);
break;
default:
return false; // return false for invlaid events
}
} | 31.537572 | 126 | 0.555291 | [
"vector"
] |
2e2f2f6d44a1d8974f3320989f04c492e998a6d1 | 4,793 | cpp | C++ | python/extensions/pybind_isce3/core/Projections.cpp | isce3-testing/isce3-circleci-poc | ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3 | [
"Apache-2.0"
] | 64 | 2019-08-06T19:22:22.000Z | 2022-03-20T17:11:46.000Z | python/extensions/pybind_isce3/core/Projections.cpp | isce-framework/isce3 | 59cdd2c659a4879367db5537604b0ca93d26b372 | [
"Apache-2.0"
] | 8 | 2020-09-01T22:46:53.000Z | 2021-11-04T00:05:28.000Z | python/extensions/pybind_isce3/core/Projections.cpp | isce-framework/isce3 | 59cdd2c659a4879367db5537604b0ca93d26b372 | [
"Apache-2.0"
] | 29 | 2019-08-05T21:40:55.000Z | 2022-03-23T00:17:03.000Z | #include "Projections.h"
#include <pybind11/eigen.h>
#include <string>
namespace py = pybind11;
using namespace isce3::core;
void addbinding(py::class_<ProjectionBase, PyProjectionBase>& pyProjectionBase)
{
pyProjectionBase.doc() = R"(
Abstract base class for map projections, which handle conversion between
geodetic and projection coordinates
Attributes
----------
code : int
The corresponding EPSG code
ellipsoid : Ellipsoid
The geodetic reference ellipsoid
)";
pyProjectionBase
// Constructors
.def(py::init<int>(), py::arg("code"))
// Methods
.def("forward",
py::overload_cast<const Vec3&>(&ProjectionBase::forward,
py::const_),
py::arg("llh"),
R"(
Forward projection transform from LLH to coordinates in the
specified projection system.
Parameters
----------
llh : Vec3
Longitude (in radians), latitude (in radians), and height above
ellipsoid (in meters)
Returns
-------
xyz : Vec3
Coordinates in the specified projection system
)")
.def("inverse",
py::overload_cast<const Vec3&>(&ProjectionBase::inverse,
py::const_),
py::arg("xyz"),
R"(
Inverse projection transform from coordinates in the specified
projection system to LLH.
Parameters
----------
xyz : Vec3
Coordinates in the specified projection system
Returns
-------
llh : Vec3
Longitude (in radians), latitude (in radians), and height above
ellipsoid (in meters)
)")
// Properties
.def_property_readonly("code", &ProjectionBase::code)
.def_property_readonly("ellipsoid", &ProjectionBase::ellipsoid)
;
}
void addbinding(py::class_<LonLat>& pyLonLat)
{
pyLonLat
.def(py::init<>())
.def("__repr__", [](const LonLat& self) {
return "LonLat(epsg=" + std::to_string(self.code()) + ")";
})
;
}
void addbinding(py::class_<Geocent>& pyGeocent)
{
pyGeocent.doc() = R"(
Earth-centered, earth-fixed (ECEF) coordinate representation (EPSG: 4978)
The projection coordinates are ECEF X/Y/Z coordinates, in meters. The WGS 84
reference ellipsoid is used.
)";
pyGeocent
.def(py::init<>())
.def("__repr__", [](const Geocent& self) {
return "Geocent(epsg=" + std::to_string(self.code()) + ")";
})
;
}
void addbinding(py::class_<UTM>& pyUTM)
{
pyUTM.doc() = R"(
Universal Transverse Mercator (UTM) projection
The projection coordinates are easting/northing/height above ellipsoid, in
meters. The WGS 84 reference ellipsoid is used.
EPSG codes 32601-32660 correspond to UTM North zones 1-60. EPSG codes
32701-32760 correspond to UTM South zones 1-60.
)";
pyUTM
.def(py::init<int>(), py::arg("code"))
.def("__repr__", [](const UTM& self) {
return "UTM(epsg=" + std::to_string(self.code()) + ")";
})
;
}
void addbinding(py::class_<PolarStereo>& pyPolarStereo)
{
pyPolarStereo.doc() = R"(
Universal Polar Stereographic (UPS) projection
The projection coordinates are easting/northing/height above ellipsoid, in
meters. The WGS 84 reference ellipsoid is used.
EPSG code 3413 corresponds to the UPS North zone. EPSG code 3031 corresponds
to UPS South zone.
)";
pyPolarStereo
.def(py::init<int>(), py::arg("code"))
.def("__repr__", [](const PolarStereo& self) {
return "PolarStereo(epsg=" + std::to_string(self.code()) + ")";
})
;
}
void addbinding(py::class_<CEA>& pyCEA)
{
pyCEA.doc() = R"(
Cylindrical Equal-Area projection used by the EASE-Grid 2.0 (EPSG: 6933)
The projection coordinates are easting/northing/height above ellipsoid, in
meters. The WGS 84 reference ellipsoid is used.
)";
pyCEA
.def(py::init<>())
.def("__repr__", [](const CEA& self) {
return "CEA(epsg=" + std::to_string(self.code()) + ")";
})
;
}
void addbinding_makeprojection(pybind11::module& m)
{
m.def("make_projection", &makeProjection, py::arg("epsg"),
"Return the projection corresponding to the specified EPSG code.");
}
| 30.335443 | 80 | 0.551638 | [
"transform"
] |
2e34500f74fb36e5384b7da137af3be77c2d1231 | 1,105 | cc | C++ | src/input/simple.cc | viyadb/viyadb | 56d9b9836a57a36483bee98e6bc79f79e2f5c772 | [
"Apache-2.0"
] | 109 | 2017-10-03T06:52:30.000Z | 2022-03-22T18:38:48.000Z | src/input/simple.cc | b-xiang/viyadb | b72f9cabacb4b24bd2192ed824d930ccb73d3609 | [
"Apache-2.0"
] | 26 | 2017-10-15T19:45:18.000Z | 2019-10-18T09:55:54.000Z | src/input/simple.cc | viyadb/viyadb | 56d9b9836a57a36483bee98e6bc79f79e2f5c772 | [
"Apache-2.0"
] | 7 | 2017-10-03T09:37:36.000Z | 2020-12-15T01:04:45.000Z | /*
* Copyright (c) 2017-present ViyaDB Group
*
* 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 "input/simple.h"
#include "util/config.h"
#include <vector>
namespace viya {
namespace input {
SimpleLoader::SimpleLoader(db::Table &table) : Loader(util::Config{}, table) {}
SimpleLoader::SimpleLoader(const util::Config &config, db::Table &table)
: Loader(config, table) {}
void SimpleLoader::Load(std::initializer_list<std::vector<std::string>> rows) {
BeforeLoad();
for (auto row : rows) {
Loader::Load(row);
}
AfterLoad();
}
} // namespace input
} // namespace viya
| 29.078947 | 79 | 0.714932 | [
"vector"
] |
aa3680c1b4688dd4b52705771ac392c1ec2520df | 1,269 | cc | C++ | DataStructure/HashTable/test.cc | five-5/code | 9c20757b1d4a087760c51da7d3dcdcc2b17aee07 | [
"Apache-2.0"
] | null | null | null | DataStructure/HashTable/test.cc | five-5/code | 9c20757b1d4a087760c51da7d3dcdcc2b17aee07 | [
"Apache-2.0"
] | null | null | null | DataStructure/HashTable/test.cc | five-5/code | 9c20757b1d4a087760c51da7d3dcdcc2b17aee07 | [
"Apache-2.0"
] | null | null | null | /*
* @Author: five-5
* @Date: 2019-07-12 16:25:08
* @Description:
* @LastEditTime: 2019-07-12 17:16:24
*/
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include "HashTable.hpp"
// 读文件内容到vector中
void readFile(std::string filename, std::vector<std::string> &words) {
std::ifstream input(filename);
if (!input.is_open()) {
printf("fail to open %s\n", filename.c_str());
}
std::string line, word;
while (std::getline(input, line)) {
std::istringstream istream(line);
while (istream >> word)
{
words.push_back(word);
}
}
}
int main()
{
std::vector<std::string> words;
readFile("Pride And prejudice.txt", words);
clock_t start, end;
start = clock();
HashTable<std::string, int> ht = HashTable<std::string, int>();
for (const auto & word: words) {
if (ht.contains(word)) {
ht.set(word, ht.get(word) + 1);
} else {
ht.add(word, 1);
}
}
for (const auto & word: words) {
ht.contains(word);
}
end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("HashTable: %f s\n", duration);
return 0;
} | 21.508475 | 70 | 0.568952 | [
"vector"
] |
aa38a8f1b92206b3cac4af8c1d027291422cdbf1 | 29,193 | cpp | C++ | GenerateROS/drinventorfindtriples.cpp | DrInventor/NUIM | 7dc0b780e3847b0d5dfb12d324e8e5bd535161b9 | [
"MIT"
] | 1 | 2015-07-01T20:37:29.000Z | 2015-07-01T20:37:29.000Z | GenerateROS/drinventorfindtriples.cpp | DrInventor/Analogy-and-Assessment | 7dc0b780e3847b0d5dfb12d324e8e5bd535161b9 | [
"MIT"
] | 1 | 2015-01-17T12:00:18.000Z | 2015-01-17T12:00:18.000Z | GenerateROS/drinventorfindtriples.cpp | DrInventor/Analogy-and-Assessment | 7dc0b780e3847b0d5dfb12d324e8e5bd535161b9 | [
"MIT"
] | null | null | null | #include "drinventorfindtriples.h"
DrInventorFindTriples::~DrInventorFindTriples(){
}
void DrInventorFindTriples::MakeTripleSent(void){
struct triplesent temp;
int count = 0;
if (!foundtriples)
FindTriples();
for (std::vector<struct sentence>::iterator sit = sentences.begin(); sit != sentences.end(); ++sit){
for (std::vector<struct triple>::iterator it = (*sit).triples.begin(); it != (*sit).triples.end(); ++it){
temp.vb = (*sit).words[(*it).ver].st;
if ((*it).sbj == -1)
temp.sbj = "%%-1%%";
else
temp.sbj = (*sit).words[(*it).sbj].st;
if ((*it).obj == -1)
temp.obj = "%%-1%%";
else
temp.obj = (*sit).words[(*it).obj].st;
temp.sentid = (long)((*sit).id);
triplesent.emplace_back(temp);
}
}
//Make APPO substitutions
for (std::vector<struct stringpair>::iterator it = appos.begin(); it != appos.end(); ++it){
int count[2] = { 0, 0 };
//First find most common
for (std::vector<struct triplesent>::iterator tripit = triplesent.begin(); tripit != triplesent.end(); ++tripit){
if ((*tripit).sbj == (*it).st1)
++count[0];
else if ((*tripit).sbj == (*it).st2)
++count[1];
if ((*tripit).obj == (*it).st1)
++count[0];
else if ((*tripit).obj == (*it).st2)
++count[1];
}
//Then replace
if (count[0] > count[1]){
for (std::vector<struct triplesent>::iterator tripit = triplesent.begin(); tripit != triplesent.end(); ++tripit){
if ((*tripit).sbj == (*it).st2){
(*tripit).sbj = (*it).st1;
}
if ((*tripit).obj == (*it).st2){
(*tripit).obj = (*it).st1;
}
}
}
else{
for (std::vector<struct triplesent>::iterator tripit = triplesent.begin(); tripit != triplesent.end(); ++tripit){
if ((*tripit).sbj == (*it).st1)
(*tripit).sbj = (*it).st2;
if ((*tripit).obj == (*it).st1)
(*tripit).obj = (*it).st2;
}
}
}
}
DrInventorFindTriples::DrInventorFindTriples(const char *file, const char *tknfile){
/*
Constructor, stores the main file and tknfile name and checks if they both exist (and are readable)
If they exist, the main file is read in line by line and the first graphs (plain white) are made
This is done line by line (line (titles) 0 ignored)
*/
filename = file;
tokenfile = tknfile;
std::ifstream toread;
toread.open(file);
graphsmade = false;
blockprint = false;
tagwordsold = true;
if (!toread.is_open()){
fisopen = false;
}
else{
std::ifstream toread2;
toread2.open(tknfile);
if (!toread2.is_open()){
toread.close();
fisopen = false;
}
else{
toread2.close();
fisopen = true;
std::string temp;
getline(toread, temp);
while (getline(toread, temp))
processline(temp);
toread.close();
}
}
}
DrInventorFindTriples::DrInventorFindTriples(const char *file){
/*
Constructor, stores the main file and checks if they it exists (and are readable)
If they exist, the main file is read in line by line and the first graphs (plain white) are made
This is done line by line (line (titles) 0 ignored)
*/
filename = file;
tokenfile = "";
std::ifstream toread;
toread.open(file);
graphsmade = false;
blockprint = false;
tagwordsold = false;
if (!toread.is_open()){
fisopen = false;
}
else{
fisopen = true;
std::string temp;
getline(toread, temp);
while (getline(toread, temp)){
if (!processlineofcombinedtable(temp))
fisopen = false;
}
toread.close();
}
}
bool DrInventorFindTriples::PrintInbetweenGraphs(void){
/*
This function generally should not be used, it is for debugging (and documenting) purposes
It prints the "inbetween" graphs, i.e. the graphs with firstly the ones formed by processing the mainfile
Then it prints the graphs made after discarding anything that's not a noun or verb
After combining verbs the graphs from the initial file will be broken (blockprint check)
If the Graphs with only nouns and verbs with the verbs combined is wanted this function can be used, however the initial (plain white) graphs will not be generated since broken
*/
if (graphsmade){
printf_s("inbetween, %d\n", sentences.size());
for (unsigned int i = 0; i < sentences.size(); ++i){
char buf[1024];
FILE *out;
if (!blockprint){
sprintf_s(buf, "%s-%d.gv", filename.c_str(), sentences[i].id);
out = fopen(buf, "w");
if (out){
fprintf_s(out, "digraph graphname {\n");
for (unsigned int j = 0; j < sentences[i].words.size(); ++j)
fprintf_s(out, "\t\tw%d [label=\"%s\"]\n", j, sentences[i].words[j].st.c_str());
for (unsigned int j = 0; j < sentences[i].links.size(); ++j)
fprintf_s(out, "\t\tw%d -> w%d [label=\"%s\"]\n", sentences[i].links[j].to, sentences[i].links[j].from, sentences[i].links[j].relat.c_str());
fprintf_s(out, "}");
fclose(out);
char buf3[1024];
sprintf_s(buf3, "c:\\users\\user\\documents\\gv\\dot %s -o %s.png -T png", buf, buf);
system(buf3);
}
}
sprintf_s(buf, "%s-n%d.gv", filename.c_str(), sentences[i].id);
printf_s("a:%s\n", buf);
out = fopen(buf, "w");
if (out){
fprintf_s(out, "digraph graphname {\n");
for (unsigned int j = 0; j < sentences[i].words.size(); ++j){
if (sentences[i].words[j].type != 0){
fprintf_s(out, "\t\tw%d [label=\"%s\" ", j, sentences[i].words[j].st.c_str());
if (sentences[i].words[j].type == 1) fprintf_s(out, "style=filled color=green]\n");
else if (sentences[i].words[j].type == 2) fprintf_s(out, "shape=box style=filled color=yellow]\n");
}
}
for (unsigned int j = 0; j < sentences[i].newlinks.size(); ++j)
fprintf_s(out, "\t\tw%d -> w%d [label=\"%s\"]\n", sentences[i].newlinks[j].from, sentences[i].newlinks[j].to, sentences[i].newlinks[j].relat.c_str());
fprintf_s(out, "}");
fclose(out);
char buf2[1024];
sprintf_s(buf2, "c:\\users\\user\\documents\\gv\\dot %s -o %s.png -T png", buf, buf);
system(buf2);
}
fclose(out);
}
return true;
}
else{
printf_s("Graphs not made");
return false;
}
}
void DrInventorFindTriples::FindTriples(bool tc){
/*
Extract the triples: , ensure links are only processed once
1) Find a link with a verb in it. If the link is of type SBJ make a triple from this by
(i) searching for an adjacent corresponding OBJ
(ii) using any adjacent noun
(iii) seeing if any adjacent verbs are only in another link with another noun and then combining verbs
2) If the link with a verb in it and the link is of type OBJ make a triple from this by
(i) searching for an adjacent corresponding SBJ
(ii) using any adjacent noun
3) After all SBJ and OBJ links have been dealt with, find any verbs with two unprocessed links to nouns and make triples from these
*/
struct triple temptriple;
for (std::vector<struct sentence>::iterator sit = sentences.begin(); sit != sentences.end(); ++sit){
std::vector<std::vector<struct link>::iterator> processed;
for (std::vector<struct link>::iterator it = (*sit).newlinks.begin(); it != (*sit).newlinks.end(); ++it){
if (std::find(processed.begin(), processed.end(), it) == processed.end()){
if ((*sit).words[(*it).from].type == 1 && (*it).relat == "SBJ"){
processed.emplace_back(it);
temptriple.sbj = (*it).to;
temptriple.ver = (*it).from;
temptriple.obj = -1;
//Got a subject so find object;//Should a nit not in processed check be done??
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end() && (*it).from == (*nit).from && (*nit).relat == "OBJ"){
processed.emplace_back(nit);
temptriple.obj = (*nit).to;
break;
}
}
//If no luck, try finding an adjacent noun anyway
if (temptriple.obj == -1){
std::vector<struct link>::iterator foundoption = (*sit).newlinks.end();
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end() && (*nit).relat != "SBJ" && (*it).from == (*nit).from && (*sit).words[(*nit).to].type == 2){
//If this link has not yet been used, use it now
if (std::find(processed.begin(), processed.end(), nit) == processed.end()){
processed.emplace_back(nit);
temptriple.obj = (*nit).to;
break;
}
else if (foundoption == (*sit).newlinks.end())
foundoption = nit;//If the link has been used before, keep it as an option, just in case
}
}
//If we found a previously used option for a link but still no complete triple, use it
if (temptriple.obj == -1 && foundoption != (*sit).newlinks.end())
temptriple.obj = (*foundoption).to;
}
//Still if no luck, maybe join two verbs to find an object?
if (temptriple.obj == -1){
bool keepgoing = true;
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); keepgoing && nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end() && (*it).from == (*nit).from && (*sit).words[(*nit).to].type == 1){
for (std::vector<struct link>::iterator anotit = (*sit).newlinks.begin(); keepgoing &&anotit != (*sit).newlinks.end(); ++anotit){
if (anotit != it && anotit != nit && std::find(processed.begin(), processed.end(), anotit) == processed.end()){
if ((*anotit).from == (*nit).to && (*sit).words[(*anotit).to].type == 2){
int count = 0;
for (unsigned int k = 0; k < (*sit).newlinks.size(); ++k){
if ((*sit).newlinks[k].to == (*nit).to || (*sit).newlinks[k].from == (*nit).to)
++count;
}
if (count > 2)
break;
else{
(*sit).words[(*it).from].st += "_";
(*sit).words[(*it).from].st += (*sit).words[(*nit).to].st;
for (std::vector<struct link>::iterator joinit = (*sit).newlinks.begin(); joinit != (*sit).newlinks.end(); ++joinit){
if (joinit != nit){
if ((*joinit).from == (*nit).to){
(*joinit).from = (*nit).from;
processed.emplace_back(joinit);
temptriple.obj = (*joinit).to;
}
}
}
keepgoing = false;
}
}
}
}
}
}
}
findappo(sit, temptriple.sbj);
findappo(sit, temptriple.obj);
(*sit).triples.emplace_back(temptriple);
}
else if ((*sit).words[(*it).from].type == 1 && (*it).relat == "OBJ"){
processed.emplace_back(it);
//Got an object
temptriple.obj = (*it).to;
temptriple.ver = (*it).from;
temptriple.sbj = -1;
//Got an object so find subject;
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end() && (*it).from == (*nit).from && (*nit).relat == "SBJ"){
processed.emplace_back(nit);
temptriple.sbj = (*nit).to;
break;
}
}
//If no luck, try finding an adjacent noun anyway
if (temptriple.sbj == -1){
std::vector<struct link>::iterator foundoption = (*sit).newlinks.end();
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && (*nit).relat != "OBJ" && (*it).from == (*nit).from && (*sit).words[(*nit).to].type == 2){
if (std::find(processed.begin(), processed.end(), nit) == processed.end()){
processed.emplace_back(nit);
temptriple.sbj = (*nit).to;
break;
}
else if (foundoption == (*sit).newlinks.end())
foundoption = nit;
}
}
if (temptriple.sbj == -1 && foundoption != (*sit).newlinks.end())
temptriple.sbj = (*foundoption).to;
}
//If still no luck, check if there is an incoming NOUN node to the verb
if (temptriple.sbj == -1){
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end() && (*it).from == (*nit).to && (*sit).words[(*nit).from].type == 2){
processed.emplace_back(nit);
temptriple.sbj = (*nit).from;
break;
}
}
}
//If still no luck, maybe try backtracking up one verb chain for a SBJ?
if (temptriple.sbj == -1){
bool keepgoing = true;
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); keepgoing && nit != (*sit).newlinks.end(); ++nit){
if (nit != it && (*it).from == (*nit).to && (*sit).words[(*nit).from].type == 1){
for (std::vector<struct link>::iterator anotit = (*sit).newlinks.begin(); keepgoing && anotit != (*sit).newlinks.end(); ++anotit){
if (anotit != it && anotit != nit){
if ((*anotit).from == (*nit).from && (*sit).words[(*anotit).to].type == 2 && (*anotit).relat == "SBJ"){
struct word tempword;
tempword.id = 0;
tempword.type = 1;
tempword.st = (*sit).words[(*nit).from].st + "_" + (*sit).words[(*it).from].st;
(*sit).words.emplace_back(tempword);
temptriple.ver = (int)(*sit).words.size() - 1;
temptriple.sbj = (*anotit).to;
keepgoing = false;
}
}
}
}
}
}
findappo(sit, temptriple.sbj);
findappo(sit, temptriple.obj);
(*sit).triples.emplace_back(temptriple);
}
}
}
//Having found and dealt with all Sbj and Obj links. If any verbs have two leftover adjacent nouns, add them as a triple
for (std::vector<struct link>::iterator it = (*sit).newlinks.begin(); it != (*sit).newlinks.end(); ++it){
if (std::find(processed.begin(), processed.end(), it) == processed.end()){
if ((*sit).words[(*it).from].type == 1 && (*sit).words[(*it).to].type == 2){
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end()){
if ((*it).from == (*nit).from && (*sit).words[(*nit).to].type == 2){
processed.emplace_back(nit);
temptriple.sbj = (*it).to;
temptriple.ver = (*it).from;
temptriple.obj = (*nit).to;
(*sit).triples.emplace_back(temptriple);
}
else if ((*it).from == (*nit).to && (*sit).words[(*nit).from].type == 2){
processed.emplace_back(nit);
temptriple.sbj = (*it).to;
temptriple.ver = (*it).from;
temptriple.obj = (*nit).from;
(*sit).triples.emplace_back(temptriple);
}
}
}
}
else if ((*sit).words[(*it).to].type == 1 && (*sit).words[(*it).from].type == 2){
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it && std::find(processed.begin(), processed.end(), nit) == processed.end()){
if ((*it).to == (*nit).from && (*sit).words[(*nit).to].type == 2){
processed.emplace_back(nit);
temptriple.sbj = (*it).from;
temptriple.ver = (*it).to;
temptriple.obj = (*nit).to;
(*sit).triples.emplace_back(temptriple);
}
else if ((*it).to == (*nit).to && (*sit).words[(*nit).from].type == 2){
processed.emplace_back(nit);
temptriple.sbj = (*it).from;
temptriple.ver = (*it).to;
temptriple.obj = (*nit).to;
(*sit).triples.emplace_back(temptriple);
}
}
}
}
}
}
}
foundtriples = true;
}
bool DrInventorFindTriples::findappo(std::vector<struct sentence>::iterator sit, unsigned int id){//Find type APPO joining nouns, i.e. could be replacement
if (id == -1)
return false;
for (std::vector<struct link>::iterator it = (*sit).newlinks.begin(); it != (*sit).newlinks.end(); ++it){
if ((*it).from == id && (*it).relat == "APPO" && (*sit).words[(*it).to].type==2){
struct stringpair temp;
temp.st1 = (*sit).words[(*it).from].st;
temp.st2 = (*sit).words[(*it).to].st;
appos.emplace_back(temp);
return true;
}
}
return false;
}
void DrInventorFindTriples::WriteTriplesToCSVFile(const char *file){
//Not used anymore, outputs the triples to a CSV file
if (!foundtriples)
FindTriples();
FILE *out;
out = fopen(file, "w");
if (out){
for (std::vector<struct sentence>::iterator sit = sentences.begin(); sit != sentences.end(); ++sit){
for (std::vector<struct triple>::iterator it = (*sit).triples.begin(); it != (*sit).triples.end(); ++it){
if ((*it).sbj == -1) fprintf_s(out, "\"%d\",\"%s\",\"%%%%-1%%%%\",\"%s\"\n", sit - sentences.begin(),(*sit).words[(*it).ver].st.c_str(), (*sit).words[(*it).obj].st.c_str());
else if ((*it).obj == -1) fprintf_s(out, "\"%d\",\"%s\",\"%s\",\"%%%%-1%%%%\"\n", sit - sentences.begin(),(*sit).words[(*it).ver].st.c_str(), (*sit).words[(*it).sbj].st.c_str());
else fprintf_s(out, "\"%d\",\"%s\",\"%s\",\"%s\"\n", sit-sentences.begin(),(*sit).words[(*it).ver].st.c_str(), (*sit).words[(*it).sbj].st.c_str(), (*sit).words[(*it).obj].st.c_str());
}
}
fclose(out);
}
}
void DrInventorFindTriples::MakeNewLinks(bool tc){
/*
Firstly all nodes that are not nouns or verbs are discarded
Then some verb chains are combined
*/
if (tagwords()){
for (unsigned int i = 0; i < sentences.size(); ++i)
discardstuff(i);
graphsmade = true;
if (tc)
PrintInbetweenGraphs();
combineVC();
}
else
printf_s("Tag Words failed");
}
void DrInventorFindTriples::combineVC(void){
//Combine some verbs together, i.e. VC (Verb Chain), IM (infinitive), OPRD and NMOD
for (std::vector<struct sentence>::iterator sit = sentences.begin(); sit != sentences.end(); ++sit){
std::vector<std::vector<struct link>::iterator> todelete;
for (std::vector<struct link>::iterator it = (*sit).newlinks.begin(); it != (*sit).newlinks.end(); ++it){
if ((*it).relat == "VC" || (*it).relat == "IM" || ((*it).relat == "OPRD") || ((*it).relat == "NMOD")){
if ((*sit).words[(*it).from].type == 1 && (*sit).words[(*it).to].type == 1){
(*sit).words[(*it).from].st += "_";
(*sit).words[(*it).from].st += (*sit).words[(*it).to].st;
for (std::vector<struct link>::iterator nit = (*sit).newlinks.begin(); nit != (*sit).newlinks.end(); ++nit){
if (nit != it){
if ((*nit).from == (*it).to)
(*nit).from = (*it).from;
}
}
(*sit).words[(*it).to].type = 0;
todelete.emplace_back(it);
}
}
}
if (todelete.size() > 0)
blockprint = true;
for (int i = (int)todelete.size() - 1; i >= 0; --i){
(*sit).newlinks.erase(todelete[i]);
}
}
}
void DrInventorFindTriples::findnewlink(unsigned int start, unsigned int from, std::vector<struct link> *newlinks, unsigned int sent){
//function to determine "newlinks", these are the links made after non-nouns and non-verbs are discarded - ensures structure maintained
std::vector<int> contained = containedin(from, sent);
struct link templink;
for (unsigned int i = 0; i < contained.size(); ++i){
if (sentences[sent].words[sentences[sent].links[contained[i]].from].type != 0){
templink.from = start;
templink.to = sentences[sent].links[contained[i]].from;
newlinks->emplace_back(templink);
}
else
findnewlink(start, sentences[sent].links[contained[i]].from, newlinks, sent);
}
}
void DrInventorFindTriples::discardstuff(int sent){
//Get rid of nodes that are not nouns nor verbs, find new link is to make sure chains aren't broken
struct link templink;
for (unsigned int i = 0; i < sentences[sent].words.size(); ++i){
if (sentences[sent].words[i].type != 0){
std::vector<int> contained = containedin(i, sent);
for (unsigned int j = 0; j < contained.size(); ++j){
if (sentences[sent].words[sentences[sent].links[contained[j]].from].type != 0){
templink.from = i;
templink.to = sentences[sent].links[contained[j]].from;
templink.relat = sentences[sent].links[contained[j]].relat;
sentences[sent].newlinks.emplace_back(templink);
}
else
findnewlink(i, sentences[sent].links[contained[j]].from, &sentences[sent].newlinks, sent);
}
}
}
}
bool DrInventorFindTriples::tagwordsnew(void){
std::string type;
for (std::vector<struct sentence>::iterator sentit = sentences.begin(); sentit != sentences.end(); ++sentit){
for (std::vector<struct word>::iterator wordit = (*sentit).words.begin(); wordit != (*sentit).words.end(); ++wordit){
type = (*wordit).pos;
if (type.size() >= 2 && type.at(0) == 'N' && type.at(1) == 'N'){
(*wordit).type = 2;
}
else if (type.size() >= 2 && type.at(0) == 'V' && type.at(1) == 'B')
(*wordit).type = 1;
else if (type.size() >= 3 && type.at(0) == 'P' && type.at(1) == 'R' && type.at(2) == 'P')
(*wordit).type = 2;
//New stuff
else if (type.size() >= 2 && type.at(0) == 'E' && type.at(1) == 'X')
(*wordit).type = 2;
else if (type.size() >= 2 && type.at(0) == 'T' && type.at(1) == 'O'){
//We sometimes want to keep the word "to", if for example it is part of an infinitive verb - it will be joined later in CombineVC
(*wordit).type = 0;
for (std::vector<struct link>::iterator linkit = (*sentit).links.begin(); linkit != (*sentit).links.end(); ++linkit){
if (wordit - (*sentit).words.begin() == (*linkit).to){
if ((*linkit).relat == "IM"){
(*wordit).type = 1;
break;
}
}
}
}
else
(*wordit).type = 0;
}
}
return true;
}
bool DrInventorFindTriples::tagwords(void){
//Tag the nouns and verbs from the tknfile. If neither noun nor verb, that word will be discarded later
if (!tagwordsold)
return tagwordsnew();
std::ifstream toread;
toread.open(tokenfile);
if (!toread.is_open()){
printf_s("Token File failed to open\n%s\n", tokenfile.c_str());
return false;
}
std::string leftover;
getline(toread, leftover);
while (getline(toread, leftover)){
int token;
std::string type;
for (unsigned int i = 0; i < 4; ++i){
std::string temp = leftover.substr(0, leftover.find('\t'));
if (i != 3) leftover = leftover.substr(leftover.find('\t') + 1);
//We only care about the first and last columns
switch (i){
case 0:
sscanf_s(temp.c_str(), "\"%d\"", &token);
break;
case 1:
break;
case 2:
break;
case 3:
type = temp.substr(1, temp.length() - 2);
break;
}
}
std::vector<struct word>::iterator wordit;
bool keepgoing = true;
for (unsigned int i = 0; keepgoing && i < sentences.size(); ++i){
if ((wordit = std::find_if(sentences[i].words.begin(), sentences[i].words.end(), find_Word(token))) != sentences[i].words.end()){
keepgoing = false;
if (type.size() >= 2 && type.at(0) == 'N' && type.at(1) == 'N'){
(*wordit).type = 2;
}
else if (type.size() >= 2 && type.at(0) == 'V' && type.at(1) == 'B')
(*wordit).type = 1;
else if (type.size() >= 3 && type.at(0) == 'P' && type.at(1) == 'R' && type.at(2) == 'P')
(*wordit).type = 2;
//New stuff
else if (type.size() >= 2 && type.at(0) == 'E' && type.at(1) == 'X')
(*wordit).type = 2;
else if (type.size() >= 2 && type.at(0) == 'T' && type.at(1) == 'O'){
//We sometimes want to keep the word "to", if for example it is part of an infinitive verb - it will be joined later in CombineVC
(*wordit).type = 0;
for (unsigned int j = 0; j < sentences[i].links.size(); ++j){
if (wordit - sentences[i].words.begin() == sentences[i].links[j].to){
if (sentences[i].links[j].relat == "IM"){
(*wordit).type = 1;
break;
}
}
}
}
else
(*wordit).type = 0;
}
}
}
toread.close();
return true;
}
std::vector<int> DrInventorFindTriples::containedin(int bit, int sent){
//Finds all the links a given node is in, this only goes in one direction since we are doing a tree search
std::vector<int> toreturn;
for (unsigned int i = 0; i < sentences[sent].links.size(); ++i){
if (!sentences[sent].links[i].checked && sentences[sent].links[i].to == bit){
toreturn.emplace_back(i);
sentences[sent].links[i].checked = true;
}
}
return toreturn;
}
int DrInventorFindTriples::processlineofcombinedtable(std::string which){
/*
Extract the words from the a line in the file
Identifies the sentence id, the id of the word the link is from and the id of the word to. It also gets the actual words
The sentence id is checked for uniqueness and if new a new sentence is created in the struct array
Each word ID is then checked in sentences.words and again if new inserted
The link from : "wordfrom to wordto" is then saved in terms of array positions
This reads from combined tables that have the POS tags included
*/
int sID, FromID, ToID;
std::string FromWord, ToWord, Relation, FromPOS, ToPOS, temp;
std::string leftover = which;
std::vector<std::string> splits = splitbydelimiter(which, "\t", true);
if (splits.size() != 10)
return 0;
sID = atoi(splits[0].c_str());
if (splits[1].find('_') != std::string::npos)
FromID = atoi(splits[1].substr(splits[1].find('_') + 1).c_str());
else
FromID = atoi(splits[1].c_str());
FromWord = splits[3];
FromPOS = splits[4];
if (splits[5].find('_') != std::string::npos)
ToID = atoi(splits[5].substr(splits[5].find('_') + 1).c_str());
else
ToID = atoi(splits[5].c_str());
ToWord = splits[7];
ToPOS = splits[8];
Relation = splits[9];
std::vector<struct sentence>::iterator sentit;
sentit = std::find_if(sentences.begin(), sentences.end(), find_sID(sID));
if (sentit == sentences.end()){
struct sentence tempsent;
tempsent.id = sID;
sentences.emplace_back(tempsent);
sentit = std::find_if(sentences.begin(), sentences.end(), find_sID(sID));
}
int whichword[2];
whichword[0] = find_word(FromID, (*sentit).words);
if (whichword[0] == -1){
struct word tempword;
tempword.id = FromID;
tempword.st = FromWord;
tempword.pos = FromPOS;
whichword[0] = (int)((*sentit).words.size());
(*sentit).words.emplace_back(tempword);
}
whichword[1] = find_word(ToID, (*sentit).words);
if (whichword[1] == -1){
struct word tempword;
tempword.id = ToID;
tempword.st = ToWord;
tempword.st = ToPOS;
whichword[1] = (int)((*sentit).words.size());
(*sentit).words.emplace_back(tempword);
}
struct link templink;
templink.from = whichword[0];
templink.to = whichword[1];
templink.relat = Relation;
templink.checked = false;
(*sentit).links.emplace_back(templink);
return 1;
}
int DrInventorFindTriples::processline(std::string which){
/*
Extract the words from the a line in the file
Identifies the sentence id, the id of the word the link is from and the id of the word to. It also gets the actual words
The sentence id is checked for uniqueness and if new a new sentence is created in the struct array
Each word ID is then checked in sentences.words and again if new inserted
The link from : "wordfrom to wordto" is then saved in terms of array positions
*/
int sID, FromID, ToID;
std::string FromWord, ToWord, Relation, temp;
std::string leftover = which;
for (unsigned int i = 0; i < 8; ++i){
temp = leftover.substr(0, leftover.find('\t'));
if (i != 7) leftover = leftover.substr(leftover.find('\t') + 1);
switch (i){
case 0:
sscanf_s(temp.c_str(), "\"%d\"", &sID);
break;
case 1:
sscanf_s(temp.c_str(), "\"%d\"", &FromID);
break;
case 2:
//FromWord = temp.substr(1, temp.length() - 2);
break;
case 3:
//Really this is FromLemma but I don't want to change variables elsewhere!
FromWord = temp.substr(1, temp.length() - 2);
break;
case 4:
sscanf_s(temp.c_str(), "\"%d\"", &ToID);
break;
case 5:
//ToWord = temp.substr(1, temp.length() - 2);
break;
case 6:
//Again, really this is ToLemma
ToWord = temp.substr(1, temp.length() - 2);
break;
case 7:
Relation = temp.substr(1, temp.length() - 2);
break;
}
}
std::vector<struct sentence>::iterator sentit;
sentit = std::find_if(sentences.begin(), sentences.end(), find_sID(sID));
if (sentit == sentences.end()){
struct sentence tempsent;
tempsent.id = sID;
sentences.emplace_back(tempsent);
sentit = std::find_if(sentences.begin(), sentences.end(), find_sID(sID));
}
int whichword[2];
whichword[0] = find_word(FromID, (*sentit).words);
if (whichword[0] == -1){
struct word tempword;
tempword.id = FromID;
tempword.st = FromWord;
whichword[0] = (int)((*sentit).words.size());
(*sentit).words.emplace_back(tempword);
}
whichword[1] = find_word(ToID, (*sentit).words);
if (whichword[1] == -1){
struct word tempword;
tempword.id = ToID;
tempword.st = ToWord;
whichword[1] = (int)((*sentit).words.size());
(*sentit).words.emplace_back(tempword);
}
struct link templink;
templink.from = whichword[0];
templink.to = whichword[1];
templink.relat = Relation;
templink.checked = false;
(*sentit).links.emplace_back(templink);
return 1;
}
bool DrInventorFindTriples::isopen(void){
return fisopen;
} | 38.061278 | 187 | 0.600418 | [
"object",
"shape",
"vector"
] |
aa38cdffb506d79b193e21f56e48de604678fa28 | 15,535 | cpp | C++ | src/library/discr_tree.cpp | solson/lean | b13ac127fd83f3724d2f096b1fb85dc6b15e3746 | [
"Apache-2.0"
] | 2,232 | 2015-01-01T18:20:29.000Z | 2022-03-30T02:35:50.000Z | src/library/discr_tree.cpp | SNU-2D/lean | 72a965986fa5aeae54062e98efb3140b2c4e79fd | [
"Apache-2.0"
] | 1,187 | 2015-01-06T05:18:44.000Z | 2019-10-31T18:45:42.000Z | src/library/discr_tree.cpp | SNU-2D/lean | 72a965986fa5aeae54062e98efb3140b2c4e79fd | [
"Apache-2.0"
] | 306 | 2015-01-16T22:30:27.000Z | 2022-03-28T02:55:51.000Z | /*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <algorithm>
#include <vector>
#include "util/rb_map.h"
#include "util/memory_pool.h"
#include "library/trace.h"
#include "library/annotation.h"
#include "library/fun_info.h"
#include "library/discr_tree.h"
namespace lean {
/* Auxiliary expr used to implement insert/erase operations.
When adding the children of an application into the todo stack,
we use g_delimiter to indicate where the arguments end.
For example, suppose the current stack is S, and we want
to add the children of (f a b). Then, the new stack will
be [S, *g_delimiter, b, a]
\remark g_delimiter is an unique expression. */
static expr * g_delimiter = nullptr;
struct discr_tree::node_cmp {
int operator()(node const & n1, node const & n2) const;
};
void discr_tree::swap(node & n1, node & n2) {
std::swap(n1.m_ptr, n2.m_ptr);
}
struct discr_tree::edge {
edge_kind m_kind;
bool m_fn;
name m_name; // only relevant for Local/Const
edge(edge_kind k):m_kind(k), m_fn(false) {}
edge(expr const & e, bool fn) {
m_fn = fn;
lean_assert(is_constant(e) || is_local(e));
if (is_constant(e)) {
m_kind = edge_kind::Constant;
m_name = const_name(e);
} else {
lean_assert(is_local(e));
m_kind = edge_kind::Local;
m_name = mlocal_name(e);
}
}
};
struct discr_tree::edge_cmp {
int operator()(edge const & e1, edge const & e2) const {
if (e1.m_fn != e2.m_fn)
return static_cast<int>(e1.m_fn) - static_cast<int>(e2.m_fn);
if (e1.m_kind != e2.m_kind)
return static_cast<int>(e1.m_kind) - static_cast<int>(e2.m_kind);
return quick_cmp(e1.m_name, e2.m_name);
}
};
struct discr_tree::node_cell {
MK_LEAN_RC();
/* Unique id. We use it to implement node_cmp */
unsigned m_id;
/* We use a map based tree to map edges to nodes, we should investigate whether we really need a tree here.
We suspect the set of edges is usually quite small. So, an assoc-list may be enough.
We should also investigate whether a small array + hash code based on the edge is not enough.
Note that we may even ignore collisions since this is an imperfect discrimination tree anyway. */
rb_map<edge, node, edge_cmp> m_children;
node m_star_child;
/* The skip set is needed when searching for the set of terms stored in the discrimination tree
that may match an input term containing metavariables. In the literature, they are called
skip set/list. */
rb_tree<node, node_cmp> m_skip;
rb_expr_tree m_values;
void dealloc();
node_cell();
node_cell(node_cell const & s);
};
DEF_THREAD_MEMORY_POOL(get_allocator, sizeof(discr_tree::node_cell));
LEAN_THREAD_VALUE(unsigned, g_next_id, 0);
MK_THREAD_LOCAL_GET_DEF(std::vector<unsigned>, get_recycled_ids);
static unsigned mk_id() {
auto & ids = get_recycled_ids();
unsigned r;
if (ids.empty()) {
r = g_next_id;
g_next_id++;
} else {
r = ids.back();
ids.pop_back();
}
return r;
}
discr_tree::node_cell::node_cell():m_rc(0), m_id(mk_id()) {
}
discr_tree::node_cell::node_cell(node_cell const & s):
m_rc(0), m_id(mk_id()),
m_children(s.m_children),
m_star_child(s.m_star_child),
m_values(s.m_values) {
}
void discr_tree::node_cell::dealloc() {
this->~node_cell();
get_recycled_ids().push_back(m_id);
get_allocator().recycle(this);
}
auto discr_tree::ensure_unshared(node && n) -> node {
if (!n.m_ptr)
return node(new (get_allocator().allocate()) node_cell());
else if (n.is_shared())
return node(new (get_allocator().allocate()) node_cell(*n.m_ptr));
else
return n;
}
discr_tree::node::node(node_cell * ptr):m_ptr(ptr) { if (m_ptr) ptr->inc_ref(); }
discr_tree::node::node(node const & s):m_ptr(s.m_ptr) { if (m_ptr) m_ptr->inc_ref(); }
discr_tree::node::node(node && s):m_ptr(s.m_ptr) { s.m_ptr = nullptr; }
discr_tree::node::~node() { if (m_ptr) m_ptr->dec_ref(); }
discr_tree::node & discr_tree::node::operator=(node const & n) { LEAN_COPY_REF(n); }
discr_tree::node & discr_tree::node::operator=(node&& n) { LEAN_MOVE_REF(n); }
bool discr_tree::node::is_shared() const { return m_ptr && m_ptr->get_rc() > 1; }
int discr_tree::node_cmp::operator()(node const & n1, node const & n2) const {
if (n1.m_ptr) {
return n2.m_ptr ? unsigned_cmp()(n1.m_ptr->m_id, n2.m_ptr->m_id) : 1;
} else {
return n2.m_ptr ? -1 : 0;
}
}
auto discr_tree::insert_erase_atom(type_context_old & ctx, node && n, edge const & e, buffer<pair<expr, bool>> & todo,
expr const & v, buffer<pair<node, node>> & skip, bool ins) -> node {
node new_n = ensure_unshared(n.steal());
if (auto child = new_n.m_ptr->m_children.find(e)) {
node new_child(*child);
new_n.m_ptr->m_children.erase(e);
new_child = insert_erase(ctx, new_child.steal(), false, todo, v, skip, ins);
new_n.m_ptr->m_children.insert(e, new_child);
return new_n;
} else {
node new_child = insert_erase(ctx, node(), false, todo, v, skip, ins);
new_n.m_ptr->m_children.insert(e, new_child);
return new_n;
}
}
auto discr_tree::insert_erase_star(type_context_old & ctx, node && n, buffer<pair<expr, bool>> & todo, expr const & v,
buffer<pair<node, node>> & skip, bool ins) -> node {
node new_n = ensure_unshared(n.steal());
new_n.m_ptr->m_star_child = insert_erase(ctx, new_n.m_ptr->m_star_child.steal(), false, todo, v, skip, ins);
return new_n;
}
auto discr_tree::insert_erase_app(type_context_old & ctx,
node && n, bool is_root, expr const & e, buffer<pair<expr, bool>> & todo, expr const & v,
buffer<pair<node, node>> & skip, bool ins) -> node {
lean_assert(is_app(e));
buffer<expr> args;
expr const & fn = get_app_args(e, args);
if (is_constant(fn) || is_local(fn)) {
if (!is_root)
todo.push_back(mk_pair(*g_delimiter, false));
fun_info info = get_fun_info(ctx, fn, args.size());
buffer<param_info> pinfos;
to_buffer(info.get_params_info(), pinfos);
lean_assert(pinfos.size() == args.size());
unsigned i = args.size();
while (i > 0) {
--i;
if (pinfos[i].is_prop() || pinfos[i].is_inst_implicit() || pinfos[i].is_implicit())
continue; // We ignore propositions, implicit and inst-implict arguments
todo.push_back(mk_pair(args[i], false));
}
todo.push_back(mk_pair(fn, true));
node new_n = insert_erase(ctx, std::move(n), false, todo, v, skip, ins);
if (!is_root) {
lean_assert(!skip.empty());
// Update skip set.
pair<node, node> const & p = skip.back();
new_n.m_ptr->m_skip.erase(p.first); // remove old skip node
new_n.m_ptr->m_skip.insert(p.second); // insert new skip node
skip.pop_back();
}
return new_n;
} else if (is_meta(fn)) {
return insert_erase_star(ctx, std::move(n), todo, v, skip, ins);
} else {
return insert_erase_atom(ctx, std::move(n), edge(edge_kind::Unsupported), todo, v, skip, ins);
}
}
auto discr_tree::insert_erase(type_context_old & ctx,
node && n, bool is_root, buffer<pair<expr, bool>> & todo,
expr const & v, buffer<pair<node, node>> & skip, bool ins) -> node {
if (todo.empty()) {
node new_n = ensure_unshared(n.steal());
if (ins)
new_n.m_ptr->m_values.insert(v);
else
new_n.m_ptr->m_values.erase(v);
return new_n;
}
pair<expr, bool> p = todo.back();
todo.pop_back();
expr const & e = p.first;
bool fn = p.second;
if (is_eqp(e, *g_delimiter)) {
node old_n(n);
node new_n = insert_erase(ctx, std::move(n), false, todo, v, skip, ins);
skip.emplace_back(old_n, new_n);
return new_n;
}
switch (e.kind()) {
case expr_kind::Constant: case expr_kind::Local:
return insert_erase_atom(ctx, std::move(n), edge(e, fn), todo, v, skip, ins);
case expr_kind::Meta:
return insert_erase_star(ctx, std::move(n), todo, v, skip, ins);
case expr_kind::App:
return insert_erase_app(ctx, std::move(n), is_root, e, todo, v, skip, ins);
case expr_kind::Var:
lean_unreachable();
case expr_kind::Sort: case expr_kind::Lambda:
case expr_kind::Pi: case expr_kind::Macro:
case expr_kind::Let:
// unsupported
return insert_erase_atom(ctx, std::move(n), edge(edge_kind::Unsupported), todo, v, skip, ins);
}
lean_unreachable();
}
void discr_tree::insert_erase(type_context_old & ctx, expr const & k, expr const & v, bool ins) {
// insert & erase operations.
// The erase operation is not optimal because it does not eliminate dead branches from the tree.
// If this becomes an issue, we can remove dead branches from time to time and/or reconstruct
// the tree from time to time.
buffer<pair<expr, bool>> todo;
buffer<pair<node, node>> skip;
todo.push_back(mk_pair(k, false));
m_root = insert_erase(ctx, m_root.steal(), true, todo, v, skip, ins);
lean_trace("discr_tree", tout() << "\n"; trace(););
}
bool discr_tree::find_atom(type_context_old & ctx, node const & n, edge const & e, list<pair<expr, bool>> todo, std::function<bool(expr const &)> const & fn) { // NOLINT
if (auto child = n.m_ptr->m_children.find(e)) {
return find(ctx, *child, todo, fn);
} else {
return true; // continue
}
}
bool discr_tree::find_star(type_context_old & ctx, node const & n, list<pair<expr, bool>> todo, std::function<bool(expr const &)> const & fn) { // NOLINT
bool cont = true;
n.m_ptr->m_skip.for_each([&](node const & skip_child) {
if (cont && !find(ctx, skip_child, todo, fn))
cont = false;
});
if (!cont)
return false;
// we also have to traverse children whose edge is an atom.
n.m_ptr->m_children.for_each([&](edge const & e, node const & child) {
if (cont && !e.m_fn && !find(ctx, child, todo, fn))
cont = false;
});
return cont;
}
bool discr_tree::find_app(type_context_old & ctx, node const & n, expr const & e, list<pair<expr, bool>> todo, std::function<bool(expr const &)> const & fn) { // NOLINT
lean_assert(is_app(e));
buffer<expr> args;
expr const & f = get_app_args(e, args);
if (is_constant(f) || is_local(f)) {
fun_info info = get_fun_info(ctx, f, args.size());
buffer<param_info> pinfos;
to_buffer(info.get_params_info(), pinfos);
lean_assert(pinfos.size() == args.size());
unsigned i = args.size();
list<pair<expr, bool>> new_todo = todo;
while (i > 0) {
--i;
if (pinfos[i].is_prop() || pinfos[i].is_inst_implicit() || pinfos[i].is_implicit())
continue; // We ignore propositions, implicit and inst-implict arguments
new_todo = cons(mk_pair(args[i], false), new_todo);
}
new_todo = cons(mk_pair(f, true), new_todo);
return find(ctx, n, new_todo, fn);
} else if (is_meta(f)) {
return find_star(ctx, n, todo, fn);
} else {
return find_atom(ctx, n, edge(edge_kind::Unsupported), todo, fn);
}
}
bool discr_tree::find(type_context_old & ctx, node const & n, list<pair<expr, bool>> todo, std::function<bool(expr const &)> const & fn) { // NOLINT
if (!todo) {
bool cont = true;
n.m_ptr->m_values.for_each([&](expr const & v) {
if (cont && !fn(v))
cont = false;
});
return cont;
}
if (n.m_ptr->m_star_child && !find(ctx, n.m_ptr->m_star_child, tail(todo), fn))
return false; // stop search
pair<expr, bool> const & p = head(todo);
expr const & e = p.first;
bool is_fn = p.second;
switch (e.kind()) {
case expr_kind::Constant: case expr_kind::Local:
return find_atom(ctx, n, edge(e, is_fn), tail(todo), fn);
case expr_kind::Meta:
return find_star(ctx, n, tail(todo), fn);
case expr_kind::App:
return find_app(ctx, n, e, tail(todo), fn);
case expr_kind::Var:
lean_unreachable();
case expr_kind::Sort: case expr_kind::Lambda:
case expr_kind::Pi: case expr_kind::Macro:
case expr_kind::Let:
// unsupported
return find_atom(ctx, n, edge(edge_kind::Unsupported), tail(todo), fn);
}
lean_unreachable();
}
void discr_tree::find(type_context_old & ctx, expr const & e, std::function<bool(expr const &)> const & fn) const { // NOLINT
if (m_root)
find(ctx, m_root, to_list(mk_pair(e, false)), fn);
}
void discr_tree::collect(type_context_old & ctx, expr const & e, buffer<expr> & r) const {
find(ctx, e, [&](expr const & v) { r.push_back(v); return true; });
}
static void indent(unsigned depth) {
for (unsigned i = 0; i < depth; i++) tout() << " ";
}
void discr_tree::node::trace(optional<edge> const & e, unsigned depth, bool disj) const {
if (!m_ptr) {
tout() << "[null]\n";
return;
}
indent(depth);
if (disj)
tout() << "| ";
else if (depth > 0)
tout() << " ";
if (e) {
switch (e->m_kind) {
case edge_kind::Constant:
tout() << e->m_name;
break;
case edge_kind::Local:
tout() << e->m_name;
break;
case edge_kind::Star:
tout() << "*";
break;
case edge_kind::Unsupported:
tout() << "#";
break;
}
if (e->m_fn)
tout() << " (fn)";
tout() << " -> ";
}
tout() << "[" << m_ptr->m_id << "] {";
bool first = true;
m_ptr->m_skip.for_each([&](node const & s) {
if (first) first = false; else tout() << ", ";
tout() << s.m_ptr->m_id;
});
tout() << "}";
if (!m_ptr->m_values.empty()) {
tout() << " {";
first = true;
m_ptr->m_values.for_each([&](expr const & v) {
if (first) first = false; else tout() << ", ";
tout() << v;
});
tout() << "}";
}
tout() << "\n";
unsigned new_depth = depth;
unsigned num_children = m_ptr->m_children.size();
if (m_ptr->m_star_child)
num_children++;
if (num_children > 1)
new_depth++;
m_ptr->m_children.for_each([&](edge const & e, node const & n) {
n.trace(optional<edge>(e), new_depth, num_children > 1);
});
if (m_ptr->m_star_child) {
m_ptr->m_star_child.trace(optional<edge>(edge_kind::Star), new_depth, num_children > 1);
}
}
void discr_tree::trace() const {
m_root.trace(optional<edge>(), 0, false);
}
void initialize_discr_tree() {
register_trace_class(name{"discr_tree"});
g_delimiter = new expr(mk_constant(name::mk_internal_unique_name()));
}
void finalize_discr_tree() {
delete g_delimiter;
}
}
| 36.381733 | 169 | 0.592404 | [
"vector"
] |
aa43a84928dbf409d8cb056668c73fa436662c2a | 3,849 | cpp | C++ | src/colorer/parsers/FileTypeImpl.cpp | elfmz/Colorer-library | b1ddc95064a030bfc583eea1a7f70c9cdc1a9e30 | [
"MIT"
] | null | null | null | src/colorer/parsers/FileTypeImpl.cpp | elfmz/Colorer-library | b1ddc95064a030bfc583eea1a7f70c9cdc1a9e30 | [
"MIT"
] | null | null | null | src/colorer/parsers/FileTypeImpl.cpp | elfmz/Colorer-library | b1ddc95064a030bfc583eea1a7f70c9cdc1a9e30 | [
"MIT"
] | null | null | null | #include <colorer/parsers/FileTypeImpl.h>
#include <colorer/unicode/UnicodeTools.h>
#include <memory>
FileTypeImpl::FileTypeImpl(HRCParserImpl* hrcParser): name(nullptr), group(nullptr), description(nullptr)
{
this->hrcParser = hrcParser;
protoLoaded = type_loaded = loadDone = load_broken = input_source_loading = false;
isPackage = false;
baseScheme = nullptr;
inputSource = nullptr;
}
FileTypeImpl::~FileTypeImpl(){
for(auto it : chooserVector){
delete it;
}
chooserVector.clear();
for(const auto& it: paramsHash){
delete it.second;
}
paramsHash.clear();
importVector.clear();
}
Scheme* FileTypeImpl::getBaseScheme() {
if (!type_loaded) hrcParser->loadFileType(this);
return baseScheme;
}
std::vector<SString> FileTypeImpl::enumParams() const {
std::vector<SString> r;
r.reserve(paramsHash.size());
for (const auto & p : paramsHash)
{
r.push_back(p.first);
}
return r;
}
const String* FileTypeImpl::getParamDescription(const String &name) const{
auto tp = paramsHash.find(name);
if (tp != paramsHash.end()) return tp->second->description.get();
return nullptr;
}
const String *FileTypeImpl::getParamValue(const String &name) const{
auto tp = paramsHash.find(name);
if (tp != paramsHash.end()){
if(tp->second->user_value) return tp->second->user_value.get();
return tp->second->default_value.get();
}
return nullptr;
}
int FileTypeImpl::getParamValueInt(const String &name, int def) const{
int val = def;
UnicodeTools::getNumber(getParamValue(name), &val);
return val;
}
const String* FileTypeImpl::getParamDefaultValue(const String &name) const{
auto tp = paramsHash.find(name);
if (tp !=paramsHash.end()) {
return tp->second->default_value.get();
}
return nullptr;
}
const String* FileTypeImpl::getParamUserValue(const String &name) const{
auto tp = paramsHash.find(name);
if (tp !=paramsHash.end()) {
return tp->second->user_value.get();
}
return nullptr;
}
TypeParameter* FileTypeImpl::addParam(const String *name){
auto* tp = new TypeParameter;
tp->name = std::make_unique<SString>(name);
std::pair<SString, TypeParameter*> pp(name, tp);
paramsHash.emplace(pp);
return tp;
}
void FileTypeImpl::setParamValue(const String &name, const String *value){
auto tp = paramsHash.find(name);
if (tp != paramsHash.end()) {
if (value) {
tp->second->user_value = std::make_unique<SString>(value);
}
else{
tp->second->user_value = nullptr;
}
}
}
void FileTypeImpl::setParamDefaultValue(const String &name, const String *value){
auto tp = paramsHash.find(name);
if (tp != paramsHash.end()) {
tp->second->default_value = std::make_unique<SString>(value);
}
}
void FileTypeImpl::setParamUserValue(const String &name, const String *value){
setParamValue(name,value);
}
void FileTypeImpl::setParamDescription(const String &name, const String *value){
auto tp = paramsHash.find(name);
if (tp != paramsHash.end()) {
tp->second->description = std::make_unique<SString>(value);
}
}
void FileTypeImpl::removeParamValue(const String &name){
paramsHash.erase(name);
}
size_t FileTypeImpl::getParamCount() const{
return paramsHash.size();
}
size_t FileTypeImpl::getParamUserValueCount() const{
size_t count=0;
for (const auto & it : paramsHash){
if (it.second->user_value) count++;
}
return count;
}
double FileTypeImpl::getPriority(const String *fileName, const String *fileContent) const{
SMatches match;
double cur_prior = 0;
for(auto ftc : chooserVector){
if (fileName != nullptr && ftc->isFileName() && ftc->getRE()->parse(fileName, &match))
cur_prior += ftc->getPriority();
if (fileContent != nullptr && ftc->isFileContent() && ftc->getRE()->parse(fileContent, &match))
cur_prior += ftc->getPriority();
}
return cur_prior;
}
| 26.183673 | 105 | 0.696285 | [
"vector"
] |
aa4a4c8d6eee207d300ecba4a6b635fa41dff114 | 3,322 | cc | C++ | confonnx/test/helpers/tensorproto_converter.cc | kapilvgit/onnx-server-openenclave | 974e747c9ba08d6a4fc5cc9943acc1b937a933df | [
"MIT"
] | null | null | null | confonnx/test/helpers/tensorproto_converter.cc | kapilvgit/onnx-server-openenclave | 974e747c9ba08d6a4fc5cc9943acc1b937a933df | [
"MIT"
] | null | null | null | confonnx/test/helpers/tensorproto_converter.cc | kapilvgit/onnx-server-openenclave | 974e747c9ba08d6a4fc5cc9943acc1b937a933df | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <iostream>
#include <unordered_set>
#include "onnx_protobuf.h"
#include "predict_protobuf.h"
#include "test/helpers/pb_loader.h"
#include "test/helpers/prettyprint.h"
#include "test/helpers/tensorproto_util.h"
#include "test/helpers/tensorproto_converter.h"
namespace onnxruntime {
namespace server {
namespace test {
namespace pb = google::protobuf;
PredictRequest TensorProtoToRequest(const ONNX_NAMESPACE::ModelProto& model,
const std::vector<std::string>& paths) {
const ONNX_NAMESPACE::GraphProto& graph = model.graph();
// Determine all graph inputs without initializer.
std::unordered_set<std::string> initializer_names;
for (const auto& init : graph.initializer()) {
if (!init.has_name()) continue;
initializer_names.insert(init.name());
}
std::vector<std::string> input_names;
for (const auto& p : graph.input()) {
if (!p.has_name()) throw std::invalid_argument("input without name??");
if (initializer_names.find(p.name()) == initializer_names.end()) {
input_names.push_back(p.name());
}
}
if (input_names.size() != paths.size()) {
throw std::invalid_argument(
"Number of graph inputs (" + std::to_string(input_names.size()) + ") " +
"not equal to number of paths (" + std::to_string(paths.size()) + ")");
}
PredictRequest request;
pb::Map<std::string, ONNX_NAMESPACE::TensorProto>* inputs = request.mutable_inputs();
for (size_t i = 0; i < paths.size(); i++) {
auto input_name = input_names[i];
auto tensor = LoadProtobufFromFile<ONNX_NAMESPACE::TensorProto>(paths[i]);
std::cout << "Input: " << input_name << " = " << paths[i] << std::endl;
std::cout << " Shape: " << GetTensorShapeFromTensorProto(tensor) << std::endl;
inputs->insert({input_name, std::move(tensor)});
}
for (const auto& p : graph.output()) {
std::string output_name = p.name();
std::cout << "Output filter: " << output_name << std::endl;
request.add_output_filter(std::move(output_name));
}
return request;
}
PredictResponse TensorProtoToResponse(const ONNX_NAMESPACE::ModelProto& model,
const std::vector<std::string>& paths) {
const ONNX_NAMESPACE::GraphProto& graph = model.graph();
if (graph.output().size() != static_cast<int>(paths.size())) {
throw std::invalid_argument(
"Number of graph outputs (" + std::to_string(graph.output().size()) + ") " +
"not equal to number of paths (" + std::to_string(paths.size()) + ")");
}
PredictResponse response;
pb::Map<std::string, ONNX_NAMESPACE::TensorProto>* outputs = response.mutable_outputs();
for (size_t i = 0; i < paths.size(); i++) {
auto output_name = graph.output(i).name();
std::cout << "Output: " << output_name << " = " << paths[i] << std::endl;
auto tensor_proto = LoadProtobufFromFile<ONNX_NAMESPACE::TensorProto>(paths[i]);
tensor_proto.clear_name(); // to match server output
std::cout << " Shape: " << GetTensorShapeFromTensorProto(tensor_proto) << std::endl;
outputs->insert({output_name, std::move(tensor_proto)});
}
return response;
}
} // namespace test
} // namespace server
} // namespace onnxruntime
| 37.325843 | 90 | 0.661048 | [
"shape",
"vector",
"model"
] |
aa5361d3483b98be9dcebd3c3f254430b6089b66 | 1,025 | cpp | C++ | source/Crinkler/Transform.cpp | Vertver/Crinkler | 608f1aff6041b394ed3b206e30d67f4a47b25d83 | [
"BSD-3-Clause"
] | 739 | 2020-07-21T21:08:21.000Z | 2022-03-29T20:59:43.000Z | source/Crinkler/Transform.cpp | Vertver/Crinkler | 608f1aff6041b394ed3b206e30d67f4a47b25d83 | [
"BSD-3-Clause"
] | 10 | 2020-08-07T21:24:03.000Z | 2021-11-23T16:11:51.000Z | source/Crinkler/Transform.cpp | Vertver/Crinkler | 608f1aff6041b394ed3b206e30d67f4a47b25d83 | [
"BSD-3-Clause"
] | 47 | 2020-07-21T22:14:12.000Z | 2022-03-14T04:44:37.000Z | #include "Transform.h"
#include "Hunk.h"
#include "HunkList.h"
#include "Log.h"
#include "Symbol.h"
#include "Crinkler.h"
bool Transform::LinkAndTransform(HunkList* hunklist, Symbol *entry_label, int baseAddress, Hunk* &transformedHunk, Hunk** untransformedHunk, int* splittingPoint, bool verbose)
{
Hunk* detrans = nullptr;
if (m_enabled)
{
detrans = GetDetransformer();
if(detrans)
{
detrans->SetVirtualSize(detrans->GetRawSize());
}
}
if(!detrans)
{
detrans = new Hunk("Stub", NULL, HUNK_IS_CODE, 0, 0, 0);
}
hunklist->AddHunkFront(detrans);
detrans->SetContinuation(entry_label);
int sp;
transformedHunk = hunklist->ToHunk("linked", baseAddress, &sp);
transformedHunk->Relocate(baseAddress);
if (splittingPoint)
{
*splittingPoint = sp;
}
if (untransformedHunk)
{
*untransformedHunk = new Hunk(*transformedHunk);
}
hunklist->RemoveHunk(detrans);
delete detrans;
return m_enabled ? DoTransform(transformedHunk, sp, verbose) : false;
} | 22.777778 | 176 | 0.687805 | [
"transform"
] |
aa53ba0f9d049cb80c0340ae02563adbf047b821 | 5,681 | cc | C++ | L1Trigger/L1TMuonEndCap/test/tools/MakePtLUT.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | L1Trigger/L1TMuonEndCap/test/tools/MakePtLUT.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | L1Trigger/L1TMuonEndCap/test/tools/MakePtLUT.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include <memory>
#include <vector>
#include <iostream>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
// #include "L1Trigger/L1TMuonEndCap/interface/PtAssignmentEngine2016.h"
#include "L1Trigger/L1TMuonEndCap/interface/PtAssignmentEngine2017.h"
#include "L1Trigger/L1TMuonEndCap/interface/PtLUTWriter.h"
#include "helper.h"
#include "progress_bar.h"
class MakePtLUT : public edm::EDAnalyzer {
public:
explicit MakePtLUT(const edm::ParameterSet&);
virtual ~MakePtLUT();
private:
//virtual void beginJob();
//virtual void endJob();
//virtual void beginRun(const edm::Run&, const edm::EventSetup&);
//virtual void endRun(const edm::Run&, const edm::EventSetup&);
virtual void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup);
void makeLUT();
void checkAddresses();
private:
std::unique_ptr<PtAssignmentEngine> pt_assign_engine_;
PtLUTWriter ptlut_writer_;
const edm::ParameterSet config_;
int verbose_;
int num_;
int denom_;
std::string xml_dir_;
std::string outfile_;
bool onlyCheck_;
std::vector<unsigned long long> addressesToCheck_;
bool done_;
};
// _____________________________________________________________________________
#define PTLUT_SIZE (1<<30)
MakePtLUT::MakePtLUT(const edm::ParameterSet& iConfig) :
// pt_assign_engine_(new PtAssignmentEngine2016()),
pt_assign_engine_(new PtAssignmentEngine2017()),
ptlut_writer_(),
config_(iConfig),
verbose_(iConfig.getUntrackedParameter<int>("verbosity")),
num_(iConfig.getParameter<int>("numerator")),
denom_(iConfig.getParameter<int>("denominator")),
outfile_(iConfig.getParameter<std::string>("outfile")),
onlyCheck_(iConfig.getParameter<bool>("onlyCheck")),
addressesToCheck_(iConfig.getParameter<std::vector<unsigned long long> >("addressesToCheck")),
done_(false)
{
auto ptLUTVersion = iConfig.getParameter<int>("PtLUTVersion");
const edm::ParameterSet spPAParams16 = config_.getParameter<edm::ParameterSet>("spPAParams16");
auto bdtXMLDir = spPAParams16.getParameter<std::string>("BDTXMLDir");
auto readPtLUTFile = spPAParams16.getParameter<bool>("ReadPtLUTFile");
auto fixMode15HighPt = spPAParams16.getParameter<bool>("FixMode15HighPt");
auto bug9BitDPhi = spPAParams16.getParameter<bool>("Bug9BitDPhi");
auto bugMode7CLCT = spPAParams16.getParameter<bool>("BugMode7CLCT");
auto bugNegPt = spPAParams16.getParameter<bool>("BugNegPt");
ptlut_writer_.set_version(ptLUTVersion);
pt_assign_engine_->configure(
verbose_,
readPtLUTFile, fixMode15HighPt,
bug9BitDPhi, bugMode7CLCT, bugNegPt
);
xml_dir_ = bdtXMLDir;
}
MakePtLUT::~MakePtLUT() {}
void MakePtLUT::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
if (done_) return;
if (onlyCheck_) {
checkAddresses();
} else {
makeLUT();
}
done_ = true;
return;
}
void MakePtLUT::makeLUT() {
// Load XMLs inside function
std::cout << "Inside makeLUT() - loading XMLs" << std::endl;
pt_assign_engine_->read(config_.getParameter<int>("PtLUTVersion"), xml_dir_);
std::cout << "Calculating pT for " << PTLUT_SIZE / denom_ << " addresses, please sit tight..." << std::endl;
if (num_ - 1 < 0) std::cout << "ERROR: tried to fill address < 0. KILL!!!" << std::endl;
PtLUTWriter::address_t address = abs((num_ - 1) * (PTLUT_SIZE / denom_));
float xmlpt = 0.;
float pt = 0.;
int gmt_pt = 0;
for ( ; address < (PtLUTWriter::address_t) abs(num_ * (PTLUT_SIZE / denom_)); ++address) {
if (address % (PTLUT_SIZE / (denom_ * 128)) == 0)
show_progress_bar(address, PTLUT_SIZE);
//int mode_inv = (address >> (30-4)) & ((1<<4)-1);
// floats
xmlpt = pt_assign_engine_->calculate_pt(address);
pt = (xmlpt < 0.) ? 1. : xmlpt; // Matt used fabs(-1) when mode is invalid
pt *= pt_assign_engine_->scale_pt(pt, 15); // Multiply by some factor to achieve 90% efficiency at threshold
// integers
gmt_pt = (pt * 2) + 1;
gmt_pt = (gmt_pt > 511) ? 511 : gmt_pt;
//if (address % (1<<20) == 0)
// std::cout << mode_inv << " " << address << " " << print_subaddresses(address) << " " << gmt_pt << std::endl;
ptlut_writer_.push_back(gmt_pt);
}
std::cout << "\nAbout to write file " << outfile_ << " for part " << num_ << "/" << denom_ << std::endl;
ptlut_writer_.write(outfile_, num_, denom_);
std::cout << "Wrote file! DONE!" << std::endl;
}
void MakePtLUT::checkAddresses() {
unsigned int n = addressesToCheck_.size();
std::cout << "Calculating pT for " << n << " addresses, please sit tight..." << std::endl;
PtLUTWriter::address_t address = 0;
float xmlpt = 0.;
float pt = 0.;
int gmt_pt = 0;
for (unsigned int i=0; i<n; ++i) {
//show_progress_bar(i, n);
address = addressesToCheck_.at(i);
int mode_inv = (address >> (30-4)) & ((1<<4)-1);
// floats
xmlpt = pt_assign_engine_->calculate_pt(address);
pt = (xmlpt < 0.) ? 1. : xmlpt; // Matt used fabs(-1) when mode is invalid
pt *= 1.4; // multiply by 1.4 to keep efficiency above 90% when the L1 trigger pT cut is applied
// integers
gmt_pt = (pt * 2) + 1;
gmt_pt = (gmt_pt > 511) ? 511 : gmt_pt;
std::cout << mode_inv << " " << address << " " << print_subaddresses(address) << " " << gmt_pt << std::endl;
}
}
// DEFINE THIS AS A PLUG-IN
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(MakePtLUT);
| 30.875 | 116 | 0.676289 | [
"vector"
] |
aa60dac511c31fb4e951b5b3b808e2c6798b6d15 | 42,204 | cpp | C++ | B2G/gecko/security/manager/ssl/src/nsIdentityChecking.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/security/manager/ssl/src/nsIdentityChecking.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/security/manager/ssl/src/nsIdentityChecking.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsNSSCertificate.h"
#include "nsNSSComponent.h"
#include "nsSSLStatus.h"
#ifndef NSS_NO_LIBPKIX
#include "mozilla/RefPtr.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsStreamUtils.h"
#include "nsNetUtil.h"
#include "nsILineInputStream.h"
#include "nsPromiseFlatString.h"
#include "nsTArray.h"
#include "cert.h"
#include "base64.h"
#include "nsSSLStatus.h"
#include "ScopedNSSTypes.h"
//
#include "nsAppDirectoryServiceDefs.h"
#include "nsStreamUtils.h"
#include "nsNetUtil.h"
#include "nsILineInputStream.h"
#include "nsPromiseFlatString.h"
#include "nsTArray.h"
#include "cert.h"
#include "base64.h"
#include "nsNSSComponent.h"
#include "nsSSLStatus.h"
#include "nsNSSCertificate.h"
#include "nsNSSCleaner.h"
using namespace mozilla;
#ifdef DEBUG
#ifndef PSM_ENABLE_TEST_EV_ROOTS
#define PSM_ENABLE_TEST_EV_ROOTS
#endif
#endif
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate)
NSSCleanupAutoPtrClass(CERTCertList, CERT_DestroyCertList)
NSSCleanupAutoPtrClass_WithParam(SECItem, SECITEM_FreeItem, TrueParam, true)
#define CONST_OID static const unsigned char
#define OI(x) { siDEROID, (unsigned char *)x, sizeof x }
struct nsMyTrustedEVInfo
{
const char *dotted_oid;
const char *oid_name; // Set this to null to signal an invalid structure,
// (We can't have an empty list, so we'll use a dummy entry)
SECOidTag oid_tag;
const char *ev_root_sha1_fingerprint;
const char *issuer_base64;
const char *serial_base64;
CERTCertificate *cert;
};
static struct nsMyTrustedEVInfo myTrustedEVInfos[] = {
/*
* IMPORTANT! When extending this list,
* pairs of dotted_oid and oid_name should always be unique pairs.
* In other words, if you add another list, that uses the same dotted_oid
* as an existing entry, then please use the same oid_name.
*/
{
// CN=WellsSecure Public Root Certificate Authority,OU=Wells Fargo Bank NA,O=Wells Fargo WellsSecure,C=US
"2.16.840.1.114171.500.9",
"WellsSecure EV OID",
SEC_OID_UNKNOWN,
"E7:B4:F6:9D:61:EC:90:69:DB:7E:90:A7:40:1A:3C:F4:7D:4F:E8:EE",
"MIGFMQswCQYDVQQGEwJVUzEgMB4GA1UECgwXV2VsbHMgRmFyZ28gV2VsbHNTZWN1"
"cmUxHDAaBgNVBAsME1dlbGxzIEZhcmdvIEJhbmsgTkExNjA0BgNVBAMMLVdlbGxz"
"U2VjdXJlIFB1YmxpYyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eQ==",
"AQ==",
nullptr
},
{
// OU=Security Communication EV RootCA1,O="SECOM Trust Systems CO.,LTD.",C=JP
"1.2.392.200091.100.721.1",
"SECOM EV OID",
SEC_OID_UNKNOWN,
"FE:B8:C4:32:DC:F9:76:9A:CE:AE:3D:D8:90:8F:FD:28:86:65:64:7D",
"MGAxCzAJBgNVBAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENP"
"LixMVEQuMSowKAYDVQQLEyFTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVWIFJvb3RD"
"QTE=",
"AA==",
nullptr
},
{
// CN=Cybertrust Global Root,O=Cybertrust, Inc
"1.3.6.1.4.1.6334.1.100.1",
"Cybertrust EV OID",
SEC_OID_UNKNOWN,
"5F:43:E5:B1:BF:F8:78:8C:AC:1C:C7:CA:4A:9A:C6:22:2B:CC:34:C6",
"MDsxGDAWBgNVBAoTD0N5YmVydHJ1c3QsIEluYzEfMB0GA1UEAxMWQ3liZXJ0cnVz"
"dCBHbG9iYWwgUm9vdA==",
"BAAAAAABD4WqLUg=",
nullptr
},
{
// CN=SwissSign Gold CA - G2,O=SwissSign AG,C=CH
"2.16.756.1.89.1.2.1.1",
"SwissSign EV OID",
SEC_OID_UNKNOWN,
"D8:C5:38:8A:B7:30:1B:1B:6E:D4:7A:E6:45:25:3A:6F:9F:1A:27:61",
"MEUxCzAJBgNVBAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMT"
"FlN3aXNzU2lnbiBHb2xkIENBIC0gRzI=",
"ALtAHEP1Xk+w",
nullptr
},
{
// CN=StartCom Certification Authority,OU=Secure Digital Certificate Signing,O=StartCom Ltd.,C=IL
"1.3.6.1.4.1.23223.2",
"StartCom EV OID",
SEC_OID_UNKNOWN,
"3E:2B:F7:F2:03:1B:96:F3:8C:E6:C4:D8:A8:5D:3E:2D:58:47:6A:0F",
"MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQL"
"EyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYDVQQDEyBT"
"dGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eQ==",
"AQ==",
nullptr
},
{
// CN=VeriSign Class 3 Public Primary Certification Authority - G5,OU="(c) 2006 VeriSign, Inc. - For authorized use only",OU=VeriSign Trust Network,O="VeriSign, Inc.",C=US
"2.16.840.1.113733.1.7.23.6",
"VeriSign EV OID",
SEC_OID_UNKNOWN,
"4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5",
"MIHKMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNV"
"BAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA2IFZl"
"cmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMT"
"PFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBB"
"dXRob3JpdHkgLSBHNQ==",
"GNrRniZ96LtKIVjNzGs7Sg==",
nullptr
},
{
// CN=GeoTrust Primary Certification Authority,O=GeoTrust Inc.,C=US
"1.3.6.1.4.1.14370.1.6",
"GeoTrust EV OID",
SEC_OID_UNKNOWN,
"32:3C:11:8E:1B:F7:B8:B6:52:54:E2:E2:10:0D:D6:02:90:37:F0:96",
"MFgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQD"
"EyhHZW9UcnVzdCBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5",
"GKy1av1pthU6Y2yv2vrEoQ==",
nullptr
},
{
// CN=thawte Primary Root CA,OU="(c) 2006 thawte, Inc. - For authorized use only",OU=Certification Services Division,O="thawte, Inc.",C=US
"2.16.840.1.113733.1.7.48.1",
"Thawte EV OID",
SEC_OID_UNKNOWN,
"91:C6:D6:EE:3E:8A:C8:63:84:E5:48:C2:99:29:5C:75:6C:81:7B:81",
"MIGpMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3RlLCBJbmMuMSgwJgYDVQQL"
"Ex9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYDVQQLEy8oYykg"
"MjAwNiB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEfMB0G"
"A1UEAxMWdGhhd3RlIFByaW1hcnkgUm9vdCBDQQ==",
"NE7VVyDV7exJ9C/ON9srbQ==",
nullptr
},
{
// CN=XRamp Global Certification Authority,O=XRamp Security Services Inc,OU=www.xrampsecurity.com,C=US
"2.16.840.1.114404.1.1.2.4.1",
"Trustwave EV OID",
SEC_OID_UNKNOWN,
"B8:01:86:D1:EB:9C:86:A5:41:04:CF:30:54:F3:4C:52:B7:E5:58:C6",
"MIGCMQswCQYDVQQGEwJVUzEeMBwGA1UECxMVd3d3LnhyYW1wc2VjdXJpdHkuY29t"
"MSQwIgYDVQQKExtYUmFtcCBTZWN1cml0eSBTZXJ2aWNlcyBJbmMxLTArBgNVBAMT"
"JFhSYW1wIEdsb2JhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eQ==",
"UJRs7Bjq1ZxN1ZfvdY+grQ==",
nullptr
},
{
// CN=SecureTrust CA,O=SecureTrust Corporation,C=US
"2.16.840.1.114404.1.1.2.4.1",
"Trustwave EV OID",
SEC_OID_UNKNOWN,
"87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11",
"MEgxCzAJBgNVBAYTAlVTMSAwHgYDVQQKExdTZWN1cmVUcnVzdCBDb3Jwb3JhdGlv"
"bjEXMBUGA1UEAxMOU2VjdXJlVHJ1c3QgQ0E=",
"DPCOXAgWpa1Cf/DrJxhZ0A==",
nullptr
},
{
// CN=Secure Global CA,O=SecureTrust Corporation,C=US
"2.16.840.1.114404.1.1.2.4.1",
"Trustwave EV OID",
SEC_OID_UNKNOWN,
"3A:44:73:5A:E5:81:90:1F:24:86:61:46:1E:3B:9C:C4:5F:F5:3A:1B",
"MEoxCzAJBgNVBAYTAlVTMSAwHgYDVQQKExdTZWN1cmVUcnVzdCBDb3Jwb3JhdGlv"
"bjEZMBcGA1UEAxMQU2VjdXJlIEdsb2JhbCBDQQ==",
"B1YipOjUiolN9BPI8PjqpQ==",
nullptr
},
{
// CN=COMODO ECC Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
"1.3.6.1.4.1.6449.1.2.1.5.1",
"Comodo EV OID",
SEC_OID_UNKNOWN,
"9F:74:4E:9F:2B:4D:BA:EC:0F:31:2C:50:B6:56:3B:8E:2D:93:C3:11",
"MIGFMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAw"
"DgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDErMCkG"
"A1UEAxMiQ09NT0RPIEVDQyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eQ==",
"H0evqmIAcFBUTAGem2OZKg==",
nullptr
},
{
// CN=COMODO Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB
"1.3.6.1.4.1.6449.1.2.1.5.1",
"Comodo EV OID",
SEC_OID_UNKNOWN,
"66:31:BF:9E:F7:4F:9E:B6:C9:D5:A6:0C:BA:6A:BE:D1:F7:BD:EF:7B",
"MIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAw"
"DgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDEnMCUG"
"A1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0aG9yaXR5",
"ToEtioJl4AsC7j41AkblPQ==",
nullptr
},
{
// CN=AddTrust External CA Root,OU=AddTrust External TTP Network,O=AddTrust AB,C=SE
"1.3.6.1.4.1.6449.1.2.1.5.1",
"Comodo EV OID",
SEC_OID_UNKNOWN,
"02:FA:F3:E2:91:43:54:68:60:78:57:69:4D:F5:E4:5B:68:85:18:68",
"MG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMd"
"QWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0"
"IEV4dGVybmFsIENBIFJvb3Q=",
"AQ==",
nullptr
},
{
// CN=UTN - DATACorp SGC,OU=http://www.usertrust.com,O=The USERTRUST Network,L=Salt Lake City,ST=UT,C=US
"1.3.6.1.4.1.6449.1.2.1.5.1",
"Comodo EV OID",
SEC_OID_UNKNOWN,
"58:11:9F:0E:12:82:87:EA:50:FD:D9:87:45:6F:4F:78:DC:FA:D6:D4",
"MIGTMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFr"
"ZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsT"
"GGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNv"
"cnAgU0dD",
"RL4Mi1AAIbQR0ypoBqmtaQ==",
nullptr
},
{
// CN=UTN-USERFirst-Hardware,OU=http://www.usertrust.com,O=The USERTRUST Network,L=Salt Lake City,ST=UT,C=US
"1.3.6.1.4.1.6449.1.2.1.5.1",
"Comodo EV OID",
SEC_OID_UNKNOWN,
"04:83:ED:33:99:AC:36:08:05:87:22:ED:BC:5E:46:00:E3:BE:F9:D7",
"MIGXMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFr"
"ZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsT"
"GGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEfMB0GA1UEAxMWVVROLVVTRVJGaXJz"
"dC1IYXJkd2FyZQ==",
"RL4Mi1AAJLQR0zYq/mUK/Q==",
nullptr
},
{
// OU=Go Daddy Class 2 Certification Authority,O=\"The Go Daddy Group, Inc.\",C=US
"2.16.840.1.114413.1.7.23.3",
"Go Daddy EV OID a",
SEC_OID_UNKNOWN,
"27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4",
"MGMxCzAJBgNVBAYTAlVTMSEwHwYDVQQKExhUaGUgR28gRGFkZHkgR3JvdXAsIElu"
"Yy4xMTAvBgNVBAsTKEdvIERhZGR5IENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRo"
"b3JpdHk=",
"AA==",
nullptr
},
{
// CN=Go Daddy Root Certificate Authority - G2,O="GoDaddy.com, Inc.",L=Scottsdale,ST=Arizona,C=US
"2.16.840.1.114413.1.7.23.3",
"Go Daddy EV OID a",
SEC_OID_UNKNOWN,
"47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B",
"MIGDMQswCQYDVQQGEwJVUzEQMA4GA1UECBMHQXJpem9uYTETMBEGA1UEBxMKU2Nv"
"dHRzZGFsZTEaMBgGA1UEChMRR29EYWRkeS5jb20sIEluYy4xMTAvBgNVBAMTKEdv"
"IERhZGR5IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IC0gRzI=",
"AA==",
nullptr
},
{
// E=info@valicert.com,CN=http://www.valicert.com/,OU=ValiCert Class 2 Policy Validation Authority,O=\"ValiCert, Inc.\",L=ValiCert Validation Network
"2.16.840.1.114413.1.7.23.3",
"Go Daddy EV OID a",
SEC_OID_UNKNOWN,
"31:7A:2A:D0:7F:2B:33:5E:F5:A1:C3:4E:4B:57:E8:B7:D8:F1:FC:A6",
"MIG7MSQwIgYDVQQHExtWYWxpQ2VydCBWYWxpZGF0aW9uIE5ldHdvcmsxFzAVBgNV"
"BAoTDlZhbGlDZXJ0LCBJbmMuMTUwMwYDVQQLEyxWYWxpQ2VydCBDbGFzcyAyIFBv"
"bGljeSBWYWxpZGF0aW9uIEF1dGhvcml0eTEhMB8GA1UEAxMYaHR0cDovL3d3dy52"
"YWxpY2VydC5jb20vMSAwHgYJKoZIhvcNAQkBFhFpbmZvQHZhbGljZXJ0LmNvbQ==",
"AQ==",
nullptr
},
{
// E=info@valicert.com,CN=http://www.valicert.com/,OU=ValiCert Class 2 Policy Validation Authority,O=\"ValiCert, Inc.\",L=ValiCert Validation Network
"2.16.840.1.114414.1.7.23.3",
"Go Daddy EV OID b",
SEC_OID_UNKNOWN,
"31:7A:2A:D0:7F:2B:33:5E:F5:A1:C3:4E:4B:57:E8:B7:D8:F1:FC:A6",
"MIG7MSQwIgYDVQQHExtWYWxpQ2VydCBWYWxpZGF0aW9uIE5ldHdvcmsxFzAVBgNV"
"BAoTDlZhbGlDZXJ0LCBJbmMuMTUwMwYDVQQLEyxWYWxpQ2VydCBDbGFzcyAyIFBv"
"bGljeSBWYWxpZGF0aW9uIEF1dGhvcml0eTEhMB8GA1UEAxMYaHR0cDovL3d3dy52"
"YWxpY2VydC5jb20vMSAwHgYJKoZIhvcNAQkBFhFpbmZvQHZhbGljZXJ0LmNvbQ==",
"AQ==",
nullptr
},
{
// OU=Starfield Class 2 Certification Authority,O=\"Starfield Technologies, Inc.\",C=US
"2.16.840.1.114414.1.7.23.3",
"Go Daddy EV OID b",
SEC_OID_UNKNOWN,
"AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A",
"MGgxCzAJBgNVBAYTAlVTMSUwIwYDVQQKExxTdGFyZmllbGQgVGVjaG5vbG9naWVz"
"LCBJbmMuMTIwMAYDVQQLEylTdGFyZmllbGQgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9u"
"IEF1dGhvcml0eQ==",
"AA==",
nullptr
},
{
// CN=Starfield Root Certificate Authority - G2,O="Starfield Technologies, Inc.",L=Scottsdale,ST=Arizona,C=US
"2.16.840.1.114414.1.7.23.3",
"Go Daddy EV OID b",
SEC_OID_UNKNOWN,
"B5:1C:06:7C:EE:2B:0C:3D:F8:55:AB:2D:92:F4:FE:39:D4:E7:0F:0E",
"MIGPMQswCQYDVQQGEwJVUzEQMA4GA1UECBMHQXJpem9uYTETMBEGA1UEBxMKU2Nv"
"dHRzZGFsZTElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEy"
"MDAGA1UEAxMpU3RhcmZpZWxkIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IC0g"
"RzI=",
"AA==",
nullptr
},
{
// CN=DigiCert High Assurance EV Root CA,OU=www.digicert.com,O=DigiCert Inc,C=US
"2.16.840.1.114412.2.1",
"DigiCert EV OID",
SEC_OID_UNKNOWN,
"5F:B7:EE:06:33:E2:59:DB:AD:0C:4C:9A:E6:D3:8F:1A:61:C7:DC:25",
"MGwxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsT"
"EHd3dy5kaWdpY2VydC5jb20xKzApBgNVBAMTIkRpZ2lDZXJ0IEhpZ2ggQXNzdXJh"
"bmNlIEVWIFJvb3QgQ0E=",
"AqxcJmoLQJuPC3nyrkYldw==",
nullptr
},
{
// CN=QuoVadis Root CA 2,O=QuoVadis Limited,C=BM
"1.3.6.1.4.1.8024.0.2.100.1.2",
"Quo Vadis EV OID",
SEC_OID_UNKNOWN,
"CA:3A:FB:CF:12:40:36:4B:44:B2:16:20:88:80:48:39:19:93:7C:F7",
"MEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYD"
"VQQDExJRdW9WYWRpcyBSb290IENBIDI=",
"BQk=",
nullptr
},
{
// CN=Network Solutions Certificate Authority,O=Network Solutions L.L.C.,C=US
"1.3.6.1.4.1.782.1.2.1.8.1",
"Network Solutions EV OID",
SEC_OID_UNKNOWN,
"74:F8:A3:C3:EF:E7:B3:90:06:4B:83:90:3C:21:64:60:20:E5:DF:CE",
"MGIxCzAJBgNVBAYTAlVTMSEwHwYDVQQKExhOZXR3b3JrIFNvbHV0aW9ucyBMLkwu"
"Qy4xMDAuBgNVBAMTJ05ldHdvcmsgU29sdXRpb25zIENlcnRpZmljYXRlIEF1dGhv"
"cml0eQ==",
"V8szb8JcFuZHFhfjkDFo4A==",
nullptr
},
{
// CN=Entrust Root Certification Authority,OU="(c) 2006 Entrust, Inc.",OU=www.entrust.net/CPS is incorporated by reference,O="Entrust, Inc.",C=US
"2.16.840.1.114028.10.1.2",
"Entrust EV OID",
SEC_OID_UNKNOWN,
"B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9",
"MIGwMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNRW50cnVzdCwgSW5jLjE5MDcGA1UE"
"CxMwd3d3LmVudHJ1c3QubmV0L0NQUyBpcyBpbmNvcnBvcmF0ZWQgYnkgcmVmZXJl"
"bmNlMR8wHQYDVQQLExYoYykgMjAwNiBFbnRydXN0LCBJbmMuMS0wKwYDVQQDEyRF"
"bnRydXN0IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHk=",
"RWtQVA==",
nullptr
},
{
// CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE
"1.3.6.1.4.1.4146.1.1",
"GlobalSign EV OID",
SEC_OID_UNKNOWN,
"B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C",
"MFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYD"
"VQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxTaWduIFJvb3QgQ0E=",
"BAAAAAABFUtaw5Q=",
nullptr
},
{
// CN=GlobalSign,O=GlobalSign,OU=GlobalSign Root CA - R2
"1.3.6.1.4.1.4146.1.1",
"GlobalSign EV OID",
SEC_OID_UNKNOWN,
"75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE",
"MEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFIyMRMwEQYDVQQKEwpH"
"bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu",
"BAAAAAABD4Ym5g0=",
nullptr
},
{
// CN=GlobalSign,O=GlobalSign,OU=GlobalSign Root CA - R3
"1.3.6.1.4.1.4146.1.1",
"GlobalSign EV OID",
SEC_OID_UNKNOWN,
"D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD",
"MEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFIzMRMwEQYDVQQKEwpH"
"bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu",
"BAAAAAABIVhTCKI=",
nullptr
},
{
// CN=Buypass Class 3 CA 1,O=Buypass AS-983163327,C=NO
"2.16.578.1.26.1.3.3",
"Buypass Class 3 CA 1",
SEC_OID_UNKNOWN,
"61:57:3A:11:DF:0E:D8:7E:D5:92:65:22:EA:D0:56:D7:44:B3:23:71",
"MEsxCzAJBgNVBAYTAk5PMR0wGwYDVQQKDBRCdXlwYXNzIEFTLTk4MzE2MzMyNzEd"
"MBsGA1UEAwwUQnV5cGFzcyBDbGFzcyAzIENBIDE=",
"Ag==",
nullptr
},
{
// CN=Class 2 Primary CA,O=Certplus,C=FR
"1.3.6.1.4.1.22234.2.5.2.3.1",
"Certplus EV OID",
SEC_OID_UNKNOWN,
"74:20:74:41:72:9C:DD:92:EC:79:31:D8:23:10:8D:C2:81:92:E2:BB",
"MD0xCzAJBgNVBAYTAkZSMREwDwYDVQQKEwhDZXJ0cGx1czEbMBkGA1UEAxMSQ2xh"
"c3MgMiBQcmltYXJ5IENB",
"AIW9S/PY2uNp9pTXX8OlRCM=",
nullptr
},
{
// CN=Chambers of Commerce Root - 2008,O=AC Camerfirma S.A.,serialNumber=A82743287,L=Madrid (see current address at www.camerfirma.com/address),C=EU
"1.3.6.1.4.1.17326.10.14.2.1.2",
"Camerfirma EV OID a",
SEC_OID_UNKNOWN,
"78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C",
"MIGuMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBh"
"ZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ"
"QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xKTAnBgNVBAMT"
"IENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4",
"AKPaQn6ksa7a",
nullptr
},
{
// CN=Global Chambersign Root - 2008,O=AC Camerfirma S.A.,serialNumber=A82743287,L=Madrid (see current address at www.camerfirma.com/address),C=EU
"1.3.6.1.4.1.17326.10.8.12.1.2",
"Camerfirma EV OID b",
SEC_OID_UNKNOWN,
"4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C",
"MIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBh"
"ZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ"
"QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMT"
"Hkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwOA==",
"AMnN0+nVfSPO",
nullptr
},
{
// CN=TC TrustCenter Universal CA III,OU=TC TrustCenter Universal CA,O=TC TrustCenter GmbH,C=DE
"1.2.276.0.44.1.1.1.4",
"TC TrustCenter EV OID",
SEC_OID_UNKNOWN,
"96:56:CD:7B:57:96:98:95:D0:E1:41:46:68:06:FB:B8:C6:11:06:87",
"MHsxCzAJBgNVBAYTAkRFMRwwGgYDVQQKExNUQyBUcnVzdENlbnRlciBHbWJIMSQw"
"IgYDVQQLExtUQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0ExKDAmBgNVBAMTH1RD"
"IFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQSBJSUk=",
"YyUAAQACFI0zFQLkbPQ=",
nullptr
},
{
// CN=AffirmTrust Commercial,O=AffirmTrust,C=US
"1.3.6.1.4.1.34697.2.1",
"AffirmTrust EV OID a",
SEC_OID_UNKNOWN,
"F9:B5:B6:32:45:5F:9C:BE:EC:57:5F:80:DC:E9:6E:2C:C7:B2:78:B7",
"MEQxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEfMB0GA1UEAwwW"
"QWZmaXJtVHJ1c3QgQ29tbWVyY2lhbA==",
"d3cGJyapsXw=",
nullptr
},
{
// CN=AffirmTrust Networking,O=AffirmTrust,C=US
"1.3.6.1.4.1.34697.2.2",
"AffirmTrust EV OID b",
SEC_OID_UNKNOWN,
"29:36:21:02:8B:20:ED:02:F5:66:C5:32:D1:D6:ED:90:9F:45:00:2F",
"MEQxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEfMB0GA1UEAwwW"
"QWZmaXJtVHJ1c3QgTmV0d29ya2luZw==",
"fE8EORzUmS0=",
nullptr
},
{
// CN=AffirmTrust Premium,O=AffirmTrust,C=US
"1.3.6.1.4.1.34697.2.3",
"AffirmTrust EV OID c",
SEC_OID_UNKNOWN,
"D8:A6:33:2C:E0:03:6F:B1:85:F6:63:4F:7D:6A:06:65:26:32:28:27",
"MEExCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEcMBoGA1UEAwwT"
"QWZmaXJtVHJ1c3QgUHJlbWl1bQ==",
"bYwURrGmCu4=",
nullptr
},
{
// CN=AffirmTrust Premium ECC,O=AffirmTrust,C=US
"1.3.6.1.4.1.34697.2.4",
"AffirmTrust EV OID d",
SEC_OID_UNKNOWN,
"B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB",
"MEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwX"
"QWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0M=",
"dJclisc/elQ=",
nullptr
},
{
// CN=Certum Trusted Network CA,OU=Certum Certification Authority,O=Unizeto Technologies S.A.,C=PL
"1.2.616.1.113527.2.5.1.1",
"Certum EV OID",
SEC_OID_UNKNOWN,
"07:E0:32:E0:20:B7:2C:3F:19:2F:06:28:A2:59:3A:19:A7:0F:06:9E",
"MH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBT"
"LkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAg"
"BgNVBAMTGUNlcnR1bSBUcnVzdGVkIE5ldHdvcmsgQ0E=",
"BETA",
nullptr
},
{
// CN=Izenpe.com,O=IZENPE S.A.,C=ES
"1.3.6.1.4.1.14777.6.1.1",
"Izenpe EV OID 1",
SEC_OID_UNKNOWN,
"2F:78:3D:25:52:18:A7:4A:65:39:71:B5:2C:A2:9C:45:15:6F:E9:19",
"MDgxCzAJBgNVBAYTAkVTMRQwEgYDVQQKDAtJWkVOUEUgUy5BLjETMBEGA1UEAwwK"
"SXplbnBlLmNvbQ==",
"ALC3WhZIX7/hy/WL1xnmfQ==",
nullptr
},
{
// CN=Izenpe.com,O=IZENPE S.A.,C=ES
"1.3.6.1.4.1.14777.6.1.2",
"Izenpe EV OID 2",
SEC_OID_UNKNOWN,
"2F:78:3D:25:52:18:A7:4A:65:39:71:B5:2C:A2:9C:45:15:6F:E9:19",
"MDgxCzAJBgNVBAYTAkVTMRQwEgYDVQQKDAtJWkVOUEUgUy5BLjETMBEGA1UEAwwK"
"SXplbnBlLmNvbQ==",
"ALC3WhZIX7/hy/WL1xnmfQ==",
nullptr
},
{
// CN=A-Trust-nQual-03,OU=A-Trust-nQual-03,O=A-Trust Ges. f. Sicherheitssysteme im elektr. Datenverkehr GmbH,C=AT
"1.2.40.0.17.1.22",
"A-Trust EV OID",
SEC_OID_UNKNOWN,
"D3:C0:63:F2:19:ED:07:3E:34:AD:5D:75:0B:32:76:29:FF:D5:9A:F2",
"MIGNMQswCQYDVQQGEwJBVDFIMEYGA1UECgw/QS1UcnVzdCBHZXMuIGYuIFNpY2hl"
"cmhlaXRzc3lzdGVtZSBpbSBlbGVrdHIuIERhdGVudmVya2VociBHbWJIMRkwFwYD"
"VQQLDBBBLVRydXN0LW5RdWFsLTAzMRkwFwYDVQQDDBBBLVRydXN0LW5RdWFsLTAz",
"AWwe",
nullptr
},
{
// OU=Sample Certification Authority,O=\"Sample, Inc.\",C=US
"0.0.0.0",
0, // for real entries use a string like "Sample INVALID EV OID"
SEC_OID_UNKNOWN,
"00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33", //UPPERCASE!
"Cg==",
"Cg==",
nullptr
}
};
static SECOidTag
register_oid(const SECItem *oid_item, const char *oid_name)
{
if (!oid_item)
return SEC_OID_UNKNOWN;
SECOidData od;
od.oid.len = oid_item->len;
od.oid.data = oid_item->data;
od.offset = SEC_OID_UNKNOWN;
od.desc = oid_name;
od.mechanism = CKM_INVALID_MECHANISM;
od.supportedExtension = INVALID_CERT_EXTENSION;
return SECOID_AddEntry(&od);
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
class nsMyTrustedEVInfoClass : public nsMyTrustedEVInfo
{
public:
nsMyTrustedEVInfoClass();
~nsMyTrustedEVInfoClass();
};
nsMyTrustedEVInfoClass::nsMyTrustedEVInfoClass()
{
dotted_oid = nullptr;
oid_name = nullptr;
oid_tag = SEC_OID_UNKNOWN;
ev_root_sha1_fingerprint = nullptr;
issuer_base64 = nullptr;
serial_base64 = nullptr;
cert = nullptr;
}
nsMyTrustedEVInfoClass::~nsMyTrustedEVInfoClass()
{
// Cast away const-ness in order to free these strings
free(const_cast<char*>(dotted_oid));
free(const_cast<char*>(oid_name));
free(const_cast<char*>(ev_root_sha1_fingerprint));
free(const_cast<char*>(issuer_base64));
free(const_cast<char*>(serial_base64));
if (cert)
CERT_DestroyCertificate(cert);
}
typedef nsTArray< nsMyTrustedEVInfoClass* > testEVArray;
static testEVArray *testEVInfos;
static bool testEVInfosLoaded = false;
#endif
static bool isEVMatch(SECOidTag policyOIDTag,
CERTCertificate *rootCert,
const nsMyTrustedEVInfo &info)
{
if (!rootCert)
return false;
NS_ConvertASCIItoUTF16 info_sha1(info.ev_root_sha1_fingerprint);
nsNSSCertificate c(rootCert);
nsAutoString fingerprint;
if (NS_FAILED(c.GetSha1Fingerprint(fingerprint)))
return false;
if (fingerprint != info_sha1)
return false;
return (policyOIDTag == info.oid_tag);
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
static const char kTestEVRootsFileName[] = "test_ev_roots.txt";
static void
loadTestEVInfos()
{
if (!testEVInfos)
return;
testEVInfos->Clear();
char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
if (!env_val)
return;
int enabled_val = atoi(env_val);
if (!enabled_val)
return;
nsCOMPtr<nsIFile> aFile;
NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(aFile));
if (!aFile)
return;
aFile->AppendNative(NS_LITERAL_CSTRING(kTestEVRootsFileName));
nsresult rv;
nsCOMPtr<nsIInputStream> fileInputStream;
rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), aFile);
if (NS_FAILED(rv))
return;
nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(fileInputStream, &rv);
if (NS_FAILED(rv))
return;
nsAutoCString buffer;
bool isMore = true;
/* file format
*
* file format must be strictly followed
* strings in file must be UTF-8
* each record consists of multiple lines
* each line consists of a descriptor, a single space, and the data
* the descriptors are:
* 1_fingerprint (in format XX:XX:XX:...)
* 2_readable_oid (treated as a comment)
* the input file must strictly follow this order
* the input file may contain 0, 1 or many records
* completely empty lines are ignored
* lines that start with the # char are ignored
*/
int line_counter = 0;
bool found_error = false;
enum {
pos_fingerprint, pos_readable_oid, pos_issuer, pos_serial
} reader_position = pos_fingerprint;
nsCString fingerprint, readable_oid, issuer, serial;
while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
++line_counter;
if (buffer.IsEmpty() || buffer.First() == '#') {
continue;
}
int32_t seperatorIndex = buffer.FindChar(' ', 0);
if (seperatorIndex == 0) {
found_error = true;
break;
}
const nsASingleFragmentCString &descriptor = Substring(buffer, 0, seperatorIndex);
const nsASingleFragmentCString &data =
Substring(buffer, seperatorIndex + 1,
buffer.Length() - seperatorIndex + 1);
if (reader_position == pos_fingerprint &&
descriptor.EqualsLiteral(("1_fingerprint"))) {
fingerprint = data;
reader_position = pos_readable_oid;
continue;
}
else if (reader_position == pos_readable_oid &&
descriptor.EqualsLiteral(("2_readable_oid"))) {
readable_oid = data;
reader_position = pos_issuer;
continue;
}
else if (reader_position == pos_issuer &&
descriptor.EqualsLiteral(("3_issuer"))) {
issuer = data;
reader_position = pos_serial;
continue;
}
else if (reader_position == pos_serial &&
descriptor.EqualsLiteral(("4_serial"))) {
serial = data;
reader_position = pos_fingerprint;
}
else {
found_error = true;
break;
}
nsMyTrustedEVInfoClass *temp_ev = new nsMyTrustedEVInfoClass;
if (!temp_ev)
return;
temp_ev->ev_root_sha1_fingerprint = strdup(fingerprint.get());
temp_ev->oid_name = strdup(readable_oid.get());
temp_ev->dotted_oid = strdup(readable_oid.get());
temp_ev->issuer_base64 = strdup(issuer.get());
temp_ev->serial_base64 = strdup(serial.get());
SECStatus rv;
CERTIssuerAndSN ias;
rv = ATOB_ConvertAsciiToItem(&ias.derIssuer, const_cast<char*>(temp_ev->issuer_base64));
NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");
rv = ATOB_ConvertAsciiToItem(&ias.serialNumber, const_cast<char*>(temp_ev->serial_base64));
NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");
temp_ev->cert = CERT_FindCertByIssuerAndSN(nullptr, &ias);
NS_ASSERTION(temp_ev->cert, "Could not find EV root in NSS storage");
SECITEM_FreeItem(&ias.derIssuer, false);
SECITEM_FreeItem(&ias.serialNumber, false);
if (!temp_ev->cert)
return;
nsNSSCertificate c(temp_ev->cert);
nsAutoString fingerprint;
c.GetSha1Fingerprint(fingerprint);
NS_ConvertASCIItoUTF16 sha1(temp_ev->ev_root_sha1_fingerprint);
if (sha1 != fingerprint) {
NS_ASSERTION(sha1 == fingerprint, "found EV root with unexpected SHA1 mismatch");
CERT_DestroyCertificate(temp_ev->cert);
temp_ev->cert = nullptr;
return;
}
SECItem ev_oid_item;
ev_oid_item.data = nullptr;
ev_oid_item.len = 0;
SECStatus srv = SEC_StringToOID(nullptr, &ev_oid_item,
readable_oid.get(), readable_oid.Length());
if (srv != SECSuccess) {
delete temp_ev;
found_error = true;
break;
}
temp_ev->oid_tag = register_oid(&ev_oid_item, temp_ev->oid_name);
SECITEM_FreeItem(&ev_oid_item, false);
testEVInfos->AppendElement(temp_ev);
}
if (found_error) {
fprintf(stderr, "invalid line %d in test_ev_roots file\n", line_counter);
}
}
static bool
isEVPolicyInExternalDebugRootsFile(SECOidTag policyOIDTag)
{
if (!testEVInfos)
return false;
char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
if (!env_val)
return false;
int enabled_val = atoi(env_val);
if (!enabled_val)
return false;
for (size_t i=0; i<testEVInfos->Length(); ++i) {
nsMyTrustedEVInfoClass *ev = testEVInfos->ElementAt(i);
if (!ev)
continue;
if (policyOIDTag == ev->oid_tag)
return true;
}
return false;
}
static bool
getRootsForOidFromExternalRootsFile(CERTCertList* certList,
SECOidTag policyOIDTag)
{
if (!testEVInfos)
return false;
char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
if (!env_val)
return false;
int enabled_val = atoi(env_val);
if (!enabled_val)
return false;
for (size_t i=0; i<testEVInfos->Length(); ++i) {
nsMyTrustedEVInfoClass *ev = testEVInfos->ElementAt(i);
if (!ev)
continue;
if (policyOIDTag == ev->oid_tag)
CERT_AddCertToListTail(certList, CERT_DupCertificate(ev->cert));
}
return false;
}
static bool
isEVMatchInExternalDebugRootsFile(SECOidTag policyOIDTag,
CERTCertificate *rootCert)
{
if (!testEVInfos)
return false;
if (!rootCert)
return false;
char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
if (!env_val)
return false;
int enabled_val = atoi(env_val);
if (!enabled_val)
return false;
for (size_t i=0; i<testEVInfos->Length(); ++i) {
nsMyTrustedEVInfoClass *ev = testEVInfos->ElementAt(i);
if (!ev)
continue;
if (isEVMatch(policyOIDTag, rootCert, *ev))
return true;
}
return false;
}
#endif
static bool
isEVPolicy(SECOidTag policyOIDTag)
{
for (size_t iEV=0; iEV < (sizeof(myTrustedEVInfos)/sizeof(nsMyTrustedEVInfo)); ++iEV) {
nsMyTrustedEVInfo &entry = myTrustedEVInfos[iEV];
if (!entry.oid_name) // invalid or placeholder list entry
continue;
if (policyOIDTag == entry.oid_tag) {
return true;
}
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
if (isEVPolicyInExternalDebugRootsFile(policyOIDTag)) {
return true;
}
#endif
return false;
}
static CERTCertList*
getRootsForOid(SECOidTag oid_tag)
{
CERTCertList *certList = CERT_NewCertList();
if (!certList)
return nullptr;
for (size_t iEV=0; iEV < (sizeof(myTrustedEVInfos)/sizeof(nsMyTrustedEVInfo)); ++iEV) {
nsMyTrustedEVInfo &entry = myTrustedEVInfos[iEV];
if (!entry.oid_name) // invalid or placeholder list entry
continue;
if (entry.oid_tag == oid_tag)
CERT_AddCertToListTail(certList, CERT_DupCertificate(entry.cert));
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
getRootsForOidFromExternalRootsFile(certList, oid_tag);
#endif
return certList;
}
static bool
isApprovedForEV(SECOidTag policyOIDTag, CERTCertificate *rootCert)
{
if (!rootCert)
return false;
for (size_t iEV=0; iEV < (sizeof(myTrustedEVInfos)/sizeof(nsMyTrustedEVInfo)); ++iEV) {
nsMyTrustedEVInfo &entry = myTrustedEVInfos[iEV];
if (!entry.oid_name) // invalid or placeholder list entry
continue;
if (isEVMatch(policyOIDTag, rootCert, entry)) {
return true;
}
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
if (isEVMatchInExternalDebugRootsFile(policyOIDTag, rootCert)) {
return true;
}
#endif
return false;
}
PRStatus
nsNSSComponent::IdentityInfoInit()
{
for (size_t iEV=0; iEV < (sizeof(myTrustedEVInfos)/sizeof(nsMyTrustedEVInfo)); ++iEV) {
nsMyTrustedEVInfo &entry = myTrustedEVInfos[iEV];
if (!entry.oid_name) // invalid or placeholder list entry
continue;
SECStatus rv;
CERTIssuerAndSN ias;
rv = ATOB_ConvertAsciiToItem(&ias.derIssuer, const_cast<char*>(entry.issuer_base64));
NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");
rv = ATOB_ConvertAsciiToItem(&ias.serialNumber, const_cast<char*>(entry.serial_base64));
NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");
ias.serialNumber.type = siUnsignedInteger;
entry.cert = CERT_FindCertByIssuerAndSN(nullptr, &ias);
NS_ASSERTION(entry.cert, "Could not find EV root in NSS storage");
SECITEM_FreeItem(&ias.derIssuer, false);
SECITEM_FreeItem(&ias.serialNumber, false);
if (!entry.cert)
continue;
nsNSSCertificate c(entry.cert);
nsAutoString fingerprint;
c.GetSha1Fingerprint(fingerprint);
NS_ConvertASCIItoUTF16 sha1(entry.ev_root_sha1_fingerprint);
if (sha1 != fingerprint) {
NS_ASSERTION(sha1 == fingerprint, "found EV root with unexpected SHA1 mismatch");
CERT_DestroyCertificate(entry.cert);
entry.cert = nullptr;
continue;
}
SECItem ev_oid_item;
ev_oid_item.data = nullptr;
ev_oid_item.len = 0;
SECStatus srv = SEC_StringToOID(nullptr, &ev_oid_item,
entry.dotted_oid, 0);
if (srv != SECSuccess)
continue;
entry.oid_tag = register_oid(&ev_oid_item, entry.oid_name);
SECITEM_FreeItem(&ev_oid_item, false);
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
if (!testEVInfosLoaded) {
testEVInfosLoaded = true;
testEVInfos = new testEVArray;
if (testEVInfos) {
loadTestEVInfos();
}
}
#endif
return PR_SUCCESS;
}
// Find the first policy OID that is known to be an EV policy OID.
static SECStatus getFirstEVPolicy(CERTCertificate *cert, SECOidTag &outOidTag)
{
if (!cert)
return SECFailure;
if (cert->extensions) {
for (int i=0; cert->extensions[i] != nullptr; i++) {
const SECItem *oid = &cert->extensions[i]->id;
SECOidTag oidTag = SECOID_FindOIDTag(oid);
if (oidTag != SEC_OID_X509_CERTIFICATE_POLICIES)
continue;
SECItem *value = &cert->extensions[i]->value;
CERTCertificatePolicies *policies;
CERTPolicyInfo **policyInfos, *policyInfo;
policies = CERT_DecodeCertificatePoliciesExtension(value);
if (!policies)
continue;
policyInfos = policies->policyInfos;
bool found = false;
while (*policyInfos != NULL) {
policyInfo = *policyInfos++;
SECOidTag oid_tag = policyInfo->oid;
if (oid_tag != SEC_OID_UNKNOWN && isEVPolicy(oid_tag)) {
// in our list of OIDs accepted for EV
outOidTag = oid_tag;
found = true;
break;
}
}
CERT_DestroyCertificatePoliciesExtension(policies);
if (found)
return SECSuccess;
}
}
return SECFailure;
}
#endif
NS_IMETHODIMP
nsSSLStatus::GetIsExtendedValidation(bool* aIsEV)
{
NS_ENSURE_ARG_POINTER(aIsEV);
*aIsEV = false;
#ifdef NSS_NO_LIBPKIX
return NS_OK;
#else
nsCOMPtr<nsIX509Cert> cert = mServerCert;
nsresult rv;
nsCOMPtr<nsIIdentityInfo> idinfo = do_QueryInterface(cert, &rv);
// mServerCert should never be null when this method is called because
// nsSSLStatus objects always have mServerCert set right after they are
// constructed and before they are returned. GetIsExtendedValidation should
// only be called in the chrome process (in e10s), and mServerCert will always
// implement nsIIdentityInfo in the chrome process.
if (!idinfo) {
NS_ERROR("nsSSLStatus has null mServerCert or was called in the content "
"process");
return NS_ERROR_UNEXPECTED;
}
// Never allow bad certs for EV, regardless of overrides.
if (mHaveCertErrorBits)
return NS_OK;
return idinfo->GetIsExtendedValidation(aIsEV);
#endif
}
#ifndef NSS_NO_LIBPKIX
nsresult
nsNSSCertificate::hasValidEVOidTag(SECOidTag &resultOidTag, bool &validEV)
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown())
return NS_ERROR_NOT_AVAILABLE;
nsresult nrv;
nsCOMPtr<nsINSSComponent> nssComponent =
do_GetService(PSM_COMPONENT_CONTRACTID, &nrv);
if (NS_FAILED(nrv))
return nrv;
nssComponent->EnsureIdentityInfoLoaded();
validEV = false;
resultOidTag = SEC_OID_UNKNOWN;
bool isOCSPEnabled = false;
nsCOMPtr<nsIX509CertDB> certdb;
certdb = do_GetService(NS_X509CERTDB_CONTRACTID);
if (certdb)
certdb->GetIsOcspOn(&isOCSPEnabled);
// No OCSP, no EV
if (!isOCSPEnabled)
return NS_OK;
SECOidTag oid_tag;
SECStatus rv = getFirstEVPolicy(mCert, oid_tag);
if (rv != SECSuccess)
return NS_OK;
if (oid_tag == SEC_OID_UNKNOWN) // not in our list of OIDs accepted for EV
return NS_OK;
CERTCertList *rootList = getRootsForOid(oid_tag);
CERTCertListCleaner rootListCleaner(rootList);
CERTRevocationMethodIndex preferedRevMethods[1] = {
cert_revocation_method_ocsp
};
uint64_t revMethodFlags =
CERT_REV_M_TEST_USING_THIS_METHOD
| CERT_REV_M_ALLOW_NETWORK_FETCHING
| CERT_REV_M_ALLOW_IMPLICIT_DEFAULT_SOURCE
| CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE
| CERT_REV_M_IGNORE_MISSING_FRESH_INFO
| CERT_REV_M_STOP_TESTING_ON_FRESH_INFO;
uint64_t revMethodIndependentFlags =
CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST
| CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
// We need a PRUint64 here instead of a nice int64_t (until bug 634793 is
// fixed) to match the type used in security/nss/lib/certdb/certt.h for
// cert_rev_flags_per_method.
PRUint64 methodFlags[2];
methodFlags[cert_revocation_method_crl] = revMethodFlags;
methodFlags[cert_revocation_method_ocsp] = revMethodFlags;
CERTRevocationFlags rev;
rev.leafTests.number_of_defined_methods = cert_revocation_method_ocsp +1;
rev.leafTests.cert_rev_flags_per_method = methodFlags;
rev.leafTests.number_of_preferred_methods = 1;
rev.leafTests.preferred_methods = preferedRevMethods;
rev.leafTests.cert_rev_method_independent_flags =
revMethodIndependentFlags;
rev.chainTests.number_of_defined_methods = cert_revocation_method_ocsp +1;
rev.chainTests.cert_rev_flags_per_method = methodFlags;
rev.chainTests.number_of_preferred_methods = 1;
rev.chainTests.preferred_methods = preferedRevMethods;
rev.chainTests.cert_rev_method_independent_flags =
revMethodIndependentFlags;
CERTValInParam cvin[4];
cvin[0].type = cert_pi_policyOID;
cvin[0].value.arraySize = 1;
cvin[0].value.array.oids = &oid_tag;
cvin[1].type = cert_pi_revocationFlags;
cvin[1].value.pointer.revocation = &rev;
cvin[2].type = cert_pi_trustAnchors;
cvin[2].value.pointer.chain = rootList;
cvin[3].type = cert_pi_end;
CERTValOutParam cvout[2];
cvout[0].type = cert_po_trustAnchor;
cvout[0].value.pointer.cert = nullptr;
cvout[1].type = cert_po_end;
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("calling CERT_PKIXVerifyCert nss cert %p\n", mCert));
rv = CERT_PKIXVerifyCert(mCert, certificateUsageSSLServer,
cvin, cvout, nullptr);
if (rv != SECSuccess)
return NS_OK;
CERTCertificate *issuerCert = cvout[0].value.pointer.cert;
CERTCertificateCleaner issuerCleaner(issuerCert);
#ifdef PR_LOGGING
if (PR_LOG_TEST(gPIPNSSLog, PR_LOG_DEBUG)) {
nsNSSCertificate ic(issuerCert);
nsAutoString fingerprint;
ic.GetSha1Fingerprint(fingerprint);
NS_LossyConvertUTF16toASCII fpa(fingerprint);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CERT_PKIXVerifyCert returned success, issuer: %s, SHA1: %s\n",
issuerCert->subjectName, fpa.get()));
}
#endif
validEV = isApprovedForEV(oid_tag, issuerCert);
if (validEV)
resultOidTag = oid_tag;
return NS_OK;
}
nsresult
nsNSSCertificate::getValidEVOidTag(SECOidTag &resultOidTag, bool &validEV)
{
if (mCachedEVStatus != ev_status_unknown) {
validEV = (mCachedEVStatus == ev_status_valid);
if (validEV)
resultOidTag = mCachedEVOidTag;
return NS_OK;
}
nsresult rv = hasValidEVOidTag(resultOidTag, validEV);
if (NS_SUCCEEDED(rv)) {
if (validEV) {
mCachedEVOidTag = resultOidTag;
}
mCachedEVStatus = validEV ? ev_status_valid : ev_status_invalid;
}
return rv;
}
#endif // NSS_NO_LIBPKIX
NS_IMETHODIMP
nsNSSCertificate::GetIsExtendedValidation(bool* aIsEV)
{
#ifdef NSS_NO_LIBPKIX
*aIsEV = false;
return NS_OK;
#else
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown())
return NS_ERROR_NOT_AVAILABLE;
NS_ENSURE_ARG(aIsEV);
*aIsEV = false;
if (mCachedEVStatus != ev_status_unknown) {
*aIsEV = (mCachedEVStatus == ev_status_valid);
return NS_OK;
}
SECOidTag oid_tag;
return getValidEVOidTag(oid_tag, *aIsEV);
#endif
}
NS_IMETHODIMP
nsNSSCertificate::GetValidEVPolicyOid(nsACString &outDottedOid)
{
outDottedOid.Truncate();
#ifndef NSS_NO_LIBPKIX
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown())
return NS_ERROR_NOT_AVAILABLE;
SECOidTag oid_tag;
bool valid;
nsresult rv = getValidEVOidTag(oid_tag, valid);
if (NS_FAILED(rv))
return rv;
if (valid) {
SECOidData *oid_data = SECOID_FindOIDByTag(oid_tag);
if (!oid_data)
return NS_ERROR_FAILURE;
char *oid_str = CERT_GetOidString(&oid_data->oid);
if (!oid_str)
return NS_ERROR_FAILURE;
outDottedOid = oid_str;
PR_smprintf_free(oid_str);
}
#endif
return NS_OK;
}
#ifndef NSS_NO_LIBPKIX
NS_IMETHODIMP
nsNSSComponent::EnsureIdentityInfoLoaded()
{
PRStatus rv = PR_CallOnce(&mIdentityInfoCallOnce, IdentityInfoInit);
return (rv == PR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE;
}
// only called during shutdown
void
nsNSSComponent::CleanupIdentityInfo()
{
nsNSSShutDownPreventionLock locker;
for (size_t iEV=0; iEV < (sizeof(myTrustedEVInfos)/sizeof(nsMyTrustedEVInfo)); ++iEV) {
nsMyTrustedEVInfo &entry = myTrustedEVInfos[iEV];
if (entry.cert) {
CERT_DestroyCertificate(entry.cert);
entry.cert = nullptr;
}
}
#ifdef PSM_ENABLE_TEST_EV_ROOTS
if (testEVInfosLoaded) {
testEVInfosLoaded = false;
if (testEVInfos) {
for (size_t i = 0; i<testEVInfos->Length(); ++i) {
delete testEVInfos->ElementAt(i);
}
testEVInfos->Clear();
delete testEVInfos;
testEVInfos = nullptr;
}
}
#endif
memset(&mIdentityInfoCallOnce, 0, sizeof(PRCallOnceType));
}
#endif
| 30.896047 | 175 | 0.709435 | [
"3d"
] |
aa62a39586b2f2adf0e81cb691e21ccf732796c6 | 814 | cpp | C++ | Leetcode - Top Interview Questions/(LEETCODE)_698_Partition_to_K_Equal_Sum_Subsets.cpp | kothariji/Competitive-Programming | c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c | [
"MIT"
] | 1 | 2020-08-27T06:59:52.000Z | 2020-08-27T06:59:52.000Z | Leetcode - Top Interview Questions/(LEETCODE)_698_Partition_to_K_Equal_Sum_Subsets.cpp | kothariji/Competitive-Programming | c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c | [
"MIT"
] | null | null | null | Leetcode - Top Interview Questions/(LEETCODE)_698_Partition_to_K_Equal_Sum_Subsets.cpp | kothariji/Competitive-Programming | c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c | [
"MIT"
] | null | null | null | class Solution {
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
int total = accumulate(nums.begin(), nums.end(), 0);
if (total % k) return false;
int avg = total / k;
vector<int> sm(k);
sort(nums.begin(), nums.end(), [&](auto& lhs, auto& rhs) {return lhs > rhs; });
function<bool(int)> fn = [&](int i) {
if (i == nums.size()) return true;
for (int kk = 0; kk < k; ++kk) {
if (sm[kk] + nums[i] <= avg) {
sm[kk] += nums[i];
if (fn(i+1)) return true;
sm[kk] -= nums[i];
}
if (sm[kk] == 0) break;
}
return false;
};
return fn(0);
}
};
| 30.148148 | 88 | 0.39312 | [
"vector"
] |
aa6430e7b7951c3bcc73ba3b32b2d08ddb8eb783 | 19,237 | cpp | C++ | utils/sqlite/statement.cpp | racktopsystems/kyua | 1929dccc5cda71cddda71485094822d3c3862902 | [
"BSD-3-Clause"
] | null | null | null | utils/sqlite/statement.cpp | racktopsystems/kyua | 1929dccc5cda71cddda71485094822d3c3862902 | [
"BSD-3-Clause"
] | null | null | null | utils/sqlite/statement.cpp | racktopsystems/kyua | 1929dccc5cda71cddda71485094822d3c3862902 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2011 The Kyua Authors.
// 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 Google Inc. 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 "utils/sqlite/statement.hpp"
extern "C" {
#include <sqlite3.h>
}
#include <map>
#include "utils/defs.hpp"
#include "utils/format/macros.hpp"
#include "utils/logging/macros.hpp"
#include "utils/noncopyable.hpp"
#include "utils/sanity.hpp"
#include "utils/sqlite/c_gate.hpp"
#include "utils/sqlite/database.hpp"
#include "utils/sqlite/exceptions.hpp"
namespace sqlite = utils::sqlite;
namespace {
static sqlite::type c_type_to_cxx(const int) UTILS_PURE;
/// Maps a SQLite 3 data type to our own representation.
///
/// \param original The native SQLite 3 data type.
///
/// \return Our internal representation for the native data type.
static sqlite::type
c_type_to_cxx(const int original)
{
switch (original) {
case SQLITE_BLOB: return sqlite::type_blob;
case SQLITE_FLOAT: return sqlite::type_float;
case SQLITE_INTEGER: return sqlite::type_integer;
case SQLITE_NULL: return sqlite::type_null;
case SQLITE_TEXT: return sqlite::type_text;
default: UNREACHABLE_MSG("Unknown data type returned by SQLite 3");
}
UNREACHABLE;
}
/// Handles the return value of a sqlite3_bind_* call.
///
/// \param db The database the call was made on.
/// \param api_function The name of the sqlite3_bind_* function called.
/// \param error The error code returned by the function; can be SQLITE_OK.
///
/// \throw std::bad_alloc If there was no memory for the binding.
/// \throw api_error If the binding fails for any other reason.
static void
handle_bind_error(sqlite::database& db, const char* api_function,
const int error)
{
switch (error) {
case SQLITE_OK:
return;
case SQLITE_RANGE:
UNREACHABLE_MSG("Invalid index for bind argument");
case SQLITE_NOMEM:
throw std::bad_alloc();
default:
throw sqlite::api_error::from_database(db, api_function);
}
}
} // anonymous namespace
/// Internal implementation for sqlite::statement.
struct utils::sqlite::statement::impl : utils::noncopyable {
/// The database this statement belongs to.
sqlite::database& db;
/// The SQLite 3 internal statement.
::sqlite3_stmt* stmt;
/// Cache for the column names in a statement; lazily initialized.
std::map< std::string, int > column_cache;
/// Constructor.
///
/// \param db_ The database this statement belongs to. Be aware that we
/// keep a *reference* to the database; in other words, if the database
/// vanishes, this object will become invalid. (It'd be trivial to keep
/// a shallow copy here instead, but I feel that statements that outlive
/// their database represents sloppy programming.)
/// \param stmt_ The SQLite internal statement.
impl(database& db_, ::sqlite3_stmt* stmt_) :
db(db_),
stmt(stmt_)
{
}
/// Destructor.
///
/// It is important to keep this as part of the 'impl' class instead of the
/// container class. The 'impl' class is destroyed exactly once (because it
/// is managed by a shared_ptr) and thus releasing the resources here is
/// OK. However, the container class is potentially released many times,
/// which means that we would be double-freeing the internal object and
/// reusing invalid data.
~impl(void)
{
(void)::sqlite3_finalize(stmt);
}
};
/// Initializes a statement object.
///
/// This is an internal function. Use database::create_statement() to
/// instantiate one of these objects.
///
/// \param db The database this statement belongs to.
/// \param raw_stmt A void pointer representing a SQLite native statement of
/// type sqlite3_stmt.
sqlite::statement::statement(database& db, void* raw_stmt) :
_pimpl(new impl(db, static_cast< ::sqlite3_stmt* >(raw_stmt)))
{
}
/// Destructor for the statement.
///
/// Remember that statements are reference-counted, so the statement will only
/// cease to be valid once its last copy is destroyed.
sqlite::statement::~statement(void)
{
}
/// Executes a statement that is not supposed to return any data.
///
/// Use this function to execute DDL and INSERT statements; i.e. statements that
/// only have one processing step and deliver no rows. This frees the caller
/// from having to deal with the return value of the step() function.
///
/// \pre The statement to execute will not produce any rows.
void
sqlite::statement::step_without_results(void)
{
const bool data = step();
INV_MSG(!data, "The statement should not have produced any rows, but it "
"did");
}
/// Performs a processing step on the statement.
///
/// \return True if the statement returned a row; false if the processing has
/// finished.
///
/// \throw api_error If the processing of the step raises an error.
bool
sqlite::statement::step(void)
{
const int error = ::sqlite3_step(_pimpl->stmt);
switch (error) {
case SQLITE_DONE:
LD("Step statement; no more rows");
return false;
case SQLITE_ROW:
LD("Step statement; row available for processing");
return true;
default:
throw api_error::from_database(_pimpl->db, "sqlite3_step");
}
UNREACHABLE;
}
/// Returns the number of columns in the step result.
///
/// \return The number of columns available for data retrieval.
int
sqlite::statement::column_count(void)
{
return ::sqlite3_column_count(_pimpl->stmt);
}
/// Returns the name of a particular column in the result.
///
/// \param index The column to request the name of.
///
/// \return The name of the requested column.
std::string
sqlite::statement::column_name(const int index)
{
const char* name = ::sqlite3_column_name(_pimpl->stmt, index);
if (name == NULL)
throw api_error::from_database(_pimpl->db, "sqlite3_column_name");
return name;
}
/// Returns the type of a particular column in the result.
///
/// \param index The column to request the type of.
///
/// \return The type of the requested column.
sqlite::type
sqlite::statement::column_type(const int index)
{
return c_type_to_cxx(::sqlite3_column_type(_pimpl->stmt, index));
}
/// Finds a column by name.
///
/// \param name The name of the column to search for.
///
/// \return The column identifier.
///
/// \throw value_error If the name cannot be found.
int
sqlite::statement::column_id(const char* name)
{
std::map< std::string, int >& cache = _pimpl->column_cache;
if (cache.empty()) {
for (int i = 0; i < column_count(); i++) {
const std::string aux_name = column_name(i);
INV(cache.find(aux_name) == cache.end());
cache[aux_name] = i;
}
}
const std::map< std::string, int >::const_iterator iter = cache.find(name);
if (iter == cache.end())
throw invalid_column_error(_pimpl->db.db_filename(), name);
else
return (*iter).second;
}
/// Returns a particular column in the result as a blob.
///
/// \param index The column to retrieve.
///
/// \return A block of memory with the blob contents. Note that the pointer
/// returned by this call will be invalidated on the next call to any SQLite API
/// function.
sqlite::blob
sqlite::statement::column_blob(const int index)
{
PRE(column_type(index) == type_blob);
return blob(::sqlite3_column_blob(_pimpl->stmt, index),
::sqlite3_column_bytes(_pimpl->stmt, index));
}
/// Returns a particular column in the result as a double.
///
/// \param index The column to retrieve.
///
/// \return The double value.
double
sqlite::statement::column_double(const int index)
{
PRE(column_type(index) == type_float);
return ::sqlite3_column_double(_pimpl->stmt, index);
}
/// Returns a particular column in the result as an integer.
///
/// \param index The column to retrieve.
///
/// \return The integer value. Note that the value may not fit in an integer
/// depending on the platform. Use column_int64 to retrieve the integer without
/// truncation.
int
sqlite::statement::column_int(const int index)
{
PRE(column_type(index) == type_integer);
return ::sqlite3_column_int(_pimpl->stmt, index);
}
/// Returns a particular column in the result as a 64-bit integer.
///
/// \param index The column to retrieve.
///
/// \return The integer value.
int64_t
sqlite::statement::column_int64(const int index)
{
PRE(column_type(index) == type_integer);
return ::sqlite3_column_int64(_pimpl->stmt, index);
}
/// Returns a particular column in the result as a double.
///
/// \param index The column to retrieve.
///
/// \return A C string with the contents. Note that the pointer returned by
/// this call will be invalidated on the next call to any SQLite API function.
/// If you want to be extra safe, store the result in a std::string to not worry
/// about this.
std::string
sqlite::statement::column_text(const int index)
{
PRE(column_type(index) == type_text);
return reinterpret_cast< const char* >(::sqlite3_column_text(
_pimpl->stmt, index));
}
/// Returns the number of bytes stored in the column.
///
/// \pre This is only valid for columns of type blob and text.
///
/// \param index The column to retrieve the size of.
///
/// \return The number of bytes in the column. Remember that strings are stored
/// in their UTF-8 representation; this call returns the number of *bytes*, not
/// characters.
int
sqlite::statement::column_bytes(const int index)
{
PRE(column_type(index) == type_blob || column_type(index) == type_text);
return ::sqlite3_column_bytes(_pimpl->stmt, index);
}
/// Type-checked version of column_blob.
///
/// \param name The name of the column to retrieve.
///
/// \return The same as column_blob if the value can be retrieved.
///
/// \throw error If the type of the cell to retrieve is invalid.
/// \throw invalid_column_error If name is invalid.
sqlite::blob
sqlite::statement::safe_column_blob(const char* name)
{
const int column = column_id(name);
if (column_type(column) != sqlite::type_blob)
throw sqlite::error(_pimpl->db.db_filename(),
F("Column '%s' is not a blob") % name);
return column_blob(column);
}
/// Type-checked version of column_double.
///
/// \param name The name of the column to retrieve.
///
/// \return The same as column_double if the value can be retrieved.
///
/// \throw error If the type of the cell to retrieve is invalid.
/// \throw invalid_column_error If name is invalid.
double
sqlite::statement::safe_column_double(const char* name)
{
const int column = column_id(name);
if (column_type(column) != sqlite::type_float)
throw sqlite::error(_pimpl->db.db_filename(),
F("Column '%s' is not a float") % name);
return column_double(column);
}
/// Type-checked version of column_int.
///
/// \param name The name of the column to retrieve.
///
/// \return The same as column_int if the value can be retrieved.
///
/// \throw error If the type of the cell to retrieve is invalid.
/// \throw invalid_column_error If name is invalid.
int
sqlite::statement::safe_column_int(const char* name)
{
const int column = column_id(name);
if (column_type(column) != sqlite::type_integer)
throw sqlite::error(_pimpl->db.db_filename(),
F("Column '%s' is not an integer") % name);
return column_int(column);
}
/// Type-checked version of column_int64.
///
/// \param name The name of the column to retrieve.
///
/// \return The same as column_int64 if the value can be retrieved.
///
/// \throw error If the type of the cell to retrieve is invalid.
/// \throw invalid_column_error If name is invalid.
int64_t
sqlite::statement::safe_column_int64(const char* name)
{
const int column = column_id(name);
if (column_type(column) != sqlite::type_integer)
throw sqlite::error(_pimpl->db.db_filename(),
F("Column '%s' is not an integer") % name);
return column_int64(column);
}
/// Type-checked version of column_text.
///
/// \param name The name of the column to retrieve.
///
/// \return The same as column_text if the value can be retrieved.
///
/// \throw error If the type of the cell to retrieve is invalid.
/// \throw invalid_column_error If name is invalid.
std::string
sqlite::statement::safe_column_text(const char* name)
{
const int column = column_id(name);
if (column_type(column) != sqlite::type_text)
throw sqlite::error(_pimpl->db.db_filename(),
F("Column '%s' is not a string") % name);
return column_text(column);
}
/// Type-checked version of column_bytes.
///
/// \param name The name of the column to retrieve the size of.
///
/// \return The same as column_bytes if the value can be retrieved.
///
/// \throw error If the type of the cell to retrieve the size of is invalid.
/// \throw invalid_column_error If name is invalid.
int
sqlite::statement::safe_column_bytes(const char* name)
{
const int column = column_id(name);
if (column_type(column) != sqlite::type_blob &&
column_type(column) != sqlite::type_text)
throw sqlite::error(_pimpl->db.db_filename(),
F("Column '%s' is not a blob or a string") % name);
return column_bytes(column);
}
/// Resets a statement to allow further processing.
void
sqlite::statement::reset(void)
{
(void)::sqlite3_reset(_pimpl->stmt);
}
/// Binds a blob to a prepared statement.
///
/// \param index The index of the binding.
/// \param b Description of the blob, which must remain valid during the
/// execution of the statement.
///
/// \throw api_error If the binding fails.
void
sqlite::statement::bind(const int index, const blob& b)
{
const int error = ::sqlite3_bind_blob(_pimpl->stmt, index, b.memory, b.size,
SQLITE_STATIC);
handle_bind_error(_pimpl->db, "sqlite3_bind_blob", error);
}
/// Binds a double value to a prepared statement.
///
/// \param index The index of the binding.
/// \param value The double value to bind.
///
/// \throw api_error If the binding fails.
void
sqlite::statement::bind(const int index, const double value)
{
const int error = ::sqlite3_bind_double(_pimpl->stmt, index, value);
handle_bind_error(_pimpl->db, "sqlite3_bind_double", error);
}
/// Binds an integer value to a prepared statement.
///
/// \param index The index of the binding.
/// \param value The integer value to bind.
///
/// \throw api_error If the binding fails.
void
sqlite::statement::bind(const int index, const int value)
{
const int error = ::sqlite3_bind_int(_pimpl->stmt, index, value);
handle_bind_error(_pimpl->db, "sqlite3_bind_int", error);
}
/// Binds a 64-bit integer value to a prepared statement.
///
/// \param index The index of the binding.
/// \param value The 64-bin integer value to bind.
///
/// \throw api_error If the binding fails.
void
sqlite::statement::bind(const int index, const int64_t value)
{
const int error = ::sqlite3_bind_int64(_pimpl->stmt, index, value);
handle_bind_error(_pimpl->db, "sqlite3_bind_int64", error);
}
/// Binds a NULL value to a prepared statement.
///
/// \param index The index of the binding.
/// \param unused_null An instance of the null class.
///
/// \throw api_error If the binding fails.
void
sqlite::statement::bind(const int index,
const null& UTILS_UNUSED_PARAM(null))
{
const int error = ::sqlite3_bind_null(_pimpl->stmt, index);
handle_bind_error(_pimpl->db, "sqlite3_bind_null", error);
}
/// Binds a text string to a prepared statement.
///
/// \param index The index of the binding.
/// \param text The string to bind. SQLite generates an internal copy of this
/// string, so the original string object does not have to remain live. We
/// do this because handling the lifetime of std::string objects is very
/// hard (think about implicit conversions), so it is very easy to shoot
/// ourselves in the foot if we don't do this.
///
/// \throw api_error If the binding fails.
void
sqlite::statement::bind(const int index, const std::string& text)
{
const int error = ::sqlite3_bind_text(_pimpl->stmt, index, text.c_str(),
text.length(), SQLITE_TRANSIENT);
handle_bind_error(_pimpl->db, "sqlite3_bind_text", error);
}
/// Returns the index of the highest parameter.
///
/// \return A parameter index.
int
sqlite::statement::bind_parameter_count(void)
{
return ::sqlite3_bind_parameter_count(_pimpl->stmt);
}
/// Returns the index of a named parameter.
///
/// \param name The name of the parameter to be queried; must exist.
///
/// \return A parameter index.
int
sqlite::statement::bind_parameter_index(const std::string& name)
{
const int index = ::sqlite3_bind_parameter_index(_pimpl->stmt,
name.c_str());
PRE_MSG(index > 0, "Parameter name not in statement");
return index;
}
/// Returns the name of a parameter by index.
///
/// \param index The index to query; must be valid.
///
/// \return The name of the parameter.
std::string
sqlite::statement::bind_parameter_name(const int index)
{
const char* name = ::sqlite3_bind_parameter_name(_pimpl->stmt, index);
PRE_MSG(name != NULL, "Index value out of range or nameless parameter");
return std::string(name);
}
/// Clears any bindings and releases their memory.
void
sqlite::statement::clear_bindings(void)
{
const int error = ::sqlite3_clear_bindings(_pimpl->stmt);
PRE_MSG(error == SQLITE_OK, "SQLite3 contract has changed; it should "
"only return SQLITE_OK");
}
| 30.828526 | 80 | 0.686957 | [
"object"
] |
aa6e7614542fda72e5cfe264682af5825eacec51 | 4,998 | cpp | C++ | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "ResetSettingsDialog.h"
#include <EMotionFX/Source/Actor.h>
#include <EMotionFX/Source/ActorManager.h>
#include <EMotionFX/Source/AnimGraphManager.h>
#include <EMotionFX/Source/AnimGraph.h>
#include <EMotionFX/Source/EMotionFXManager.h>
#include <EMotionFX/Source/MotionManager.h>
#include <EMotionFX/Source/Motion.h>
#include <EMotionFX/Source/MotionSet.h>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
namespace EMStudio
{
// Iterates through the objects in one of the Manager classes, and returns
// true if there is at least one object that is not owned by the runtime
template<class ManagerType, typename GetNumFunc, typename GetEntityFunc>
bool HasEntityInEditor(const ManagerType& manager, const GetNumFunc& getNumEntitiesFunc, const GetEntityFunc& getEntityFunc)
{
const uint32 numEntities = (manager.*getNumEntitiesFunc)();
for (uint32 i = 0; i < numEntities; ++i)
{
const auto& entity = (manager.*getEntityFunc)(i);
if (!entity->GetIsOwnedByRuntime())
{
return true;
}
}
return false;
}
ResetSettingsDialog::ResetSettingsDialog(QWidget* parent)
: QDialog(parent)
{
// update title of the dialog
setWindowTitle("Reset Workspace");
QVBoxLayout* vLayout = new QVBoxLayout(this);
vLayout->setAlignment(Qt::AlignTop);
setObjectName("StyledWidgetDark");
QLabel* topLabel = new QLabel("<b>Select one or more items that you want to reset:</b>");
topLabel->setStyleSheet("background-color: rgb(40, 40, 40); padding: 6px;");
topLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
vLayout->addWidget(topLabel);
vLayout->setMargin(0);
QVBoxLayout* layout = new QVBoxLayout();
layout->setMargin(5);
layout->setSpacing(4);
vLayout->addLayout(layout);
m_actorCheckbox = new QCheckBox("Actors");
m_actorCheckbox->setObjectName("EMFX.ResetSettingsDialog.Actors");
const bool hasActors = HasEntityInEditor(
EMotionFX::GetActorManager(), &EMotionFX::ActorManager::GetNumActors, &EMotionFX::ActorManager::GetActor);
m_actorCheckbox->setChecked(hasActors);
m_actorCheckbox->setDisabled(!hasActors);
m_motionCheckbox = new QCheckBox("Motions");
m_motionCheckbox->setObjectName("EMFX.ResetSettingsDialog.Motions");
const bool hasMotions = HasEntityInEditor(
EMotionFX::GetMotionManager(), &EMotionFX::MotionManager::GetNumMotions, &EMotionFX::MotionManager::GetMotion);
m_motionCheckbox->setChecked(hasMotions);
m_motionCheckbox->setDisabled(!hasMotions);
m_motionSetCheckbox = new QCheckBox("Motion Sets");
m_motionSetCheckbox->setObjectName("EMFX.ResetSettingsDialog.MotionSets");
const bool hasMotionSets = HasEntityInEditor(
EMotionFX::GetMotionManager(), &EMotionFX::MotionManager::GetNumMotionSets, &EMotionFX::MotionManager::GetMotionSet);
m_motionSetCheckbox->setChecked(hasMotionSets);
m_motionSetCheckbox->setDisabled(!hasMotionSets);
m_animGraphCheckbox = new QCheckBox("Anim Graphs");
m_animGraphCheckbox->setObjectName("EMFX.ResetSettingsDialog.AnimGraphs");
const bool hasAnimGraphs = HasEntityInEditor(
EMotionFX::GetAnimGraphManager(), &EMotionFX::AnimGraphManager::GetNumAnimGraphs, &EMotionFX::AnimGraphManager::GetAnimGraph);
m_animGraphCheckbox->setChecked(hasAnimGraphs);
m_animGraphCheckbox->setDisabled(!hasAnimGraphs);
layout->addWidget(m_actorCheckbox);
layout->addWidget(m_motionCheckbox);
layout->addWidget(m_motionSetCheckbox);
layout->addWidget(m_animGraphCheckbox);
QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
vLayout->addWidget(buttonBox);
}
bool ResetSettingsDialog::IsActorsChecked() const
{
return m_actorCheckbox->isChecked();
}
bool ResetSettingsDialog::IsMotionsChecked() const
{
return m_motionCheckbox->isChecked();
}
bool ResetSettingsDialog::IsMotionSetsChecked() const
{
return m_motionSetCheckbox->isChecked();
}
bool ResetSettingsDialog::IsAnimGraphsChecked() const
{
return m_animGraphCheckbox->isChecked();
}
} // namespace EMStudio
#include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/moc_ResetSettingsDialog.cpp>
| 39.354331 | 158 | 0.701481 | [
"object",
"3d"
] |
aa701e30f7fbbd778109796ba8487ac19dc09e11 | 44,635 | cpp | C++ | sources/parser/parser.cpp | louis845/COMP2012H_Project | 55ddef5e22d3dfc034b750c9b1de8f89d648ce32 | [
"MIT"
] | null | null | null | sources/parser/parser.cpp | louis845/COMP2012H_Project | 55ddef5e22d3dfc034b750c9b1de8f89d648ce32 | [
"MIT"
] | null | null | null | sources/parser/parser.cpp | louis845/COMP2012H_Project | 55ddef5e22d3dfc034b750c9b1de8f89d648ce32 | [
"MIT"
] | null | null | null | #include "parser.h"
#include "math/linear/LinearOperations.h"
using std::cout;
using std::endl;
using std::string;
using std::make_pair;
typedef Token::TokName TokName;
typedef Token::TokType TokType;
// TODO: add custom exception classes and refine exception handling
/* Rules for atomic tokens, check the docs for the full token list and
* grammar rules
*
* number ::= [(\+|-)?(\.[0-9]+|[0-9]+\.?[0-9]*)((e|E)(\+|-)?[0-9]+)?] | constants
* variable ::= [A-Za-z] | greek letters
* function ::= functions
* binop ::= + | - | * | ** | xx | // | / | ^ | %
*/
std::unordered_map<TokName, int> Parser::bin_op_precedence =
{
{TokName::PLUS, 100}, {TokName::MINUS, 100},
{TokName::AST, 200}, {TokName::CDOT, 200}, {TokName::DIV, 200}, {TokName::FRAC, 200}, {TokName::PERCENT, 200},
{TokName::CROSS, 300}, {TokName::SUP, 400}
};
Parser::Parser(const std::string& input): input(input), tokenizer(input) { getNextToken(); }
Parser::~Parser() { delete root; delete cur_tok; }
void Parser::reset_input(const std::string& input)
{
delete root;
delete cur_tok;
root = nullptr;
cur_tok = nullptr;
while (!var_table.empty())
{
bool flag{false};
for (auto iter = var_table.begin(); iter != var_table.end(); ++iter)
if (!iter->second)
{
var_table.erase(iter);
flag = true;
break;
}
if (!flag) break;
}
if (!input.empty()) this->input = input;
tokenizer.reset_input(this->input);
getNextToken();
}
// Only return precedence of binary operators
// any other tokens which are not in {')', ']', '}', '|', ',', '='} will have precedence -1
// ')', ']', '}', ',', '=' have precedence -2
// '|' has precedence -3
int Parser::getTokPrecedence()
{
if (cur_tok == nullptr) return -1;
switch (cur_tok->get_name())
{
case TokName::COMMA: case TokName::RP: case TokName::RSB:
case TokName::RCB: case TokName::EQUAL:
return -2;
case TokName::TEXTBAR:
return -3;
}
TokName name = cur_tok->get_name();
return bin_op_precedence.count(name) == 0 ? -1 : bin_op_precedence[name];
}
void Parser::getNextToken()
{
delete cur_tok;
cur_tok = tokenizer.getNextToken(); // caller will check whether cur_tok is a nullptr
// end of line is automatically omitted if not in linear system mode
while (cur_tok && cur_tok->get_name() == TokName::ENDL)
{
delete cur_tok;
cur_tok = tokenizer.getNextToken();
}
// Equal sign should never appear in a valid input unless during
// parsing linear systems
if (cur_tok && cur_tok->get_name() == TokName::EQUAL)
throw std::invalid_argument("expression contains invalid symbol '='");
}
// numberexpr
// ::= number
NumberExprAst* Parser::parseNum()
{
if (cur_tok == nullptr || cur_tok->get_type() != TokType::NUM) return nullptr;
NumberExprAst* num = new NumberExprAst(cur_tok->get_name(), cur_tok->get_raw_value());
getNextToken();
return num;
}
// matrixexpr
// ::= '[' bracketexpr ( ',' bracketexpr )* ']'
// ::= '(' bracketexpr ( ',' bracketexpr )* ')'
MatrixExprAst* Parser::parseMatrix()
{
if (cur_tok == nullptr || (cur_tok->get_name() != TokName::LSB && cur_tok->get_name() != TokName::LP))
return nullptr;
TokName expected_paren_type = cur_tok->get_name() == TokName::LP ? TokName::RP : TokName::RSB;
getNextToken();
MatrixExprAst* matrix = new MatrixExprAst;
std::vector<ExprAst*> row;
try
{
row = parseBracket();
}
catch (const std::invalid_argument& err)
{
std::cerr << "Invalid matrix: " << err.what() << '\n';
delete matrix;
throw std::invalid_argument("invalid matrix");
}
if (row.empty())
{
delete matrix;
throw std::invalid_argument("empty entries in matrix");
}
matrix->entries.push_back(row);
size_t col_size = row.size();
while (cur_tok != nullptr && cur_tok->get_name() == TokName::COMMA)
{
getNextToken();
try
{
row = parseBracket();
}
catch (const std::invalid_argument& err)
{
std::cerr << "invalid matrix: " << err.what() << '\n';
delete matrix;
throw std::invalid_argument("invalid matrix");
}
if (row.size() != col_size)
{
delete matrix;
throw std::invalid_argument("column sizes of each row of the matrix mismatch.");
}
matrix->entries.push_back(row);
}
if (cur_tok == nullptr || cur_tok->get_name() != expected_paren_type)
{
delete matrix;
if (expected_paren_type == TokName::RP)
throw std::invalid_argument("missing right parenthesis for the matrix");
else
throw std::invalid_argument("missing right square bracket for the matrix");
}
getNextToken();
return matrix;
}
// bracketexpr
// ::= '[' expression (',' expression)* ']'
std::vector<ExprAst*> Parser::parseBracket()
{
std::vector<ExprAst*> row;
if (cur_tok == nullptr || cur_tok->get_name() != TokName::LSB) return row;
getNextToken();
try
{
ExprAst* entry = parseExpr();
row.push_back(entry);
while (cur_tok != nullptr && cur_tok->get_name() == TokName::COMMA)
{
getNextToken();
entry = parseExpr();
row.push_back(entry);
}
if (cur_tok == nullptr || cur_tok->get_name() != TokName::RSB)
throw std::invalid_argument("incomplete matrix, expecting ']'");
getNextToken();
return row;
}
// Catch all exceptions but do not rethrow
// Only let top-level parseMatrix() handle exceptions
catch (...)
{
throw std::invalid_argument("invalid entries in the matrix");
}
}
// parenexpr
// ::= '(' expression ')'
// ::= '|' expression '|'
ExprAst* Parser::parseParen()
{
if (cur_tok == nullptr || cur_tok->get_type() == TokType::ERR) return nullptr;
if (cur_tok->get_name() == TokName::LP)
{
getNextToken();
ExprAst* temp = parseExpr();
if (cur_tok == nullptr || cur_tok->get_name() != TokName::RP)
{
delete temp;
throw std::invalid_argument("missing right parenthesis");
}
getNextToken();
return temp;
}
if (cur_tok->get_name() == TokName::TEXTBAR)
{
getNextToken();
ExprAst* temp = parseExpr(true);
if (cur_tok == nullptr || cur_tok->get_name() != TokName::TEXTBAR)
{
delete temp;
throw std::invalid_argument("missing closing textbar");
}
FunctionExprAst* abs = new FunctionExprAst(TokName::ABS, cur_tok->get_raw_value());
abs->args.push_back(temp);
getNextToken();
return abs;
}
return nullptr;
}
// identifierexpr
// ::= variable
// ::= function ( number | variable )
// ::= function '(' expression (',' expression)* ')'
// ::= function matrixexpr
//
// NOTE: the third and fourth rules are indistinguishable within any k tokens of
// looking-ahead i.e. always exists a string that needs LL(k+1) parser to resolve
// the ambiguity. To solve this problem, a little time travel trick is used since
// user input cannot be infinitely long. For this rule, as a result, it can be
// regard as an LL(*) parser.
ExprAst* Parser::parseId()
{
if (cur_tok == nullptr) return nullptr;
// identifierexpr ::= variable
if (cur_tok->get_type() == TokType::ID)
{
ExprAst* var = new VariableExprAst(cur_tok->get_raw_value(), &r_table, &arma_table);
auto iter = var_table.find(cur_tok->get_raw_value());
if (iter == var_table.end()) var_table[cur_tok->get_raw_value()] = 0;
else if (iter->second == 2) iter->second = 1;
getNextToken();
return var;
}
if (cur_tok->get_type() != TokType::OP || getTokPrecedence() != -1)
return nullptr; // binops are not functions
FunctionExprAst* func = new FunctionExprAst(cur_tok->get_name(), cur_tok->get_raw_value());
getNextToken();
if (cur_tok == nullptr)
{
delete func;
return nullptr;
}
// identifierexpr ::= function ( number | variable )
if (cur_tok->get_type() == TokType::NUM)
{
func->args.emplace_back(parseNum());
return func;
}
// identifierexpr ::= function ( number | variable )
if (cur_tok->get_type() == TokType::ID)
{
ExprAst* var = new VariableExprAst(cur_tok->get_raw_value(), &r_table, &arma_table);
auto iter = var_table.find(cur_tok->get_raw_value());
if (iter == var_table.end()) var_table[cur_tok->get_raw_value()] = 0;
else if (iter->second == 2) iter->second = 1;
func->args.emplace_back(var);
getNextToken();
return func;
}
// A little backup for time travelling XD
string backup = tokenizer.get_input();
// identifierexpr ::= function '(' expression (',' expression)* ')'
if (cur_tok->get_name() == TokName::LP)
{
getNextToken();
try
{
ExprAst* expr = parseExpr();
if (expr != nullptr)
{
func->args.emplace_back(expr);
while (cur_tok && cur_tok->get_name() == TokName::COMMA)
{
getNextToken();
expr = parseExpr();
if (expr == nullptr)
{
delete func;
return nullptr;
}
func->args.emplace_back(expr);
}
if (cur_tok == nullptr || cur_tok->get_name() != TokName::RP)
throw std::invalid_argument("missing right parenthesis for function");
getNextToken();
return func;
}
else
{
// Fail to follow rule 3, do time travelling and try rule 4
tokenizer.reset_input(backup);
delete cur_tok;
cur_tok = new TokOp("(");
}
}
catch (...)
{
tokenizer.reset_input(backup);
delete cur_tok;
cur_tok = new TokOp("(");
}
}
// identifierexpr ::= function matrixexpr
if (cur_tok->get_name() == TokName::LSB || cur_tok->get_name() == TokName::LP)
{
try
{
MatrixExprAst* mat = parseMatrix();
func->args.emplace_back(mat);
return func;
}
catch (...)
{
delete func;
throw;
}
}
delete func;
return nullptr;
}
// primaryexpr
// ::= numberexpr
// ::= parenexpr
// ::= matrixexpr
// ::= identifierexpr
//
// NOTE: again, there always exists a valid string where LL(k) cannot
// distinguish whether it is a parenexpr or a matrixexpr, but LL(k+1)
// parser can do, hence time travel
ExprAst* Parser::parsePrimary(bool inside_textbar)
{
if (cur_tok == nullptr) return nullptr;
if (cur_tok->get_type() == TokType::NUM)
return parseNum();
if (cur_tok->get_name() == TokName::TEXTBAR)
return parseParen();
string backup = tokenizer.get_input();
if (cur_tok->get_name() == TokName::LP)
{
try
{
ExprAst* parenexpr = parseParen();
if (parenexpr) return parenexpr;
tokenizer.reset_input(backup); // time travel
delete cur_tok;
cur_tok = new TokOp("(");
}
catch (...)
{
tokenizer.reset_input(backup); // time travel
delete cur_tok;
cur_tok = new TokOp("(");
}
}
if (cur_tok->get_name() == TokName::LSB || cur_tok->get_name() == TokName::LP)
{
ExprAst* matrixexpr = parseMatrix();
return matrixexpr;
}
ExprAst* expr = parseId();
if (!expr) throw std::invalid_argument("unknown expression");
return expr;
}
// binoprhs
// ::= ( binop ( '+' | '-' )? primaryexpr | ( '+' | '-' )? primaryexpr )*
ExprAst* Parser::parseBinOpRhs(int min_precedence, ExprAst* lhs, bool inside_textbar)
{
// Loop will terminate when
// 1) hitting right closing brackets i.e. ) ] }
// 2) hitting a pairing textbar when parsing a primaryexpr
// 3) hitting EOF or tokenizer encountered an error
while (true)
{
if (!cur_tok) return lhs;
int cur_precedence = getTokPrecedence();
TokName cur_op{TokName::CDOT}; // if not a binary op, presume to be multiplication
std::string cur_raw_str;
switch (cur_precedence)
{
case -1:
cur_precedence = bin_op_precedence[TokName::CDOT]; // CDOT is OK since matrix multiplication has associativity
if (cur_precedence < min_precedence) return lhs;
break;
case -2:
return lhs;
case -3:
if (inside_textbar) return lhs;
break;
default:
if (cur_precedence < min_precedence) return lhs;
cur_op = cur_tok->get_name();
cur_raw_str = cur_tok->get_raw_value();
getNextToken();
if (cur_tok == nullptr)
throw std::invalid_argument("binary expression is incomplete, missing right operand for " + cur_raw_str);
break;
}
ExprAst* rhs = nullptr;
try
{
if (cur_tok->get_name() == TokName::MINUS) // unitary minus
{
FunctionExprAst* neg_rhs = new FunctionExprAst(TokName::NEG, cur_tok->get_raw_value());
getNextToken();
rhs = parsePrimary(inside_textbar);
if (!rhs) throw std::invalid_argument("Incomplete expression, missing right hand side operand.");
neg_rhs->args.emplace_back(rhs);
rhs = neg_rhs;
}
else
{
if (cur_tok->get_name() == TokName::PLUS) getNextToken(); // unitary plus
rhs = parsePrimary(inside_textbar);
if (!rhs) throw std::invalid_argument("Incomplete expression, missing right hand side operand.");
}
}
catch (...)
{
delete rhs;
throw; // rethrow
}
int next_precedence = getTokPrecedence(); // no binop then assume multiplication
next_precedence = next_precedence == -1 ? bin_op_precedence[TokName::CDOT] : next_precedence;
if (next_precedence > cur_precedence) // the next binary group binds more tightly
{
// all operators with precedence greater than cur_precedence should be merged as the rhs
try
{
rhs = parseBinOpRhs(cur_precedence + 1, rhs, inside_textbar);
if (!rhs) throw std::invalid_argument("Incomplete expression, missing right hand side operand.");
}
catch (...)
{
delete rhs;
throw; // rethrow
}
}
lhs = new BinaryExprAst(cur_op, cur_raw_str, lhs, rhs); // merging
}
}
// expression
// ::= ( '+' | '-' )? primaryexpr binoprhs
ExprAst* Parser::parseExpr(bool inside_textbar)
{
if (cur_tok == nullptr) return nullptr;
switch (cur_tok->get_name())
{
// decomposition needs special handling
case TokName::SVD: case TokName:: SCHUR: case TokName::QR: case TokName::EIGEN:
{
FunctionExprAst* decomp = new FunctionExprAst(cur_tok->get_name(), cur_tok->get_raw_value());
getNextToken();
if (cur_tok == nullptr)
throw std::invalid_argument("missing argument for decomposition");
ExprAst* expr = parsePrimary(inside_textbar);
decomp->args.emplace_back(expr);
return decomp; // all remaining expression will be dumped
}
default: break;
}
if (cur_tok->get_name() == TokName::PLUS) getNextToken(); // uniary positive operator
else if (cur_tok->get_name() == TokName::MINUS) // uniary negative operator
{
FunctionExprAst* neg_expr = new FunctionExprAst(TokName::NEG, cur_tok->get_raw_value());
getNextToken();
ExprAst* expr = parsePrimary(inside_textbar);
if (!expr)
{
delete neg_expr;
throw std::runtime_error("fatal error, unexpected exception occurs");
}
neg_expr->args.emplace_back(expr);
return parseBinOpRhs(0, neg_expr, inside_textbar);
}
ExprAst* expr = parsePrimary(inside_textbar);
if (!expr) throw std::runtime_error("fatal error, unexpected exception occurs"); // should not occur during normal exception handling
return parseBinOpRhs(0, expr, inside_textbar);
}
// Auto detect which engine to use
void Parser::autoDetect(ExprAst* root)
{
if (root == nullptr || !res.success) return;
if (typeid(*root) == typeid(NumberExprAst))
{
NumberExprAst* temp = dynamic_cast<NumberExprAst*>(root);
// Float exists, choose Armadillo
if (temp->name == TokName::FLOAT || temp->name == TokName::PI || temp->name == TokName::E)
{
res.float_exists = true;
if (res.engine_chosen == 1)
{
res.success = false;
return;
}
res.engine_chosen = 2;
}
}
if (typeid(*root) == typeid(MatrixExprAst))
{
MatrixExprAst* temp = dynamic_cast<MatrixExprAst*>(root);
for (auto row : temp->entries)
for (auto entry : row)
{
// Recursively detect each entry
autoDetect(entry);
if (!res.success) return;
}
}
if (typeid(*root) == typeid(BinaryExprAst))
{
BinaryExprAst* temp = dynamic_cast<BinaryExprAst*>(root);
autoDetect(temp->lhs);
if (!res.success) return;
autoDetect(temp->rhs);
if (!res.success) return;
}
// If functions are not in the supported list of R
// or the arguments does not fulfill the requirements
// choose Armadillo
if (typeid(*root) == typeid(FunctionExprAst))
{
FunctionExprAst* temp = dynamic_cast<FunctionExprAst*>(root);
switch (temp->op)
{
case TokName::RREF: case TokName::SOLVE: case TokName::DET:
case TokName::INV: case TokName::CHAR_POLY: case TokName::NEG:
case TokName::ORTH:
break;
default:
res.func_exists = true;
if (res.engine_chosen == 1)
{
res.success = false;
return;
}
res.engine_chosen = 2;
}
for (auto arg : temp->args)
{
// Recursively detect the arguments
autoDetect(arg);
if (!res.success) return;
}
}
}
// Main driver function, handles all exceptions
const Info& Parser::parse(int engine_type, bool save, const string& var_name)
{
res.clear();
res.engine_chosen = engine_type;
if (save && var_table.count(var_name))
{
res.success = false;
res.err_msg = "Error: variable name already exists, please choose another name";
return res;
}
// Handle linear system mode
if (engine_type == 3 || input.find('=') != std::string::npos)
{
res.engine_used = 3;
try
{
evalLinearSystem(parseLinearSystem());
return res;
}
catch (const std::exception& err)
{
res.success = false;
res.err_msg = "Error: " + string(err.what());
return res;
}
}
// Normal mode, do the parsing first
try
{
delete root;
root = parseExpr();
if (root == nullptr) return res;
res.interpreted_input = getAsciiMath();
}
catch (const std::invalid_argument& err)
{
res.err_msg = "Error: parsing failed, " + string(err.what());
// delete root;
res.success = false;
return res;
}
catch (...)
{
res.err_msg = "Fatal error: unexpected exception thrown during parsing";
// delete root;
res.success = false;
return res;
}
// If parsing is fine, do evaluation based on the engine chosen
if (engine_type == 0) autoDetect(this->root);
if (res.success)
{
res.engine_used = res.engine_chosen ? res.engine_chosen : res.engine_used;
if (res.engine_used == 1) evalR(save, var_name);
if (res.engine_used == 2) eval(save, var_name);
return res;
}
else
{
res.err_msg = "Error: auto detection failed, please specify engine type";
// delete root;
return res;
}
}
const Info& Parser::getInfo() const
{
return res;
}
void Parser::evalR(bool save, const string& var_name)
{
if (getNumUnknown() > 1)
{
res.var_exists = true;
res.success = false;
res.err_msg = "Error: more than one variable with unknown value in the expression.\n";
res.err_msg += "You may want to assign values to some of the variables.\n";
return;
}
try
{
ROperand result = root->evalR(res);
if (result.type == ROperand::Type::MAT)
res.addMat(result, TokName::NA);
res.eval_result = result.genTex();
if (save)
{
var_table.insert(make_pair(var_name, 2));
r_table.insert(make_pair(var_name, result));
}
return;
}
catch (const std::invalid_argument& err)
{
res.success = false;
res.err_msg = "Error: evaluation failed, " + string(err.what());
return;
}
catch (const std::runtime_error& err)
{
res.success = false;
res.err_msg = "Error: evaluation failed, " + string(err.what());
return;
}
catch (...)
{
res.success = false;
res.err_msg = "Fatal error: unexpected exception thrown during evaluation";
return;
}
/* only for debugging or console output
if (result.type == ROperand::Type::NOR) cout << result.value;
else
{
cout << "[";
for (auto row : result.mat)
{
cout << "[";
for (auto col : row)
cout << col << ", ";
cout << "]";
}
cout << "]";
}
*/
}
void Parser::eval(bool save, const string& var_name)
{
if (getNumUnknown() > 0)
{
res.var_exists = true;
res.success = false;
res.err_msg = "Error: variables with unknown values are not supported in Armadillo.\n";
res.err_msg += "You may want to assign values to the variables.";
return;
}
try
{
if (typeid(*root) == typeid(FunctionExprAst))
{
FunctionExprAst* temp = dynamic_cast<FunctionExprAst*>(root);
switch (temp->op)
{
case TokName::QR: case TokName::EIGEN: case TokName::SCHUR: case TokName::SVD:
evalDecomp();
return;
default: break;
}
}
ArmaOperand result = root->eval();
// if (result.type == ArmaOperand::Type::NOR) cout << result.value;
// else if (result.type == ArmaOperand::Type::MAT) cout << result.mat;
// else cout << "(" << result.value << ")" << "I";
res.eval_result = result.genTex();
if (save)
{
var_table.insert(make_pair(var_name, 2));
arma_table.insert(make_pair(var_name, result));
}
return;
}
catch (const std::logic_error& err) // both evaluator and Armadillo's exception will be caught here
{
res.err_msg = "Error: evaluation failed, " + string(err.what());
res.success = false;
return;
}
catch (const std::runtime_error& err) // part of Armadillo's exception and some fatal error
{
res.err_msg = "Fatal error: " + string(err.what());
res.success = false;
return;
}
catch (...)
{
res.success = false;
res.err_msg = "Fatal error: unexpected exception thrown during evaluation";
return;
}
}
// Independent part for evaluating decompositions
// since all of them have unusual output i.e. cannot be wrapped
// by a single ArmaOperand
void Parser::evalDecomp()
{
FunctionExprAst* func = dynamic_cast<FunctionExprAst*>(root);
ArmaOperand arg = func->args[0]->eval();
if (arg.type != ArmaOperand::Type::MAT)
{
res.success = false;
throw std::logic_error("the operand of " + func->raw + " decomposition should be a matrix");
}
if (func->op == TokName::EIGEN)
{
arma::cx_mat eigvec;
arma::cx_vec eigval;
arma::eig_gen(eigval, eigvec, arg.mat);
res.eval_result = "&eigenvalues: " + ArmaOperand(arma::cx_mat(eigval)).genTex()
+ R"( \\ &eigenvectors: )" + ArmaOperand(eigvec).genTex();
return;
}
if (func->op == TokName::SCHUR)
{
arma::cx_mat U, S;
arma::schur(U, S, arg.mat);
res.eval_result = R"(&Schur~decomposition: \\ )";
res.eval_result += "&" + arg.genTex() + R"(\\ = &)" + ArmaOperand(U).genTex() + R"( \\ &)"
+ArmaOperand(S).genTex() + R"( \\ &)" + ArmaOperand(U).genTex() + R"(^*)";
return;
}
if (func->op == TokName::QR)
{
arma::cx_mat Q, R;
arma::qr(Q, R, arg.mat);
res.eval_result = R"(&QR~decomposition: \\ )";
res.eval_result += "&" + arg.genTex() + R"(\\ = &)" + ArmaOperand(Q).genTex() +
R"(\\ &)" + ArmaOperand(R).genTex();
return;
}
if (func->op == TokName::SVD)
{
arma::cx_mat U, V;
arma::vec s;
arma::svd(U, s, V, arg.mat);
arma::cx_mat S(arma::size(arg.mat), arma::fill::zeros);
s.resize(arma::size(arg.mat.diag()));
S.diag() = arma::cx_vec(s, arma::vec(arma::size(s), arma::fill::zeros));
res.eval_result = R"(&SVD: \\ )";
res.eval_result += "&" + arg.genTex() + R"(\\ = &)" + ArmaOperand(U).genTex()
+ R"(\\ &)" + ArmaOperand(S).genTex() + R"(\\ &)" + ArmaOperand(V).genTex() + R"(^T)";
return;
}
}
// Do pre-order traversal on the AST and print the infix notation of the expression
// only used in pure CLI mode
void Parser::printAst(ExprAst* root) const
{
if (!root) return;
if (typeid(*root) == typeid(BinaryExprAst))
{
BinaryExprAst* temp = dynamic_cast<BinaryExprAst*>(root);
cout << "(";
printAst(temp->lhs);
cout << " " << temp->raw << " ";
printAst(temp->rhs);
cout << ")";
}
else if (typeid(*root) == typeid(NumberExprAst))
{
NumberExprAst* temp = dynamic_cast<NumberExprAst*>(root);
if (temp->name == TokName::INTEGRAL)
cout << stol(temp->raw);
else if (temp->name == TokName::FLOAT)
cout << stod(temp->raw);
else cout << temp->raw;
}
else if (typeid(*root) == typeid(VariableExprAst))
{
VariableExprAst* temp = dynamic_cast<VariableExprAst*>(root);
cout << temp->name;
}
else if (typeid(*root) == typeid(MatrixExprAst))
{
MatrixExprAst* temp = dynamic_cast<MatrixExprAst*>(root);
cout << "[";
for (auto row_it = temp->entries.begin(); row_it != temp->entries.end() - 1; ++row_it)
{
cout << "[";
for (auto col_it = row_it->begin(); col_it != row_it->end() - 1; ++col_it)
{
printAst(*col_it);
cout << ", ";
}
printAst(*(row_it->end() - 1));
cout << "], ";
}
cout << "[";
auto last_row = (temp->entries.end() - 1);
for (auto col_it = last_row->begin(); col_it != last_row->end() - 1; ++col_it)
{
printAst(*col_it);
cout << ", ";
}
printAst(*(last_row->end() - 1));
cout << "]]";
}
else if (typeid(*root) == typeid(FunctionExprAst))
{
FunctionExprAst* temp = dynamic_cast<FunctionExprAst*>(root);
if (temp->raw == "|")
{
cout << "|";
printAst((temp->args[0]));
cout << "|";
}
else
{
cout << temp->raw << "(";
for (auto it = temp->args.begin(); it != temp->args.end() - 1; ++it)
{
printAst(*it);
cout << ", ";
}
printAst(*(temp->args.end() - 1));
cout << ")";
}
}
else throw std::runtime_error("Fail to print AST, exiting.");
}
void Parser::modifyCoeffs(const std::string& name, size_t row, bool neg,
std::map<std::string, std::map<int, ROperand*>>& coeffs, ROperand delta)
{
if (neg) delta = -delta;
if (coeffs[name].count(row))
*coeffs[name][row] += delta;
else
coeffs[name][row] = new ROperand(delta);
}
// EXPERIMENTAL: dedicated parser for parsing linear systems
// it is a feature added at the very end of the development
// therefore no major grammar modification on the main parser can be adopted for compatibility
// EXTREMELY UNRELIABLE, I myself do not believe this will work
//
// it works, how come??
std::vector<std::string> Parser::parseLinearSystem()
{
string lines = input;
size_t pos = lines.find(R"(\\)"), row_cnt = 0;
std::map<string, std::map<int, ROperand*>> coeffs;
// while-loop for seperating lines
while (true)
{
pos = pos == string::npos ? lines.size() : pos;
string line = lines.substr(0, pos);
size_t eq_pos = line.find('=');
if (eq_pos == string::npos)
throw std::invalid_argument("invalid linear equation, missing '='");
// Seperating the two sides of the equation
try
{
parseLine(line.substr(0, eq_pos), row_cnt, false, coeffs);
parseLine(line.substr(eq_pos + 1), row_cnt++, true, coeffs);
}
catch (...)
{
for (auto var : coeffs)
for (auto row : var.second)
delete row.second;
throw;
}
if (pos == lines.size()) break;
lines = lines.substr(pos + 2);
pos = lines.find(R"(\\)");
}
// Arrange all the coefficients after processing
//
// NOTE: coeffs is a map hence all variables names are automatically
// arranged in ascending order when pushed back in the vector
vector<string> var_names;
for (auto var : coeffs)
{
if (var.first == "constant") continue;
var_names.emplace_back(var.first);
}
var_names.emplace_back("constant");
R** matR = new R* [row_cnt];
for (size_t i = 0; i < row_cnt; ++i)
{
matR[i] = new R [coeffs.size()];
for (size_t j = 0; j < var_names.size() - 1; ++j)
{
if (coeffs[var_names[j]].count(i))
matR[i][j] = coeffs[var_names[j]].at(i)->value;
else matR[i][j] = newInt(0L);
}
// Constants should be on the right hand side, hence negative
if (coeffs["constant"].at(i))
matR[i][var_names.size() - 1] = -coeffs["constant"].at(i)->value;
else
matR[i][var_names.size() - 1] = newInt(0L);
}
res.parsed_mat.emplace_back(TokName::SOLVE, matR);
res.mat_size.emplace_back(std::make_pair(row_cnt, var_names.size()));
for (auto var : coeffs)
for (auto row : var.second)
delete row.second;
return var_names;
}
// Parsing each side of the equal sign
//
// From the parser grammar, I assert that all the nodes containing terms
// will be in the right subtree and the left subtree should be a node of
// BinaryExprAst except for the left-most leaf node, given the input is valid
void Parser::parseLine(std::string line, size_t row, bool neg,
std::map<std::string, std::map<int, ROperand*>>& coeffs)
{
Parser parser(line);
ExprAst* ast_root = parser.parseExpr(), *cur_root = ast_root;
if (ast_root == nullptr) throw std::invalid_argument("invalid linear system");
Info dummy_info;
dummy_info.engine_used = 3;
while (true)
{
if (cur_root == nullptr)
{
delete ast_root;
throw std::invalid_argument("the equation is not linear or not in valid form");
}
if (typeid(*cur_root) == typeid(NumberExprAst))
{
modifyCoeffs("constant", row, neg, coeffs, ROperand(cur_root->evalR(dummy_info)));
break;
}
else if (typeid(*cur_root) == typeid(VariableExprAst))
{
VariableExprAst* temp = dynamic_cast<VariableExprAst*>(cur_root);
if (temp->name != "t")
modifyCoeffs(temp->name, row, neg, coeffs, ROperand(newInt(1L)));
else
modifyCoeffs("constant", row, neg, coeffs, ROperand(newTerm(1)));
break;
}
else if (typeid(*cur_root) == typeid(BinaryExprAst))
{
BinaryExprAst* temp = dynamic_cast<BinaryExprAst*>(cur_root);
if (temp->op != TokName::PLUS && temp->op != TokName::MINUS)
{
try
{
string lhs = findVar(temp->lhs), rhs = findVar(temp->rhs);
if (lhs.empty() && rhs.empty())
{
modifyCoeffs("constant", row, neg, coeffs, ROperand(temp->evalR(dummy_info)));
break;
}
if (!lhs.empty() && !rhs.empty())
{
delete ast_root;
throw std::invalid_argument("the equation is not linear or not in valid form");
}
if (lhs.empty()) swap(lhs, rhs);
modifyCoeffs(lhs, row, neg, coeffs, ROperand(temp->evalR(dummy_info)));
break;
}
catch (...)
{
delete ast_root;
throw;
}
}
bool local_neg = neg == (temp->op == TokName::PLUS);
ExprAst* lhs = temp->lhs, *rhs = temp->rhs;
string var_name = findVar(rhs);
if (var_name.empty())
modifyCoeffs("constant", row, local_neg, coeffs, ROperand(rhs->evalR(dummy_info)));
else
modifyCoeffs(var_name, row, local_neg, coeffs, ROperand(rhs->evalR(dummy_info)));
cur_root = lhs;
}
else if (typeid(*cur_root) == typeid(FunctionExprAst))
{
FunctionExprAst* temp = dynamic_cast<FunctionExprAst*>(cur_root);
if (temp->op != TokName::NEG)
{
delete ast_root;
throw std::invalid_argument("the equation is not linear or not in valid form");
}
cur_root = temp->args[0];
neg = !neg;
}
else
{
delete ast_root;
throw std::invalid_argument("the equation is not linear or not in valid form");
}
}
delete ast_root;
}
// Find the variable name with the subtree of given root pointer
// Result will be an empty string if not found
string Parser::findVar(ExprAst* root)
{
if (typeid(*root) == typeid(BinaryExprAst))
{
BinaryExprAst* temp = dynamic_cast<BinaryExprAst*>(root);
string lhs = findVar(temp->lhs), rhs = findVar(temp->rhs);
// Both subtrees contain variables and they are not the same
if (lhs != rhs && !lhs.empty() && !rhs.empty())
throw std::invalid_argument("the equation is not linear or not in valid form, e.g. group two unknowns with parentheses");
if (!lhs.empty()) return lhs;
return rhs;
}
if (typeid(*root) == typeid(FunctionExprAst))
{
FunctionExprAst* temp = dynamic_cast<FunctionExprAst*>(root);
if (temp->op == TokName::NEG) return findVar(temp->args[0]);
// A non-linear function contains variables, the input is not a linear system
for (auto arg : temp->args)
if (!findVar(arg).empty())
throw std::invalid_argument("the equation is not linear or not in valid form");
}
if (typeid(*root) == typeid(VariableExprAst))
{
VariableExprAst* temp = dynamic_cast<VariableExprAst*>(root);
// t is a reserved name for unknown parameters in linear system
return temp->name == "t" ? "" : temp->name;
}
return "";
}
void Parser::evalLinearSystem(vector<string> var_names)
{
StepsHistory* steps{nullptr};
LinearOperationsFunc::solve(res.parsed_mat.back().second, res.mat_size.back().first,
res.mat_size.back().second, steps);
if (steps == nullptr)
throw std::invalid_argument("fail to solve the linear system, please check the input");
R** matR{nullptr};
int row, col;
steps->getAnswer(matR, row, col);
if (matR == nullptr)
{
delete steps;
throw std::invalid_argument("fail to solve the linear system, the input may be invalid or it has not solution");
}
// Construct the LaTeX output
res.eval_result = "&";
for (int i = 0; i < row; ++i)
{
string var = var_names[i];
// Enclose the subscript by curly braces
auto pos = var.find('_');
if (pos != string::npos)
var = var.substr(0, pos + 1) + "{" + var.substr(pos + 1) + "}";
res.eval_result += var + " = " + matR[i][0].to_latex() + R"( \quad )";
if (i != 0 && i % 3 == 0 && i != row - 1) res.eval_result += R"( \\ &)";
}
res.interpreted_input = R"(text(Please check the step-by-step section for the interpreted augmented matrix. ))";
res.interpreted_input += R"(text(The columns, from left to right, correspond to ))";
for (size_t i = 0; i < var_names.size() - 1; ++i)
{
res.interpreted_input += var_names[i];
if (i != var_names.size() - 2) res.interpreted_input += ", ";
}
for (int i = 0; i < row; ++i)
delete [] matR[i];
delete [] matR;
delete steps;
}
void Parser::print() const
{
printAst(root);
}
string Parser::getAsciiMath() const
{
if (root == nullptr) return "";
return root->genAsciiMath();
}
// Assign values to variables by passing the literal input from the user
// The input needs to be in AsciiMath format and the engine_type used to
// parsed the input
//
// If returning false, err_msg in Info object will be updated
bool Parser::assignVar(const string& var_name, const string& raw, int type)
{
string name = checkVarNameValid(var_name);
if (name.empty()) return false;
Parser parser(raw);
const Info& result = parser.parse(type);
Info dummy_info;
if (!res.success)
{
res.err_msg = result.err_msg;
return false;
}
if (type == 1)
{
ROperand value;
try { value = parser.root->evalR(dummy_info); }
catch (const std::exception& err)
{
res.err_msg = err.what();
return false;
}
auto iter = arma_table.find(name);
if (iter != arma_table.end()) arma_table.erase(iter);
r_table[name] = value;
auto var_iter = var_table.find(name);
if (var_iter == var_table.end()) var_table[name] = 2;
else if (!var_iter->second) var_iter->second = 1;
return true;
}
ArmaOperand value;
try { value = parser.root->eval(); }
catch (const std::exception& err)
{
res.err_msg = err.what();
return false;
}
auto iter = r_table.find(name);
if (iter != r_table.end()) r_table.erase(iter);
arma_table[name] = value;
auto var_iter = var_table.find(name);
if (var_iter == var_table.end()) var_table[name] = 2;
else if (!var_iter->second) var_iter->second = 1;
return true;
}
// Explicitly assign values to variables by passing the corresponding ROperand
// Therefore, users can use the intermediate steps of linear operations as
// variables to reduce the effort of input
bool Parser::assignVar(const string& var_name, const ROperand& value)
{
string name = checkVarNameValid(var_name);
if (name.empty()) return false;
auto iter = arma_table.find(name);
if (iter != arma_table.end()) arma_table.erase(iter);
r_table[name] = value;
auto var_iter = var_table.find(name);
if (var_iter == var_table.end()) var_table[name] = 2;
else if (!var_iter->second) var_iter->second = 1;
return true;
}
// Change the name of an existing variable to an unused name
// NOTE: the variable name appeared in the input CANNOT be modified
// even if they are not assigned with values
bool Parser::modifyName(const string& ori_name, const string& new_name)
{
if (!var_table.count(ori_name) || var_table.count(new_name)) return false;
if (var_table[ori_name] < 2) return false;
string name = checkVarNameValid(new_name);
if (name.empty()) return false;
auto r_iter = r_table.find(ori_name);
if (r_iter != r_table.end())
{
ROperand value = r_iter->second;
r_table.erase(r_iter);
r_table[name] = value;
return true;
}
auto arma_iter = arma_table.find(ori_name);
if (arma_iter != arma_table.end())
{
ArmaOperand value = arma_iter->second;
arma_table.erase(arma_iter);
arma_table[name] = value;
return true;
}
var_table.erase(ori_name);
var_table.insert(make_pair(name, 2));
return false;
}
// Erase a variable, which CANNOT be the variables appeared in the expression
bool Parser::eraseVar(const string& var_name)
{
if (!var_table.count(var_name) || var_table[var_name] < 2) return false;
if (arma_table.count(var_name)) arma_table.erase(var_name);
if (r_table.count(var_name)) r_table.erase(var_name);
var_table.erase(var_name);
return true;
}
// Retrieve a map from all the variables names to their values in LaTaX
// Variables with no values assigned will have value empty string
map<string, string> Parser::retrieve_var() const
{
map<string, string> table;
for (const auto& item : r_table)
table.insert(make_pair(item.first, item.second.genTex()));
for (const auto& item : arma_table)
table.insert(make_pair(item.first, item.second.genTex()));
for (const auto& item : var_table)
table.insert(make_pair(item.first, "")); // map.insert() won't overwrite an existent pair
return table;
}
// Retrieve the number of variables with unknown values in the input
// before do the actual evaluation
int Parser::getNumUnknown() const
{
int cnt = 0;
for (auto item : var_table)
if (!item.second) ++cnt;
return cnt;
}
// Check whether a variable user picked is valid or not
string Parser::checkVarNameValid(const std::string& var_name) const
{
Lexer lexer(var_name);
Token* var = lexer.getNextToken();
if (var == nullptr || var->get_type() != TokType::ID)
return "";
// Check whether there is additional useless string
if (lexer.getNextToken() != nullptr)
return "";
return var->get_raw_value();
}
// Check whether the given variable name exists
bool Parser::hasVarName(const std::string& var_name) const
{
return var_table.count(var_name) > 0;
}
| 30.975017 | 141 | 0.551652 | [
"object",
"vector"
] |
aa7023f1163ebaf5c4a889ae2ec64f69eae387c8 | 1,900 | hpp | C++ | src/vulkan_app.hpp | leluron/nbody | 34639f408d0c22162ed336ee01f660115b637252 | [
"MIT"
] | 4 | 2019-02-28T11:25:29.000Z | 2020-07-27T13:20:16.000Z | src/vulkan_app.hpp | leluron/nbody | 34639f408d0c22162ed336ee01f660115b637252 | [
"MIT"
] | 3 | 2018-05-27T17:53:14.000Z | 2018-05-28T04:30:54.000Z | src/vulkan_app.hpp | PLeLuron/nbody | 34639f408d0c22162ed336ee01f660115b637252 | [
"MIT"
] | 1 | 2019-09-09T10:21:13.000Z | 2019-09-09T10:21:13.000Z | #pragma once
#include <vulkan/vulkan.h>
#include <GLFW/glfw3.h>
#include <vector>
#include <string>
#include <iostream>
#define log(x) std::cout << (x) << std::endl
struct QueueFamilies
{
int32_t graphics;
int32_t present;
bool isValid() { return graphics >= 0 && present >= 0;}
};
class VulkanApp
{
protected:
VkInstance instance;
VkDevice device;
VkPhysicalDevice physicalDevice;
QueueFamilies families;
VkCommandPool commandPool;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkSurfaceKHR surface;
VkPhysicalDeviceProperties deviceProperties;
struct {
VkSwapchainKHR swapchain;
std::vector<VkImage> images;
std::vector<VkImageView> views;
std::vector<VkFramebuffer> framebuffers;
std::vector<VkCommandBuffer> commandBuffers;
std::vector<VkFence> fences;
VkExtent2D extent;
VkFormat format;
VkSemaphore imageAvailable;
VkSemaphore renderFinished;
} swapchain;
void createInstance(const std::string &appName);
void createSurface(GLFWwindow *window);
void createDevice();
void createSwapchain(int width, int height);
void createFramebuffers(VkRenderPass renderPass);
void createCommandPool();
void createBuffer(
VkDeviceSize size,
VkBufferUsageFlags usage,
VkMemoryPropertyFlags properties,
VkBuffer &buffer,
VkDeviceMemory &memory);
void createImage(
VkImageType imageType,
VkFormat format,
VkExtent3D extent,
uint32_t mipLevels,
uint32_t arrayLayers,
VkSampleCountFlagBits samples,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageLayout layout,
VkMemoryPropertyFlags properties,
VkImage &image,
VkDeviceMemory &memory);
uint32_t acquireImage();
void present(uint32_t imageIndex);
VkShaderModule createShaderModule(const std::string &filename);
int32_t findProperties(VkMemoryPropertyFlags flags);
uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
void destroy();
}; | 22.619048 | 80 | 0.777368 | [
"vector"
] |
aa72e69a6b46f300b348cd18c96525d09d2c3af7 | 26,567 | cpp | C++ | Ipopt-3.12.7/Ipopt/src/Algorithm/LinearSolvers/IpMa97SolverInterface.cpp | MikeBMW/CarND-MPC-Project | 81e6e92de2768dce9fbfd1848de6f4465d468a0e | [
"MIT"
] | 9 | 2020-07-09T06:40:31.000Z | 2022-03-28T02:50:21.000Z | third-party/CoinIpopt/Ipopt/src/Algorithm/LinearSolvers/IpMa97SolverInterface.cpp | WatsonZhouAnda/Cheetah-Software | 05e416fb26f968300826f0deb0953be9afb22bfe | [
"MIT"
] | null | null | null | third-party/CoinIpopt/Ipopt/src/Algorithm/LinearSolvers/IpMa97SolverInterface.cpp | WatsonZhouAnda/Cheetah-Software | 05e416fb26f968300826f0deb0953be9afb22bfe | [
"MIT"
] | 5 | 2020-12-01T01:41:12.000Z | 2022-01-04T01:21:49.000Z | // Copyright (C) 2012, The Science and Technology Facilities Council.
// Copyright (C) 2009, Jonathan Hogg <jhogg41.at.gmail.com>.
// Copyright (C) 2004, 2007 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id: IpMa97SolverInterface.cpp 2003 2011-06-03 03:53:44Z andreasw $
//
// Authors: Jonathan Hogg STFC 2012-12-21
// Jonathan Hogg 2009-07-29
// Carl Laird, Andreas Waechter IBM 2004-03-17
#include "IpoptConfig.h"
#ifdef COIN_HAS_HSL
#include "CoinHslConfig.h"
#endif
// if we have MA97 in HSL or the linear solver loader, then we want to build the MA97 interface
#if defined(COINHSL_HAS_MA97) || defined(HAVE_LINEARSOLVERLOADER)
#include "IpMa97SolverInterface.hpp"
#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std;
/* Uncomment the following line to enable the ma97_dump_matrix option.
* This option requires a version of the coinhsl that supports this function.
*/
//#define MA97_DUMP_MATRIX
#ifdef MA97_DUMP_MATRIX
extern "C" {
extern void F77_FUNC (dump_mat_csc, DUMP_MAT_CSC) (
const ipfint *factidx,
const ipfint *n,
const ipfint *ptr,
const ipfint *row,
const double *a);
}
#endif
namespace Ipopt
{
Ma97SolverInterface::~Ma97SolverInterface()
{
delete [] val_;
if(scaling_) delete [] scaling_;
ma97_finalise(&akeep_, &fkeep_);
}
void Ma97SolverInterface::RegisterOptions(SmartPtr<RegisteredOptions> roptions)
{
roptions->AddIntegerOption(
"ma97_print_level",
"Debug printing level for the linear solver MA97",
0, ""
/*
"<0 no printing.\n"
"0 Error and warning messages only.\n"
"=1 Limited diagnostic printing.\n"
">1 Additional diagnostic printing."*/);
roptions->AddLowerBoundedIntegerOption(
"ma97_nemin",
"Node Amalgamation parameter",
1, 8,
"Two nodes in elimination tree are merged if result has fewer than "
"ma97_nemin variables.");
roptions->AddLowerBoundedNumberOption(
"ma97_small",
"Zero Pivot Threshold",
0.0, false, 1e-20,
"Any pivot less than ma97_small is treated as zero.");
roptions->AddBoundedNumberOption(
"ma97_u",
"Pivoting Threshold",
0.0, false, 0.5, false, 1e-8,
"See MA97 documentation.");
roptions->AddBoundedNumberOption(
"ma97_umax",
"Maximum Pivoting Threshold",
0.0, false, 0.5, false, 1e-4,
"See MA97 documentation.");
roptions->AddStringOption5(
"ma97_scaling",
"Specifies strategy for scaling in HSL_MA97 linear solver",
"dynamic",
"none", "Do not scale the linear system matrix",
"mc30", "Scale all linear system matrices using MC30",
"mc64", "Scale all linear system matrices using MC64",
"mc77", "Scale all linear system matrices using MC77 [1,3,0]",
"dynamic", "Dynamically select scaling according to rules specified by ma97_scalingX and ma97_switchX options.",
"");
roptions->AddStringOption4(
"ma97_scaling1",
"First scaling.",
"mc64",
"none", "No scaling",
"mc30", "Scale linear system matrix using MC30",
"mc64", "Scale linear system matrix using MC64",
"mc77", "Scale linear system matrix using MC77 [1,3,0]",
"If ma97_scaling=dynamic, this scaling is used according to the trigger "
"ma97_switch1. If ma97_switch2 is triggered it is disabled.");
roptions->AddStringOption9(
"ma97_switch1",
"First switch, determine when ma97_scaling1 is enabled.",
"od_hd_reuse",
"never", "Scaling is never enabled.",
"at_start", "Scaling to be used from the very start.",
"at_start_reuse", "Scaling to be used on first iteration, then reused thereafter.",
"on_demand", "Scaling to be used after Ipopt request improved solution (i.e. iterative refinement has failed).",
"on_demand_reuse", "As on_demand, but reuse scaling from previous itr",
"high_delay", "Scaling to be used after more than 0.05*n delays are present",
"high_delay_reuse", "Scaling to be used only when previous itr created more that 0.05*n additional delays, otherwise reuse scaling from previous itr",
"od_hd", "Combination of on_demand and high_delay",
"od_hd_reuse", "Combination of on_demand_reuse and high_delay_reuse",
"If ma97_scaling=dynamic, ma97_scaling1 is enabled according to this condition. If ma97_switch2 occurs this option is henceforth ignored.");
roptions->AddStringOption4(
"ma97_scaling2",
"Second scaling.",
"mc64",
"none", "No scaling",
"mc30", "Scale linear system matrix using MC30",
"mc64", "Scale linear system matrix using MC64",
"mc77", "Scale linear system matrix using MC77 [1,3,0]",
"If ma97_scaling=dynamic, this scaling is used according to the trigger "
"ma97_switch2. If ma97_switch3 is triggered it is disabled.");
roptions->AddStringOption9(
"ma97_switch2",
"Second switch, determine when ma97_scaling2 is enabled.",
"never",
"never", "Scaling is never enabled.",
"at_start", "Scaling to be used from the very start.",
"at_start_reuse", "Scaling to be used on first iteration, then reused thereafter.",
"on_demand", "Scaling to be used after Ipopt request improved solution (i.e. iterative refinement has failed).",
"on_demand_reuse", "As on_demand, but reuse scaling from previous itr",
"high_delay", "Scaling to be used after more than 0.05*n delays are present",
"high_delay_reuse", "Scaling to be used only when previous itr created more that 0.05*n additional delays, otherwise reuse scaling from previous itr",
"od_hd", "Combination of on_demand and high_delay",
"od_hd_reuse", "Combination of on_demand_reuse and high_delay_reuse",
"If ma97_scaling=dynamic, ma97_scaling2 is enabled according to this condition. If ma97_switch3 occurs this option is henceforth ignored.");
roptions->AddStringOption4(
"ma97_scaling3",
"Third scaling.",
"mc64",
"none", "No scaling",
"mc30", "Scale linear system matrix using MC30",
"mc64", "Scale linear system matrix using MC64",
"mc77", "Scale linear system matrix using MC77 [1,3,0]",
"If ma97_scaling=dynamic, this scaling is used according to the trigger "
"ma97_switch3.");
roptions->AddStringOption9(
"ma97_switch3",
"Third switch, determine when ma97_scaling3 is enabled.",
"never",
"never", "Scaling is never enabled.",
"at_start", "Scaling to be used from the very start.",
"at_start_reuse", "Scaling to be used on first iteration, then reused thereafter.",
"on_demand", "Scaling to be used after Ipopt request improved solution (i.e. iterative refinement has failed).",
"on_demand_reuse", "As on_demand, but reuse scaling from previous itr",
"high_delay", "Scaling to be used after more than 0.05*n delays are present",
"high_delay_reuse", "Scaling to be used only when previous itr created more that 0.05*n additional delays, otherwise reuse scaling from previous itr",
"od_hd", "Combination of on_demand and high_delay",
"od_hd_reuse", "Combination of on_demand_reuse and high_delay_reuse",
"If ma97_scaling=dynamic, ma97_scaling3 is enabled according to this condition.");
roptions->AddStringOption7(
"ma97_order",
"Controls type of ordering used by HSL_MA97",
"auto",
"auto", "Use HSL_MA97 heuristic to guess best of AMD and METIS",
"best", "Try both AMD and MeTiS, pick best",
"amd", "Use the HSL_MC68 approximate minimum degree algorithm",
"metis", "Use the MeTiS nested dissection algorithm",
"matched-auto", "Use the HSL_MC80 matching with heuristic choice of AMD or METIS",
"matched-metis", "Use the HSL_MC80 matching based ordering with METIS",
"matched-amd", "Use the HSL_MC80 matching based ordering with AMD",
"");
#ifdef MA97_DUMP_MATRIX
roptions->AddStringOption2(
"ma97_dump_matrix",
"Controls whether HSL_MA97 dumps each matrix to a file",
"no",
"no", "Do not dump matrix",
"yes", "Do dump matrix",
"");
#endif
roptions->AddStringOption2(
"ma97_solve_blas3",
"Controls if blas2 or blas3 routines are used for solve",
"no",
"no", "Use BLAS2 (faster, some implementations bit incompatible)",
"yes", "Use BLAS3 (slower)",
"");
}
int Ma97SolverInterface::ScaleNameToNum(const std::string& name) {
if(name=="none") return 0;
if(name=="mc64") return 1;
if(name=="mc77") return 2;
if(name=="mc30") return 4;
assert(0);
return -1;
}
bool Ma97SolverInterface::InitializeImpl(const OptionsList& options,
const std::string& prefix)
{
ma97_default_control(&control_);
control_.f_arrays = 1; // Use Fortran numbering (faster)
control_.action = 0; // false, shuold exit with error on singularity
options.GetIntegerValue("ma97_print_level", control_.print_level,
prefix);
options.GetIntegerValue("ma97_nemin", control_.nemin, prefix);
options.GetNumericValue("ma97_small", control_.small, prefix);
options.GetNumericValue("ma97_u", control_.u, prefix);
options.GetNumericValue("ma97_umax", umax_, prefix);
std::string order_method, scaling_method, rescale_strategy;
options.GetStringValue("ma97_order", order_method, prefix);
if(order_method == "metis") {
ordering_ = ORDER_METIS;
} else if(order_method == "amd") {
ordering_ = ORDER_AMD;
} else if(order_method == "best") {
ordering_ = ORDER_BEST;
} else if(order_method == "matched-metis") {
ordering_ = ORDER_MATCHED_METIS;
} else if(order_method == "matched-amd") {
ordering_ = ORDER_MATCHED_AMD;
} else if(order_method == "matched-auto") {
ordering_ = ORDER_MATCHED_AUTO;
} else {
ordering_ = ORDER_AUTO;
}
options.GetStringValue("ma97_scaling", scaling_method, prefix);
current_level_ = 0;
if(scaling_method == "dynamic") {
scaling_type_ = 0;
string switch_val[3], scale_val[3];
options.GetStringValue("ma97_switch1", switch_val[0], prefix);
options.GetStringValue("ma97_scaling1", scale_val[0], prefix);
options.GetStringValue("ma97_switch2", switch_val[1], prefix);
options.GetStringValue("ma97_scaling2", scale_val[1], prefix);
options.GetStringValue("ma97_switch3", switch_val[2], prefix);
options.GetStringValue("ma97_scaling3", scale_val[2], prefix);
for(int i=0; i<3; i++) {
scaling_val_[i] = ScaleNameToNum(scale_val[i]);
if(switch_val[i]=="never")
switch_[i] = SWITCH_NEVER;
else if(switch_val[i]=="at_start") {
switch_[i] = SWITCH_AT_START;
scaling_type_ = scaling_val_[i];
current_level_ = i;
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Enabled scaling level %d on initialization\n", current_level_);
}
else if(switch_val[i]=="at_start_reuse") {
switch_[i] = SWITCH_AT_START_REUSE;
scaling_type_ = scaling_val_[i];
current_level_ = i;
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Enabled scaling level %d on initialization\n", current_level_);
}
else if(switch_val[i]=="on_demand")
switch_[i] = SWITCH_ON_DEMAND;
else if(switch_val[i]=="on_demand_reuse")
switch_[i] = SWITCH_ON_DEMAND_REUSE;
else if(switch_val[i]=="high_delay")
switch_[i] = SWITCH_NDELAY;
else if(switch_val[i]=="high_delay_reuse")
switch_[i] = SWITCH_NDELAY_REUSE;
else if(switch_val[i]=="od_hd")
switch_[i] = SWITCH_OD_ND;
else if(switch_val[i]=="od_hd_reuse")
switch_[i] = SWITCH_OD_ND_REUSE;
}
} else {
switch_[0] = SWITCH_AT_START;
switch_[1] = SWITCH_NEVER;
switch_[2] = SWITCH_NEVER;
scaling_type_ = ScaleNameToNum(scaling_method);
}
#ifdef MA97_DUMP_MATRIX
options.GetBoolValue("ma97_dump_matrix", dump_, prefix);
#endif
bool solve_blas3;
options.GetBoolValue("ma97_solve_blas3", solve_blas3, prefix);
control_.solve_blas3 = solve_blas3 ? 1 : 0;
// Set whether we scale on first iteration or not
switch(switch_[current_level_]) {
case SWITCH_NEVER:
case SWITCH_ON_DEMAND:
case SWITCH_ON_DEMAND_REUSE:
case SWITCH_NDELAY:
case SWITCH_NDELAY_REUSE:
case SWITCH_OD_ND:
case SWITCH_OD_ND_REUSE:
rescale_ = false;
break;
case SWITCH_AT_START:
case SWITCH_AT_START_REUSE:
rescale_ = true;
break;
}
// Set scaling
control_.scaling = scaling_type_;
return true; // All is well
}
/* Method for initializing internal stuctures. Here, ndim gives
* the number of rows and columns of the matrix, nonzeros give
* the number of nonzero elements, and ia and ja give the
* positions of the nonzero elements, given in the matrix format
* determined by MatrixFormat.
*/
ESymSolverStatus Ma97SolverInterface::InitializeStructure(Index dim,
Index nonzeros, const Index* ia, const Index* ja)
{
struct ma97_info info, info2;
void *akeep_amd, *akeep_metis;
// Store size for later use
ndim_ = dim;
// Setup memory for values
if (val_!=NULL) delete[] val_;
val_ = new double[nonzeros];
// Check if analyse needs to be postponed
if(ordering_ == ORDER_MATCHED_AMD || ordering_ == ORDER_MATCHED_METIS) {
// Ordering requires values. Just signal success and return
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Delaying analyse until values are available\n");
switch(ordering_)
{
case ORDER_MATCHED_AMD:
control_.ordering = 7; // HSL_MC80 with AMD
break;
case ORDER_MATCHED_METIS:
control_.ordering = 8; // HSL_MC80 with METIS
break;
}
return SYMSOLVER_SUCCESS;
}
if (HaveIpData()) {
IpData().TimingStats().LinearSystemSymbolicFactorization().Start();
}
// perform analyse
if(ordering_ == ORDER_BEST) {
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Use best of AMD or MeTiS:\n");
control_.ordering = 1; // AMD
ma97_analyse(0, dim, ia, ja, NULL, &akeep_amd, &control_, &info2, NULL);
if (info2.flag<0) return SYMSOLVER_FATAL_ERROR;
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"AMD nfactor = %d, nflops = %d:\n",
info2.num_factor, info2.num_flops);
control_.ordering = 3; // METIS
ma97_analyse(0, dim, ia, ja, NULL, &akeep_metis, &control_, &info, NULL);
if (info.flag<0) return SYMSOLVER_FATAL_ERROR;
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"MeTiS nfactor = %d, nflops = %d:\n",
info.num_factor, info.num_flops);
if(info.num_flops > info2.num_flops) {
// Use AMD
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Choose AMD\n");
akeep_ = akeep_amd;
ma97_free_akeep(&akeep_metis);
info = info2;
} else {
// Use MeTiS
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Choose MeTiS\n");
akeep_ = akeep_metis;
ma97_free_akeep(&akeep_amd);
}
} else {
switch(ordering_)
{
case ORDER_AMD:
case ORDER_MATCHED_AMD:
control_.ordering = 1; // AMD
break;
case ORDER_METIS:
case ORDER_MATCHED_METIS:
control_.ordering = 3; // METIS
break;
case ORDER_AUTO:
case ORDER_MATCHED_AUTO:
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Make heuristic choice of AMD or MeTiS\n");
control_.ordering = 5; // Use heuristic to pick which to use
}
ma97_analyse(0, dim, ia, ja, NULL, &akeep_, &control_, &info, NULL);
switch(info.ordering) {
case 1:
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Used AMD\n");
if(ordering_ == ORDER_MATCHED_AUTO)
ordering_ = ORDER_MATCHED_AMD;
break;
case 3:
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Used MeTiS\n");
if(ordering_ == ORDER_MATCHED_AUTO)
ordering_ = ORDER_MATCHED_METIS;
break;
default:
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Used ordering %d\n", info.ordering);
break;
}
}
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: PREDICTED nfactor %d, maxfront %d\n",
info.num_factor, info.maxfront);
if (HaveIpData()) {
IpData().TimingStats().LinearSystemSymbolicFactorization().End();
}
if (info.flag>=0) {
return SYMSOLVER_SUCCESS;
}
else {
return SYMSOLVER_FATAL_ERROR;
}
}
/* Solve operation for multiple right hand sides. Solves the
* linear system A * x = b with multiple right hand sides, where
* A is the symmtric indefinite matrix. Here, ia and ja give the
* positions of the values (in the required matrix data format).
* The actual values of the matrix will have been given to this
* object by copying them into the array provided by
* GetValuesArrayPtr. ia and ja are identical to the ones given
* to InitializeStructure. The flag new_matrix is set to true,
* if the values of the matrix has changed, and a refactorzation
* is required.
*
* The return code is SYMSOLV_SUCCESS if the factorization and
* solves were successful, SYMSOLV_SINGULAR if the linear system
* is singular, and SYMSOLV_WRONG_INERTIA if check_NegEVals is
* true and the number of negative eigenvalues in the matrix does
* not match numberOfNegEVals. If SYMSOLV_CALL_AGAIN is
* returned, then the calling function will request the pointer
* for the array for storing a again (with GetValuesPtr), write
* the values of the nonzero elements into it, and call this
* MultiSolve method again with the same right-hand sides. (This
* can be done, for example, if the linear solver realized it
* does not have sufficient memory and needs to redo the
* factorization; e.g., for MA27.)
*
* The number of right-hand sides is given by nrhs, the values of
* the right-hand sides are given in rhs_vals (one full right-hand
* side stored immediately after the other), and solutions are
* to be returned in the same array.
*
* check_NegEVals will not be chosen true, if ProvidesInertia()
* returns false.
*/
ESymSolverStatus Ma97SolverInterface::MultiSolve(bool new_matrix,
const Index* ia, const Index* ja, Index nrhs, double* rhs_vals,
bool check_NegEVals, Index numberOfNegEVals)
{
struct ma97_info info;
Number t1=0,t2;
if (new_matrix || pivtol_changed_) {
#ifdef MA97_DUMP_MATRIX
if(dump_) {
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"Dumping matrix %d\n", fctidx_);
F77_FUNC (dump_mat_csc, DUMP_MAT_CSC)
(&fctidx_, &ndim_, ia, ja, val_);
fctidx_++;
}
#endif
// Set scaling option
if(rescale_) {
control_.scaling = scaling_type_;
if(scaling_type_!=0 && scaling_==NULL)
scaling_ = new double[ndim_]; // alloc if not already
} else {
control_.scaling = 0; // None or user (depends if scaling_ is alloc'd)
}
if((ordering_ == ORDER_MATCHED_AMD || ordering_ == ORDER_MATCHED_METIS) && rescale_) {
/*
* Perform delayed analyse
*/
if (HaveIpData()) {
IpData().TimingStats().LinearSystemSymbolicFactorization().Start();
}
switch(ordering_)
{
case ORDER_MATCHED_AMD:
control_.ordering = 7; // HSL_MC80 with AMD
break;
case ORDER_MATCHED_METIS:
control_.ordering = 8; // HSL_MC80 with METIS
break;
}
ma97_analyse(0, ndim_, ia, ja, val_, &akeep_, &control_, &info, NULL);
if(scaling_type_ == 1)
control_.scaling = 3; // use mc64 from ordering
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: PREDICTED nfactor %d, maxfront %d\n",
info.num_factor, info.maxfront);
if (HaveIpData()) {
IpData().TimingStats().LinearSystemSymbolicFactorization().End();
}
if (info.flag==6 || info.flag==-7) {
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"In Ma97SolverInterface::Factorization: "
"Singular system, estimated rank %d of %d\n",
info.matrix_rank, ndim_);
return SYMSOLVER_SINGULAR;
}
if (info.flag<0) return SYMSOLVER_FATAL_ERROR;
}
if (HaveIpData()) {
t1 = IpData().TimingStats().LinearSystemFactorization().TotalWallclockTime();
IpData().TimingStats().LinearSystemFactorization().Start();
}
ma97_factor(4, ia, ja, val_, &akeep_, &fkeep_, &control_, &info, scaling_);
//ma97_factor_solve(4, ia, ja, val_, nrhs, rhs_vals, ndim_, &akeep_, &fkeep_,
// &control_, &info, scaling_);
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: delays %d, nfactor %d, nflops %ld, maxfront %d\n",
info.num_delay, info.num_factor, info.num_flops, info.maxfront);
if (HaveIpData()) {
IpData().TimingStats().LinearSystemFactorization().End();
t2 = IpData().TimingStats().LinearSystemFactorization().TotalWallclockTime();
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"Ma97SolverInterface::Factorization: "
"ma97_factor_solve took %10.3f\n",
t2-t1);
}
if (info.flag==7 || info.flag==-7) {
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"In Ma97SolverInterface::Factorization: "
"Singular system, estimated rank %d of %d\n",
info.matrix_rank, ndim_);
return SYMSOLVER_SINGULAR;
}
for(int i=current_level_; i<3; i++) {
switch(switch_[i]) {
case SWITCH_NEVER:
case SWITCH_AT_START:
case SWITCH_ON_DEMAND:
// Nothing to do here
break;
case SWITCH_AT_START_REUSE:
rescale_ = false; // Scaled exactly once, never changed again
break;
case SWITCH_ON_DEMAND_REUSE:
if(i==current_level_ && rescale_) rescale_ = false;
break;
case SWITCH_NDELAY_REUSE:
case SWITCH_OD_ND_REUSE:
if(rescale_) numdelay_ = info.num_delay; // Need to do this before we reset rescale_
if(i==current_level_ && rescale_) rescale_ = false;
// Falls through to:
case SWITCH_NDELAY:
case SWITCH_OD_ND:
if(rescale_) numdelay_ = info.num_delay;
if(info.num_delay - numdelay_ > 0.05*ndim_) {
// number of delays has signficantly increased, so trigger
current_level_ = i;
scaling_type_ = scaling_val_[i];
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Enabling scaling %d due to excess delays\n", i);
rescale_ = true;
}
break;
}
}
if (info.flag<0) {
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"In Ma97SolverInterface::Factorization: "
"Unhandled error. info.flag = %d\n",
info.flag);
return SYMSOLVER_FATAL_ERROR;
}
if (check_NegEVals && info.num_neg!=numberOfNegEVals) {
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"In Ma97SolverInterface::Factorization: "
"info.num_neg = %d, but numberOfNegEVals = %d\n",
info.num_neg, numberOfNegEVals);
return SYMSOLVER_WRONG_INERTIA;
}
if (HaveIpData()) {
IpData().TimingStats().LinearSystemBackSolve().Start();
}
ma97_solve(0, nrhs, rhs_vals, ndim_, &akeep_, &fkeep_, &control_, &info);
if (HaveIpData()) {
IpData().TimingStats().LinearSystemBackSolve().End();
}
numneg_ = info.num_neg;
pivtol_changed_ = false;
}
else {
if (HaveIpData()) {
IpData().TimingStats().LinearSystemBackSolve().Start();
}
ma97_solve(0, nrhs, rhs_vals, ndim_, &akeep_, &fkeep_, &control_, &info);
if (HaveIpData()) {
IpData().TimingStats().LinearSystemBackSolve().End();
}
}
return SYMSOLVER_SUCCESS;
}
bool Ma97SolverInterface::IncreaseQuality()
{
for(int i=current_level_; i<3; i++) {
switch(switch_[i]) {
case SWITCH_ON_DEMAND:
case SWITCH_ON_DEMAND_REUSE:
case SWITCH_OD_ND:
case SWITCH_OD_ND_REUSE:
rescale_ = true;
current_level_ = i;
scaling_type_ = scaling_val_[i];
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"HSL_MA97: Enabling scaling %d due to failure of iterative refinement\n", current_level_);
break;
default: ;
}
}
if (control_.u >= umax_) {
return false;
}
pivtol_changed_ = true;
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"Indreasing pivot tolerance for HSL_MA97 from %7.2e ",
control_.u);
control_.u = Min(umax_, pow(control_.u,0.75));
Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
"to %7.2e.\n",
control_.u);
return true;
}
} // namespace Ipopt
#endif /* COINHSL_HAS_MA97 or HAVE_LINEARSOLVERLOADER */
| 39.534226 | 156 | 0.623104 | [
"object"
] |
aa7648a7a5c3f3025f302c881f55861d9f30afdf | 7,620 | cpp | C++ | Driver.cpp | RyanBabij/BigThink | 412db815ab6c764e11e766ee445590608b43a4e0 | [
"Unlicense"
] | null | null | null | Driver.cpp | RyanBabij/BigThink | 412db815ab6c764e11e766ee445590608b43a4e0 | [
"Unlicense"
] | null | null | null | Driver.cpp | RyanBabij/BigThink | 412db815ab6c764e11e766ee445590608b43a4e0 | [
"Unlicense"
] | null | null | null | // Boards can be either current game or possible future game state
// simple A-B tree: Pick best option for white, then pick best option for black.
// heuristics - Remove bad moves from tree.
// step 1 - random moves
// turn 1 - max 16
// turn 2 - max 16 etc.
//complexity: 16^n
// assume always promotion to queen
// idea: use tree to come up with move sets.
// use neural net to decide which states are best aka positional play
// however to start out we can use simple material points system.
// For neural net we can use pattern recognition on board states to recognise
// "good" and "bad" states, and then encourage/avoid transitioning to them.
// Alternatively we can abstract the game to a state hash and transition
// commands. We could break the state up into other useful information too,
// for example a piece's rank and file.
#define SLEEP_BETWEEN_TURNS
#define SLEEP_AMOUNT 0
#ifdef SLEEP_BETWEEN_TURNS
#define WILDCAT_WINDOWS
#include <System/Sleep/Sleep.hpp>
#endif
#define TIME_BETWEEN_TURNS 1000
#include <System/Time/Timer.hpp>
#include <File/FileManagerStatic.hpp>
#include <Container/Vector/Vector.hpp>
#include <Math/Random/RandomLehmer.hpp>
#include <Data/DataTools.hpp>
#include <iostream>
#include <string>
#include <time.h>
#define WHITE true
#define BLACK false
// board states for analysis.
#define WHITE_CHECK 0b10000000
#define WHITE_CHECKMATE 0b01000000
#define WHITE_NO_KING 0b00100000
#define BLACK_CHECK 0b00001000
#define BLACK_CHECKMATE 0b00000100
#define BLACK_NO_KING 0b00000010
#define STALEMATE_MOVEMENT 0b00001000
#define STALEMATE_MATERIAL 0b00000100
// pieces
#define WPAWN 244
#define BPAWN 245
#define WROOK 'r'
#define BROOK 'R'
#define WKNIGHT 'n'
#define BKNIGHT 'N'
#define WBISHOP 'b'
#define BBISHOP 'B'
#define WQUEEN 'q'
#define BQUEEN 'Q'
#define WKING 'k'
#define BKING 'K'
// We should convert the team defines to enum
//enum eTeam {WHITE, BLACK, BOTH};
RandomLehmer rng;
#include "Piece.hpp"
#include "Board.hpp"
Board mainBoard;
std::string gameLog = "";
#define LOG_GAMES false
int moveBlackRandom()
{
if ( mainBoard.randomMove(BLACK) == false )
{
// black is unable to move
// if we are in check, this is checkmate
if (mainBoard.boardStatus() != 0)
{
std::cout<<"Black is in checkmate, white wins.\n";
return 1;
}
else
{
std::cout<<"Stalemate\n";
return 2;
}
}
return 0;
}
int moveBlackGreedy()
{
if ( mainBoard.greedyMove(BLACK) == false )
{
// black is unable to move
// if we are in check, this is checkmate
if (mainBoard.boardStatus() != 0)
{
std::cout<<"Black is in checkmate, white wins.\n";
return 1;
}
else
{
std::cout<<"Stalemate\n";
return 2;
}
}
return 0;
}
int moveBlackDepth(int _depth, int _breadth)
{
if ( mainBoard.depthMove(BLACK, _depth, _breadth) == false )
{
// black is unable to move
// if we are in check, this is checkmate
if (mainBoard.boardStatus() != 0)
{
std::cout<<"Black is in checkmate, white wins.\n";
return 1;
}
else
{
std::cout<<"Stalemate\n";
return 2;
}
}
return 0;
}
void printScore()
{
std::cout<<"Material scores: "<<mainBoard.getMaterialScore(WHITE)-1000
<<" / "<<mainBoard.getMaterialScore(BLACK)-1000<<"\n";
}
void printBoard(bool _log=true)
{
std::cout<<mainBoard.getState(true)<<"\n\n";
if (_log && LOG_GAMES)
{
gameLog+=mainBoard.getState(true)+"\n\n";
}
}
Timer turnTimer;
int aiPlay()
{
turnTimer.init();
// play entire game until somebody wins
int i=1;
while (true)
{
std::cout<<"\n\nTurn: "<<i++<<"\n";
gameLog+="\n\nTurn: "+DataTools::toString(i-1)+"\n\n";
printBoard();
if (mainBoard.hasState(STALEMATE_MATERIAL))
{
std::cout<<"Stalemate: Lack of material.\n";
return 0;
}
if ( mainBoard.hasState(WHITE_CHECK) )
{
std::cout<<"White is in check/checkmate.\n";
gameLog+="White is in check/checkmate.\n";
}
else if ( mainBoard.boardStatus() == 2 )
{
std::cout<<"Stalemate.\n";
gameLog+="Stalemate.\n";
return 0;
}
if (mainBoard.hasKing(WHITE) == false)
{
std::cout<<"White king is ded.\n";
return 0;
}
// if ( mainBoard.randomMove(WHITE) == false )
// {
// std::cout<<"White is unable to move.\n";
// return 0;
// }
//mainBoard.materialMove(WHITE);
//mainBoard.materialDepthMove(WHITE, 2);
if (mainBoard.greedyMove(WHITE) == false )
{
std::cout<<"White cannot move. Stalemate/checkmate.\n";
return 0;
}
// analysis
printBoard();
printScore();
if (mainBoard.hasState(STALEMATE_MATERIAL))
{
std::cout<<"Stalemate: Lack of material.\n";
return 0;
}
if (mainBoard.hasKing(BLACK) == false)
{
std::cout<<"Black king is ded.\n";
return 0;
}
turnTimer.init();
turnTimer.start();
if (moveBlackDepth(1,999) != 0)
{
std::cout<<"White wins\n";
return 0;
}
turnTimer.update();
while (turnTimer.uSeconds < TIME_BETWEEN_TURNS)
{
sleep(100);
}
printScore();
#ifdef SLEEP_BETWEEN_TURNS
//sleep(SLEEP_AMOUNT);
#endif
}
// finished
std::cout<<"Writing game log\n";
FileManagerStatic::writeFreshString(gameLog,"gamelog.txt");
return 0;
}
int main (int narg, char ** arg)
{
rng.seed(time(NULL));
mainBoard.reset();
return aiPlay();
std::cout<<"\n\nBigThink chess engine\n";
std::cout<<"Enter 4 digits to make move.\n";
std::cout<<" a - let AI move\n";
std::cout<<" b - let AI play full game\n";
int currentTurn=0;
while(++currentTurn<100)
{
std::string input;
printBoard();
// command options
// a - AI turn
// b - full AI vs AI game
// [4 digits from 0-7] - make move if valid.
// s - skip turn for white
std::cout<<"Enter command:\n";
std::cin>>input;
while (std::cin.fail())
{
std::cout<<"Invalid input, try again.\n";
std::cin.clear();
std::cin.ignore();
input = "";
--currentTurn;
}
// process input here.
if (input.find('b') != std::string::npos)
{
// std::ios_base::sync_with_stdio(false);
// std::cin.tie(NULL);
return aiPlay();
}
if (input.find('s') != std::string::npos)
{
std::cout<<"Skip turn\n";
if (moveBlackRandom() != 0)
{
return 0;
}
}
else if (input.find('a') != std::string::npos)
{
std::cout<<"AI turn\n";
mainBoard.randomMove(WHITE);
// analysis
printBoard();
if ( mainBoard.hasKing(BLACK)==false )
{
std::cout<<"White wins\n";
return 0;
}
mainBoard.randomMove(BLACK);
printBoard();
if ( mainBoard.hasKing(WHITE)==false )
{
std::cout<<"Black wins\n";
return 0;
}
}
else
{
// process normally.
// strip the first 4 numbers we find in the string.
// valid input is 4 numbers from 0-7. Anything else is ignored.
int digit[4]={-1};
int currentDigit = 0;
for (unsigned int i=0;i<input.size();++i)
{
if (std::isdigit(input[i]))
{
int d = DataTools::toInt(input[i]);
if (d >= 0 && d < 8)
{
digit[currentDigit] = DataTools::toInt(input[i]);
++currentDigit;
}
if (currentDigit==4)
{
break;
}
}
}
// process digits
if (currentDigit == 4)
{
if (mainBoard.move(digit[0],digit[1],digit[2],digit[3]))
{
printBoard();
printScore();
std::cout<<"\n*** Black to move ***\n\n";
if (moveBlackRandom() != 0)
{
return 0;
}
//mainBoard.materialMove(BLACK);
//mainBoard.materialDepthMove(BLACK,2);
printScore();
}
}
else
{
std::cout<<"Error: Invalid input.\n";
}
}
}
return 0;
} | 19.488491 | 80 | 0.627428 | [
"vector"
] |
aa7667c78472afd45375bc42852c246d198fd6ef | 9,951 | cxx | C++ | dsmcFoamPlusGpu-master/applications/utilities/postProcessing/graphics/PV4Readers/PV4blockMeshReader/PV4blockMeshReader/vtkPV4blockMeshReader.cxx | Jootiinha/IC-dsmcFoam | f46bb7307e4d3dd7b3eace50603713e153ce72c1 | [
"MIT"
] | 3 | 2020-11-25T06:32:42.000Z | 2021-12-20T21:35:15.000Z | dsmcFoamPlusGpu-master/applications/utilities/postProcessing/graphics/PV4Readers/PV4blockMeshReader/PV4blockMeshReader/vtkPV4blockMeshReader.cxx | Jootiinha/IC-dsmcFoam | f46bb7307e4d3dd7b3eace50603713e153ce72c1 | [
"MIT"
] | null | null | null | dsmcFoamPlusGpu-master/applications/utilities/postProcessing/graphics/PV4Readers/PV4blockMeshReader/PV4blockMeshReader/vtkPV4blockMeshReader.cxx | Jootiinha/IC-dsmcFoam | f46bb7307e4d3dd7b3eace50603713e153ce72c1 | [
"MIT"
] | 2 | 2020-11-25T06:32:52.000Z | 2021-12-20T21:35:37.000Z | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "vtkPV4blockMeshReader.h"
#include "pqApplicationCore.h"
#include "pqRenderView.h"
#include "pqServerManagerModel.h"
// VTK includes
#include "vtkCallbackCommand.h"
#include "vtkDataArraySelection.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkObjectFactory.h"
#include "vtkSMRenderViewProxy.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStringArray.h"
// OpenFOAM includes
#include "vtkPV4blockMesh.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
vtkStandardNewMacro(vtkPV4blockMeshReader);
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
vtkPV4blockMeshReader::vtkPV4blockMeshReader()
{
Debug = 0;
vtkDebugMacro(<<"Constructor");
SetNumberOfInputPorts(0);
FileName = NULL;
foamData_ = NULL;
ShowPointNumbers = 1;
UpdateGUI = 0;
BlockSelection = vtkDataArraySelection::New();
CurvedEdgesSelection = vtkDataArraySelection::New();
// Setup the selection callback to modify this object when an array
// selection is changed.
SelectionObserver = vtkCallbackCommand::New();
SelectionObserver->SetCallback
(
&vtkPV4blockMeshReader::SelectionModifiedCallback
);
SelectionObserver->SetClientData(this);
BlockSelection->AddObserver
(
vtkCommand::ModifiedEvent,
this->SelectionObserver
);
CurvedEdgesSelection->AddObserver
(
vtkCommand::ModifiedEvent,
this->SelectionObserver
);
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
vtkPV4blockMeshReader::~vtkPV4blockMeshReader()
{
vtkDebugMacro(<<"Deconstructor");
if (foamData_)
{
// remove point numbers
updatePointNumbersView(false);
delete foamData_;
}
if (FileName)
{
delete [] FileName;
}
BlockSelection->RemoveObserver(this->SelectionObserver);
CurvedEdgesSelection->RemoveObserver(this->SelectionObserver);
SelectionObserver->Delete();
BlockSelection->Delete();
}
// * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * //
// Do everything except set the output info
int vtkPV4blockMeshReader::RequestInformation
(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector
)
{
vtkDebugMacro(<<"RequestInformation");
if (Foam::vtkPV4blockMesh::debug)
{
cout<<"REQUEST_INFORMATION\n";
}
if (!FileName)
{
vtkErrorMacro("FileName has to be specified!");
return 0;
}
int nInfo = outputVector->GetNumberOfInformationObjects();
if (Foam::vtkPV4blockMesh::debug)
{
cout<<"RequestInformation with " << nInfo << " item(s)\n";
for (int infoI = 0; infoI < nInfo; ++infoI)
{
outputVector->GetInformationObject(infoI)->Print(cout);
}
}
if (!foamData_)
{
foamData_ = new Foam::vtkPV4blockMesh(FileName, this);
}
else
{
foamData_->updateInfo();
}
// might need some other type of error handling
// {
// vtkErrorMacro("could not find valid OpenFOAM blockMesh");
//
// // delete foamData and flag it as fatal error
// delete foamData_;
// foamData_ = NULL;
// return 0;
// }
return 1;
}
// Set the output info
int vtkPV4blockMeshReader::RequestData
(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector
)
{
vtkDebugMacro(<<"RequestData");
if (!FileName)
{
vtkErrorMacro("FileName has to be specified!");
return 0;
}
// catch previous error
if (!foamData_)
{
vtkErrorMacro("Reader failed - perhaps no mesh?");
return 0;
}
int nInfo = outputVector->GetNumberOfInformationObjects();
if (Foam::vtkPV4blockMesh::debug)
{
cout<<"RequestData with " << nInfo << " item(s)\n";
for (int infoI = 0; infoI < nInfo; ++infoI)
{
outputVector->GetInformationObject(infoI)->Print(cout);
}
}
vtkMultiBlockDataSet* output = vtkMultiBlockDataSet::SafeDownCast
(
outputVector->GetInformationObject(0)->Get
(
vtkMultiBlockDataSet::DATA_OBJECT()
)
);
if (Foam::vtkPV4blockMesh::debug)
{
cout<< "update output with "
<< output->GetNumberOfBlocks() << " blocks\n";
}
foamData_->Update(output);
updatePointNumbersView(ShowPointNumbers);
// Do any cleanup on the OpenFOAM side
foamData_->CleanUp();
return 1;
}
void vtkPV4blockMeshReader::SetShowPointNumbers(const int val)
{
if (ShowPointNumbers != val)
{
ShowPointNumbers = val;
updatePointNumbersView(ShowPointNumbers);
}
}
void vtkPV4blockMeshReader::updatePointNumbersView(const bool show)
{
pqApplicationCore* appCore = pqApplicationCore::instance();
// need to check this, since our destructor calls this
if (!appCore)
{
return;
}
// Server manager model for querying items in the server manager
pqServerManagerModel* smModel = appCore->getServerManagerModel();
if (!smModel || !foamData_)
{
return;
}
// Get all the pqRenderView instances
QList<pqRenderView*> renderViews = smModel->findItems<pqRenderView*>();
for (int viewI=0; viewI<renderViews.size(); ++viewI)
{
foamData_->renderPointNumbers
(
renderViews[viewI]->getRenderViewProxy()->GetRenderer(),
show
);
}
// use refresh here?
}
void vtkPV4blockMeshReader::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDebugMacro(<<"PrintSelf");
this->Superclass::PrintSelf(os,indent);
os << indent << "File name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
foamData_->PrintSelf(os, indent);
}
// ----------------------------------------------------------------------
// Block selection list control
vtkDataArraySelection* vtkPV4blockMeshReader::GetBlockSelection()
{
vtkDebugMacro(<<"GetBlockSelection");
return BlockSelection;
}
int vtkPV4blockMeshReader::GetNumberOfBlockArrays()
{
vtkDebugMacro(<<"GetNumberOfBlockArrays");
return BlockSelection->GetNumberOfArrays();
}
const char* vtkPV4blockMeshReader::GetBlockArrayName(int index)
{
vtkDebugMacro(<<"GetBlockArrayName");
return BlockSelection->GetArrayName(index);
}
int vtkPV4blockMeshReader::GetBlockArrayStatus(const char* name)
{
vtkDebugMacro(<<"GetBlockArrayStatus");
return BlockSelection->ArrayIsEnabled(name);
}
void vtkPV4blockMeshReader::SetBlockArrayStatus
(
const char* name,
int status
)
{
vtkDebugMacro(<<"SetBlockArrayStatus");
if (status)
{
BlockSelection->EnableArray(name);
}
else
{
BlockSelection->DisableArray(name);
}
}
// ----------------------------------------------------------------------
// CurvedEdges selection list control
vtkDataArraySelection* vtkPV4blockMeshReader::GetCurvedEdgesSelection()
{
vtkDebugMacro(<<"GetCurvedEdgesSelection");
return CurvedEdgesSelection;
}
int vtkPV4blockMeshReader::GetNumberOfCurvedEdgesArrays()
{
vtkDebugMacro(<<"GetNumberOfCurvedEdgesArrays");
return CurvedEdgesSelection->GetNumberOfArrays();
}
const char* vtkPV4blockMeshReader::GetCurvedEdgesArrayName(int index)
{
vtkDebugMacro(<<"GetCurvedEdgesArrayName");
return CurvedEdgesSelection->GetArrayName(index);
}
int vtkPV4blockMeshReader::GetCurvedEdgesArrayStatus(const char* name)
{
vtkDebugMacro(<<"GetCurvedEdgesArrayStatus");
return CurvedEdgesSelection->ArrayIsEnabled(name);
}
void vtkPV4blockMeshReader::SetCurvedEdgesArrayStatus
(
const char* name,
int status
)
{
vtkDebugMacro(<<"SetCurvedEdgesArrayStatus");
if (status)
{
CurvedEdgesSelection->EnableArray(name);
}
else
{
CurvedEdgesSelection->DisableArray(name);
}
}
// ----------------------------------------------------------------------
void vtkPV4blockMeshReader::SelectionModifiedCallback
(
vtkObject*,
unsigned long,
void* clientdata,
void*
)
{
static_cast<vtkPV4blockMeshReader*>(clientdata)->Modified();
}
int vtkPV4blockMeshReader::FillOutputPortInformation
(
int port,
vtkInformation* info
)
{
if (port == 0)
{
return this->Superclass::FillOutputPortInformation(port, info);
}
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet");
return 1;
}
// ************************************************************************* //
| 23.692857 | 79 | 0.616119 | [
"mesh",
"object",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.