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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa769c17ba945b84db2faad4521ed29eb3753876 | 12,985 | hpp | C++ | src/cgi/include/computeCoreIdentity.hpp | TaskeHAMANO/FastANI | cddf65688767740d35c841dc3e622709358c7b98 | [
"Apache-2.0"
] | null | null | null | src/cgi/include/computeCoreIdentity.hpp | TaskeHAMANO/FastANI | cddf65688767740d35c841dc3e622709358c7b98 | [
"Apache-2.0"
] | null | null | null | src/cgi/include/computeCoreIdentity.hpp | TaskeHAMANO/FastANI | cddf65688767740d35c841dc3e622709358c7b98 | [
"Apache-2.0"
] | null | null | null | /**
* @file computeCoreIdentity.hpp
* @author Chirag Jain <cjain7@gatech.edu>
*/
#ifndef CGI_IDENTITY_HPP
#define CGI_IDENTITY_HPP
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <fstream>
#include <omp.h>
//Own includes
#include "map/include/base_types.hpp"
#include "cgi/include/cgid_types.hpp"
//External includes
#include "common/prettyprint.hpp"
namespace cgi
{
/**
* @brief Use reference sketch's sequence to file (genome) mapping
* and revise reference ids to genome id
* @param[in/out] shortResults
*/
void reviseRefIdToGenomeId(std::vector<MappingResult_CGI> &shortResults, skch::Sketch &refSketch)
{
for(auto &e : shortResults)
{
auto referenceSequenceId = e.refSequenceId;
auto upperRangeIter = std::upper_bound(refSketch.sequencesByFileInfo.begin(),
refSketch.sequencesByFileInfo.end(),
referenceSequenceId);
e.genomeId = std::distance(refSketch.sequencesByFileInfo.begin(), upperRangeIter);
}
}
/**
* @brief output blast tabular mappings for visualization
* @param[in] parameters algorithm parameters
* @param[in] results bidirectional mappings
* @param[in] mapper mapper object used for mapping
* @param[in] refSketch reference sketch
* @param[in] queryFileNo query genome is parameters.querySequences[queryFileNo]
* @param[in] fileName file name where results will be reported
*/
void outputVisualizationFile(skch::Parameters ¶meters,
std::vector<MappingResult_CGI> &mappings_2way,
skch::Map &mapper,
skch::Sketch &refSketch,
uint64_t queryFileNo,
std::string &fileName)
{
std::ofstream outstrm(fileName + ".visual", std::ios::app);
//Shift offsets for converting from local (to contig) to global (to genome)
std::vector <skch::offset_t> queryOffsetAdder (mapper.metadata.size());
std::vector <skch::offset_t> refOffsetAdder (refSketch.metadata.size());
for(int i = 0; i < mapper.metadata.size(); i++)
{
if(i == 0)
queryOffsetAdder[i] = 0;
else
queryOffsetAdder[i] = queryOffsetAdder[i-1] + mapper.metadata[i-1].len;
}
for(int i = 0; i < refSketch.metadata.size(); i++)
{
if(i == 0)
refOffsetAdder[i] = 0;
else
refOffsetAdder[i] = refOffsetAdder[i-1] + refSketch.metadata[i-1].len;
}
//Report all mappings that contribute to core-genome identity estimate
//Format the output to blast tabular way (outfmt 6)
for(auto &e : mappings_2way)
{
outstrm << parameters.querySequences[queryFileNo]
<< "\t" << parameters.refSequences[e.genomeId]
<< "\t" << e.nucIdentity
<< "\t" << "NA"
<< "\t" << "NA"
<< "\t" << "NA"
<< "\t" << e.queryStartPos + queryOffsetAdder[e.querySeqId]
<< "\t" << e.queryStartPos + parameters.minReadLength - 1 + queryOffsetAdder[e.querySeqId]
<< "\t" << e.refStartPos + refOffsetAdder[e.refSequenceId]
<< "\t" << e.refStartPos + parameters.minReadLength - 1 + refOffsetAdder[e.refSequenceId]
<< "\t" << "NA"
<< "\t" << "NA"
<< "\n";
}
}
/**
* @brief compute and report AAI/ANI
* @param[in] parameters algorithm parameters
* @param[in] results mapping results
* @param[in] mapper mapper object used for mapping
* @param[in] refSketch reference sketch
* @param[in] totalQueryFragments count of total sequence fragments in query genome
* @param[in] queryFileNo query genome is parameters.querySequences[queryFileNo]
* @param[in] fileName file name where results will be reported
* @param[out] CGI_ResultsVector FastANI results
*/
void computeCGI(skch::Parameters ¶meters,
skch::MappingResultsVector_t &results,
skch::Map &mapper,
skch::Sketch &refSketch,
uint64_t totalQueryFragments,
uint64_t queryFileNo,
std::string &fileName,
std::vector<cgi::CGI_Results> &CGI_ResultsVector
)
{
//Vector to save relevant fields from mapping results
std::vector<MappingResult_CGI> shortResults;
shortResults.reserve(results.size());
///Parse map results and save fields which we need
// reference id (R), query id (Q), estimated identity (I)
for(auto &e : results)
{
shortResults.emplace_back(MappingResult_CGI{
e.refSeqId,
0, //this value will be revised to genome id
e.querySeqId,
e.refStartPos,
e.queryStartPos,
e.refStartPos/(parameters.minReadLength - 20),
e.nucIdentity
});
}
/*
* NOTE: We assume single file contains the sequences for single genome
* We revise reference sequence id to genome (or file) id
*/
reviseRefIdToGenomeId(shortResults, refSketch);
//We need best reciprocal identity match for each genome, query pair
std::vector<MappingResult_CGI> mappings_1way;
std::vector<MappingResult_CGI> mappings_2way;
///1. Code below fetches best identity match for each genome, query pair
//For each query sequence, best match in the reference is preserved
{
//Sort the vector shortResults
std::sort(shortResults.begin(), shortResults.end(), cmp_query_bucket);
for(auto &e : shortResults)
{
if(mappings_1way.empty())
mappings_1way.push_back(e);
else if ( !(
e.genomeId == mappings_1way.back().genomeId &&
e.querySeqId == mappings_1way.back().querySeqId))
{
mappings_1way.emplace_back(e);
}
else
{
mappings_1way.back() = e;
}
}
}
///2. Now, we compute 2-way ANI
//For each mapped region, and within a reference bin bucket, single best query mapping is preserved
{
std::sort(mappings_1way.begin(), mappings_1way.end(), cmp_refbin_bucket);
for(auto &e : mappings_1way)
{
if(mappings_2way.empty())
mappings_2way.push_back(e);
else if ( !(
e.refSequenceId == mappings_2way.back().refSequenceId &&
e.mapRefPosBin == mappings_2way.back().mapRefPosBin))
{
mappings_2way.emplace_back(e);
}
else
{
mappings_2way.back() = e;
}
}
}
{
if(parameters.visualize)
{
outputVisualizationFile(parameters, mappings_2way, mapper, refSketch, queryFileNo, fileName);
}
}
//Do average for ANI/AAI computation
//mappings_2way should be sorted by genomeId
for(auto it = mappings_2way.begin(); it != mappings_2way.end();)
{
skch::seqno_t currentGenomeId = it->genomeId;
//Bucket by genome id
auto rangeEndIter = std::find_if(it, mappings_2way.end(), [&](const MappingResult_CGI& e)
{
return e.genomeId != currentGenomeId;
} );
float sumIdentity = 0.0;
for(auto it2 = it; it2 != rangeEndIter; it2++)
{
sumIdentity += it2->nucIdentity;
}
//Save the result
CGI_Results currentResult;
currentResult.qryGenomeId = queryFileNo;
currentResult.refGenomeId = currentGenomeId;
currentResult.countSeq = std::distance(it, rangeEndIter);
currentResult.totalQueryFragments = totalQueryFragments;
currentResult.identity = sumIdentity/currentResult.countSeq;
CGI_ResultsVector.push_back(currentResult);
//Advance the iterator it
it = rangeEndIter;
}
}
/**
* @brief output FastANI results to file
* @param[in] parameters algorithm parameters
* @param[in] CGI_ResultsVector results
* @param[in] fileName file name where results will be reported
*/
void outputCGI(skch::Parameters ¶meters,
std::vector<cgi::CGI_Results> &CGI_ResultsVector,
std::string &fileName)
{
//sort result by identity
std::sort(CGI_ResultsVector.rbegin(), CGI_ResultsVector.rend());
std::ofstream outstrm(fileName);
//Report results
for(auto &e : CGI_ResultsVector)
{
if(e.countSeq >= parameters.minFragments)
{
outstrm << parameters.querySequences[e.qryGenomeId]
<< "\t" << parameters.refSequences[e.refGenomeId]
<< "\t" << e.identity
<< "\t" << e.countSeq
<< "\t" << e.totalQueryFragments
<< "\n";
}
}
outstrm.close();
}
/**
* @brief output FastANI results as lower triangular matrix
* @param[in] parameters algorithm parameters
* @param[in] CGI_ResultsVector results
* @param[in] fileName file name where results will be reported
*/
void outputPhylip(skch::Parameters ¶meters,
std::vector<cgi::CGI_Results> &CGI_ResultsVector,
std::string &fileName)
{
std::unordered_map <std::string, int> genome2Int; // name of genome -> integer
std::unordered_map <int, std::string> genome2Int_rev; // integer -> name of genome
//Assign unique index to the set of query and reference genomes
for(auto &e : parameters.querySequences)
{
auto id = genome2Int.size();
if( genome2Int.find(e) == genome2Int.end() )
{
genome2Int [e] = id;
genome2Int_rev [id] = e;
}
}
for(auto &e : parameters.refSequences)
{
auto id = genome2Int.size();
if( genome2Int.find(e) == genome2Int.end() )
{
genome2Int [e] = id;
genome2Int_rev [id] = e;
}
}
int totalGenomes = genome2Int.size();
//create a square 2-d matrix
std::vector< std::vector<float> > fastANI_matrix (totalGenomes, std::vector<float> (totalGenomes, 0.0));
//transform FastANI results into 3-tuples
for(auto &e : CGI_ResultsVector)
{
if(e.countSeq >= parameters.minFragments)
{
int qGenome = genome2Int [ parameters.querySequences[e.qryGenomeId] ];
int rGenome = genome2Int [ parameters.refSequences[e.refGenomeId] ];
if (qGenome != rGenome) //ignore if both genomes are same
{
if (qGenome > rGenome)
{
if (fastANI_matrix[qGenome][rGenome] > 0)
fastANI_matrix[qGenome][rGenome] = (fastANI_matrix[qGenome][rGenome] + e.identity)/2;
else
fastANI_matrix[qGenome][rGenome] = e.identity;
}
else
{
if (fastANI_matrix[rGenome][qGenome] > 0)
fastANI_matrix[rGenome][qGenome] = (fastANI_matrix[rGenome][qGenome] + e.identity)/2;
else
fastANI_matrix[rGenome][qGenome] = e.identity;
}
}
}
}
std::ofstream outstrm(fileName + ".matrix");
outstrm << totalGenomes << "\n";
//Report matrix
for (int i = 0; i < totalGenomes; i++)
{
//output genome name
outstrm << genome2Int_rev[i];
for (int j = 0; j < i; j++)
{
//output ani values
//average if computed twice
std::string val = fastANI_matrix[i][j] > 0.0 ? std::to_string (fastANI_matrix[i][j]) : "NA";
outstrm << "\t" << val;
}
outstrm << "\n";
}
outstrm.close();
}
/**
* @brief generate multiple parameter objects from one
* @details purpose it to divide the list of reference genomes
* into as many buckets as there are threads
* @param[in] parameters
* @param[out] parameters_split
*/
void splitReferenceGenomes(skch::Parameters ¶meters,
std::vector <skch::Parameters> ¶meters_split)
{
for (int i = 0; i < parameters.threads; i++)
{
parameters_split[i] = parameters;
//update the reference genomes list
parameters_split[i].refSequences.clear();
//assign ref. genome to threads in round-robin fashion
for (int j = 0; j < parameters.refSequences.size(); j++)
{
if (j % parameters.threads == i)
parameters_split[i].refSequences.push_back (parameters.refSequences[j]);
}
}
}
/**
* @brief update thread local reference genome ids to global ids
* @param[in/out] CGI_ResultsVector
*/
void correctRefGenomeIds (std::vector<cgi::CGI_Results> &CGI_ResultsVector)
{
int tid = omp_get_thread_num();
int thread_count = omp_get_num_threads();
for (auto &e : CGI_ResultsVector)
e.refGenomeId = e.refGenomeId * thread_count + tid;
}
}
#endif
| 32.061728 | 109 | 0.594532 | [
"object",
"vector",
"transform"
] |
aa7820ec1438169f8e5b3decadffd476906fde7b | 7,184 | cxx | C++ | smtk/session/polygon/operators/TweakEdge.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 40 | 2015-02-21T19:55:54.000Z | 2022-01-06T13:13:05.000Z | smtk/session/polygon/operators/TweakEdge.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 127 | 2015-01-15T20:55:45.000Z | 2021-08-19T17:34:15.000Z | smtk/session/polygon/operators/TweakEdge.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 27 | 2015-03-04T14:17:51.000Z | 2021-12-23T01:05:42.000Z | //=============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=============================================================================
#include "smtk/session/polygon/operators/TweakEdge.h"
#include "smtk/session/polygon/Resource.h"
#include "smtk/session/polygon/internal/Model.h"
#include "smtk/session/polygon/internal/Model.txx"
#include "smtk/io/Logger.h"
#include "smtk/model/Face.h"
#include "smtk/model/Vertex.h"
#include "smtk/operation/MarkGeometry.h"
#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"
#include "smtk/attribute/DoubleItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/StringItem.h"
#include "smtk/session/polygon/TweakEdge_xml.h"
namespace smtk
{
namespace session
{
namespace polygon
{
TweakEdge::Result TweakEdge::operateInternal()
{
auto edgeItem = this->parameters()->associations();
auto pointsItem = this->parameters()->findDouble("points");
auto coordinatesItem = this->parameters()->findInt("coordinates");
auto promoteItem = this->parameters()->findInt("promote");
smtk::model::Edge src(edgeItem->valueAs<smtk::model::Entity>());
if (!src.isValid())
{
smtkErrorMacro(this->log(), "Input edge was invalid.");
return this->createResult(smtk::operation::Operation::Outcome::FAILED);
}
smtk::session::polygon::Resource::Ptr resource =
std::static_pointer_cast<smtk::session::polygon::Resource>(src.component()->resource());
if (!resource)
return this->createResult(smtk::operation::Operation::Outcome::FAILED);
internal::edge::Ptr storage = resource->findStorage<internal::edge>(src.entity());
internal::pmodel* pmod = storage->parentAs<internal::pmodel>();
if (!storage || !pmod)
{
smtkErrorMacro(
this->log(), "Input edge was not part of its parent model (or not a polygon-session edge).");
return this->createResult(smtk::operation::Operation::Outcome::FAILED);
}
bool ok = true;
std::set<int> splits(promoteItem->begin(), promoteItem->end());
int numCoordsPerPt = coordinatesItem->value(0);
std::size_t npts = pointsItem->numberOfValues() / numCoordsPerPt; // == #pts / #coordsPerPt
if (npts < 2)
{
smtkErrorMacro(
this->log(),
"Not enough points to form an edge (" << pointsItem->numberOfValues() << " coordinates at "
<< numCoordsPerPt << " per point => " << npts
<< " points)");
return this->createResult(smtk::operation::Operation::Outcome::FAILED);
}
if (!splits.empty())
{
std::set<int>::iterator sit;
std::ostringstream derp;
bool bad = false;
derp << "Ignoring invalid split-point indices: ";
for (sit = splits.begin(); sit != splits.end() && *sit < 0; ++sit)
{
derp << " " << *sit;
std::set<int>::iterator tmp = sit;
++sit;
splits.erase(tmp);
bad = true;
--sit;
}
std::set<int>::reverse_iterator rsit;
for (rsit = splits.rbegin(); rsit != splits.rend() && *rsit >= static_cast<int>(npts); ++rsit)
{
derp << " " << *rsit;
std::set<int>::iterator tmp = --rsit.base();
++rsit;
splits.erase(tmp);
bad = true;
--rsit;
}
if (bad)
{
smtkWarningMacro(this->log(), derp.str());
}
}
smtk::model::EntityRefArray modified; // includes edge and perhaps eventually faces.
smtk::model::Edges edgeCreated;
smtk::model::Vertices verticesCreated;
// Done checking input. Perform operation.
ok &= pmod->tweakEdge(src, numCoordsPerPt, pointsItem->begin(), pointsItem->end(), modified);
// Split the edge as requested by the user:
std::vector<internal::vertex::Ptr> promotedVerts;
std::vector<internal::PointSeq::const_iterator> splitLocs;
internal::PointSeq& epts(storage->points());
internal::PointSeq::const_iterator ptit = epts.begin();
int last = 0;
for (std::set<int>::iterator promit = splits.begin(); promit != splits.end(); ++promit)
{
std::advance(ptit, *promit - last);
last = *promit;
if (!!pmod->pointId(*ptit))
{
continue; // skip points that are already model vertices (should only happen at start/end)
}
smtk::model::Vertex pv = pmod->findOrAddModelVertex(resource, *ptit);
verticesCreated.push_back(pv);
promotedVerts.push_back(resource->findStorage<internal::vertex>(pv.entity()));
splitLocs.push_back(ptit);
std::cout << " " << ptit->x() << " " << ptit->y() << "\n";
}
smtk::model::EntityRefArray edgesAdded;
smtk::model::EntityRefArray expunged;
if (!splitLocs.empty())
{
smtkInfoMacro(this->log(), "Splitting tweaked edge at " << splitLocs.size() << " places.");
if (!pmod->splitModelEdgeAtModelVertices(
resource, storage, promotedVerts, splitLocs, edgesAdded, m_debugLevel))
{
smtkErrorMacro(this->log(), "Could not split edge.");
ok = false;
}
if (!edgesAdded.empty())
{
expunged.push_back(src);
}
edgeCreated.insert(edgeCreated.end(), edgesAdded.begin(), edgesAdded.end());
}
if (m_debugLevel > 0)
{
for (smtk::model::Edges::iterator eCrit = edgeCreated.begin(); eCrit != edgeCreated.end();
++eCrit)
{
smtkOpDebug("Created " << eCrit->name() << ".");
}
for (auto vCrit = verticesCreated.begin(); vCrit != verticesCreated.end(); ++vCrit)
{
smtkOpDebug("Created " << vCrit->name() << ".");
}
for (smtk::model::EntityRefArray::iterator moit = modified.begin(); moit != modified.end();
++moit)
{
smtkOpDebug("Modified " << moit->name() << ".");
}
for (smtk::model::EntityRefArray::iterator epit = expunged.begin(); epit != expunged.end();
++epit)
{
smtkOpDebug("Expunged " << epit->name() << ".");
}
}
Result opResult;
if (ok)
{
opResult = this->createResult(smtk::operation::Operation::Outcome::SUCCEEDED);
smtk::attribute::ComponentItem::Ptr createdItem = opResult->findComponent("created");
for (auto& c : verticesCreated)
{
createdItem->appendValue(c.component());
}
for (auto& c : edgeCreated)
{
createdItem->appendValue(c.component());
}
smtk::attribute::ComponentItem::Ptr modifiedItem = opResult->findComponent("modified");
for (auto& m : modified)
{
modifiedItem->appendValue(m.component());
}
smtk::attribute::ComponentItem::Ptr expungedItem = opResult->findComponent("expunged");
for (auto& e : expunged)
{
expungedItem->appendValue(e.component());
}
operation::MarkGeometry(resource).markResult(opResult);
}
else
{
opResult = this->createResult(smtk::operation::Operation::Outcome::FAILED);
}
return opResult;
}
const char* TweakEdge::xmlDescription() const
{
return TweakEdge_xml;
}
} // namespace polygon
} //namespace session
} // namespace smtk
| 31.787611 | 99 | 0.62848 | [
"vector",
"model"
] |
aa8805dad466852b89c943014add77469a2db675 | 1,481 | cpp | C++ | Codeforces/484div2/C.cpp | transcompany/Training | d9ff0454a1171a46a8b81af5024f76d362d8e547 | [
"MIT"
] | null | null | null | Codeforces/484div2/C.cpp | transcompany/Training | d9ff0454a1171a46a8b81af5024f76d362d8e547 | [
"MIT"
] | null | null | null | Codeforces/484div2/C.cpp | transcompany/Training | d9ff0454a1171a46a8b81af5024f76d362d8e547 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define pb push_back
const int maxn = 1e5 + 5;
int n;
vector<int> adj[maxn];
int dp[maxn][2];
void dfs(int u, int p = -1) {
int tot = 0;
int cnt = 0;
int state = 1;
int canrem = 0;
for (auto v : adj[u]) {
if (v == p) continue;
dfs(v, u);
if (~dp[v][0]) {
tot += dp[v][0];
canrem++;
} else {
state++;
tot += dp[v][1];
}
cnt++;
}
if (cnt == 0) {
// cout << u << endl;
dp[u][1] = 0;
dp[u][0] = -1;
return;
}
if (state % 2) {
dp[u][1] = canrem + tot;
dp[u][0] = -1;
if (canrem) {
for (auto v : adj[u]) {
if (v == p || !~dp[v][0] || !~dp[v][1]) continue;
int rem = tot - dp[v][0];
rem += dp[v][1];
rem += canrem - 1;
dp[u][0] = max(dp[u][0], rem);
}
}
} else {
// if (u == 3) cout << canrem << ' ' << tot << endl;
dp[u][0] = canrem + tot;
dp[u][1] = -1;
if (canrem) {
for (auto v : adj[u]) {
if (v == p || !~dp[v][0] || !~dp[v][1]) continue;
int rem = tot - dp[v][0];
rem += dp[v][1];
rem += canrem - 1;
dp[u][1] = max(dp[u][1], rem);
}
}
}
}
int main() {
cin >> n;
rep(i, 0, n - 1) {
int x, y;
cin >> x >> y;
x--; y--;
adj[x].pb(y);
adj[y].pb(x);
}
dfs(0);
// cout << dp[9][0] << endl;
cout << dp[0][0];
return 0;
}
| 17.22093 | 57 | 0.390277 | [
"vector"
] |
aa8868305563f6b2051aaa9b9dc7ce786a67f9c9 | 4,840 | cpp | C++ | src/mongo/scripting/mozjs/db.cpp | MartinNeupauer/mongo | 6cc2dfe7edd312b8596355edef454e15988e350e | [
"Apache-2.0"
] | 1 | 2019-05-15T03:41:50.000Z | 2019-05-15T03:41:50.000Z | src/mongo/scripting/mozjs/db.cpp | MartinNeupauer/mongo | 6cc2dfe7edd312b8596355edef454e15988e350e | [
"Apache-2.0"
] | 2 | 2021-03-26T00:01:11.000Z | 2021-03-26T00:02:19.000Z | src/mongo/scripting/mozjs/db.cpp | MartinNeupauer/mongo | 6cc2dfe7edd312b8596355edef454e15988e350e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/scripting/mozjs/db.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/scripting/mozjs/idwrapper.h"
#include "mongo/scripting/mozjs/implscope.h"
#include "mongo/scripting/mozjs/internedstring.h"
#include "mongo/scripting/mozjs/objectwrapper.h"
#include "mongo/scripting/mozjs/valuereader.h"
#include "mongo/scripting/mozjs/valuewriter.h"
namespace mongo {
namespace mozjs {
const char* const DBInfo::className = "DB";
void DBInfo::getProperty(JSContext* cx,
JS::HandleObject obj,
JS::HandleId id,
JS::MutableHandleValue vp) {
// 2nd look into real values, may be cached collection object
if (!vp.isUndefined()) {
auto scope = getScope(cx);
auto opContext = scope->getOpContext();
if (opContext && vp.isObject()) {
ObjectWrapper o(cx, vp);
}
return;
}
JS::RootedObject parent(cx);
if (!JS_GetPrototype(cx, obj, &parent))
uasserted(ErrorCodes::JSInterpreterFailure, "Couldn't get prototype");
ObjectWrapper parentWrapper(cx, parent);
if (parentWrapper.hasOwnField(id)) {
parentWrapper.getValue(id, vp);
return;
}
IdWrapper idw(cx, id);
// if starts with '_' we dont return collection, one must use getCollection()
if (idw.isString()) {
JSStringWrapper jsstr;
auto sname = idw.toStringData(&jsstr);
if (sname.size() == 0 || sname[0] == '_') {
return;
}
}
// no hit, create new collection
JS::RootedValue getCollection(cx);
parentWrapper.getValue(InternedString::getCollection, &getCollection);
if (!(getCollection.isObject() && JS_ObjectIsFunction(cx, getCollection.toObjectOrNull()))) {
uasserted(ErrorCodes::BadValue, "getCollection is not a function");
}
JS::AutoValueArray<1> args(cx);
idw.toValue(args[0]);
JS::RootedValue coll(cx);
ObjectWrapper(cx, obj).callMethod(getCollection, args, &coll);
uassert(16861,
"getCollection returned something other than a collection",
getScope(cx)->getProto<DBCollectionInfo>().instanceOf(coll));
// cache collection for reuse, don't enumerate
ObjectWrapper(cx, obj).defineProperty(id, coll, 0);
vp.set(coll);
}
void DBInfo::construct(JSContext* cx, JS::CallArgs args) {
auto scope = getScope(cx);
if (args.length() != 2)
uasserted(ErrorCodes::BadValue, "db constructor requires 2 arguments");
for (unsigned i = 0; i < args.length(); ++i) {
uassert(ErrorCodes::BadValue,
"db initializer called with undefined argument",
!args.get(i).isUndefined());
}
JS::RootedObject thisv(cx);
scope->getProto<DBInfo>().newObject(&thisv);
ObjectWrapper o(cx, thisv);
o.setValue(InternedString::_mongo, args.get(0));
o.setValue(InternedString::_name, args.get(1));
std::string dbName = ValueWriter(cx, args.get(1)).toString();
if (!NamespaceString::validDBName(dbName, NamespaceString::DollarInDbNameBehavior::Allow))
uasserted(ErrorCodes::BadValue,
str::stream() << "[" << dbName << "] is not a valid database name");
args.rval().setObjectOrNull(thisv);
}
} // namespace mozjs
} // namespace mongo
| 34.571429 | 97 | 0.675826 | [
"object"
] |
aa8f78bfe61bc0e3c6754ebe7f29f5d33a97835a | 10,607 | cpp | C++ | ugene/src/corelibs/U2Gui/src/OpenViewTask.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/corelibs/U2Gui/src/OpenViewTask.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/corelibs/U2Gui/src/OpenViewTask.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "OpenViewTask.h"
#include <U2Core/LoadDocumentTask.h>
#include <U2Core/LoadRemoteDocumentTask.h>
#include <U2Core/AppContext.h>
#include <U2Core/ProjectModel.h>
#include <U2Core/Log.h>
#include <U2Core/ResourceTracker.h>
#include <U2Core/DocumentModel.h>
#include <U2Core/GObjectReference.h>
#include <U2Core/GObject.h>
#include <U2Core/IOAdapter.h>
#include <U2Core/GHints.h>
#include <U2Core/AppResources.h>
#include <U2Core/BaseDocumentFormats.h>
#include <U2Core/U2SafePoints.h>
#include <U2Core/GObjectSelection.h>
#include <U2Core/GObjectTypes.h>
#include <U2Core/GObjectUtils.h>
#include <U2Core/GObjectRelationRoles.h>
#include <U2Core/AnnotationTableObject.h>
#include <U2Gui/ObjectViewModel.h>
#include <QtCore/QFileInfo>
#include <QtGui/QApplication>
namespace U2 {
/* TRANSLATOR U2::LoadUnloadedDocumentTask */
//////////////////////////////////////////////////////////////////////////
// LoadUnloadedDocumentAndOpenViewTask
LoadUnloadedDocumentAndOpenViewTask::LoadUnloadedDocumentAndOpenViewTask(Document* d) :
Task("", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText)
{
loadUnloadedTask = new LoadUnloadedDocumentTask(d);
setUseDescriptionFromSubtask(true);
setVerboseLogMode(true);
setTaskName(tr("Load document: '%1'").arg(d->getName()));
addSubTask(loadUnloadedTask);
}
static Task* createOpenViewTask(const MultiGSelection& ms) {
QList<GObjectViewFactory*> fs = AppContext::getObjectViewFactoryRegistry()->getAllFactories();
QList<GObjectViewFactory*> ls;
foreach(GObjectViewFactory* f, fs) {
//check if new view can be created
if (f->canCreateView(ms)) {
ls.append(f);
}
}
if (ls.size() > 1) {
GObjectViewFactory* f = AppContext::getObjectViewFactoryRegistry()->getFactoryById(GObjectViewFactory::SIMPLE_TEXT_FACTORY);
if (ls.contains(f)) {
// ignore auxiliary text data
ls.removeAll(f);
}
}
if (ls.size() == 1) {
GObjectViewFactory* f = ls.first();
Task* t = f->createViewTask(ms, true);
return t;
}
return NULL;
}
QList<Task*> LoadUnloadedDocumentAndOpenViewTask::onSubTaskFinished(Task* subTask) {
QList<Task*> res;
if (subTask != loadUnloadedTask || hasError() || isCanceled()) {
return res;
}
// look if saved state can be loaded
Document* doc = loadUnloadedTask->getDocument();
assert(doc->isLoaded());
res.append( new OpenViewTask(doc));
return res;
}
//////////////////////////////////////////////////////////////////////////
// OpenViewTask
OpenViewTask::OpenViewTask( Document* d )
: Task("Open view", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText ), doc(d)
{
assert(doc != NULL);
assert(doc->isLoaded());
}
void OpenViewTask::prepare()
{
QList<Task*> res;
//if any of existing views has added an object from the document -> do not open new view
const QList<GObject*>& docObjects = doc->getObjects();
if (!GObjectViewUtils::findViewsWithAnyOfObjects(docObjects).isEmpty()) {
return;
}
//try open new view
GObjectSelection os; os.addToSelection(docObjects);
MultiGSelection ms; ms.addSelection(&os);
QList<GObjectViewState*> sl = GObjectViewUtils::selectStates(ms, AppContext::getProject()->getGObjectViewStates());
if (sl.size() == 1) {
GObjectViewState* state = sl.first();
GObjectViewFactory* f = AppContext::getObjectViewFactoryRegistry()->getFactoryById(state->getViewFactoryId());
assert(f!=NULL);
res.append(f->createViewTask(state->getViewName(), state->getStateData()));
} else {
Task* openViewTask = createOpenViewTask(ms);
if (openViewTask!=NULL) {
openViewTask->setSubtaskProgressWeight(0);
res.append(openViewTask);
}
}
if (res.isEmpty()) {
// no view can be opened -> check special case: loaded object contains annotations associated with sequence
// -> load sequence and open view for it;
foreach(GObject* obj, doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE)) {
QList<GObjectRelation> rels = obj->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE);
if (rels.isEmpty()) {
continue;
}
const GObjectRelation& rel = rels.first();
Document* seqDoc = AppContext::getProject()->findDocumentByURL(rel.ref.docUrl);
if (seqDoc!=NULL) {
if (seqDoc->isLoaded()) { //try open sequence view
GObject* seqObj = seqDoc->findGObjectByName(rel.ref.objName);
if (seqObj!=NULL && seqObj->getGObjectType() == GObjectTypes::SEQUENCE) {
GObjectSelection os2; os2.addToSelection(seqObj);
MultiGSelection ms2; ms2.addSelection(&os2);
Task* openViewTask = createOpenViewTask(ms2);
if (openViewTask!=NULL) {
openViewTask->setSubtaskProgressWeight(0);
res.append(openViewTask);
}
}
} else { //try load doc and open sequence view
AppContext::getTaskScheduler()->registerTopLevelTask(new LoadUnloadedDocumentAndOpenViewTask(seqDoc));
}
}
if (!res.isEmpty()) { //one view is ok
break;
}
}
}
foreach(Task* task, res) {
addSubTask(task);
}
}
//////////////////////////////////////////////////////////////////////////
LoadRemoteDocumentAndOpenViewTask::LoadRemoteDocumentAndOpenViewTask( const QString& accId, const QString& dbName )
: Task("LoadRemoteDocumentAndOpenView", TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), loadRemoteDocTask(NULL)
{
accNumber = accId;
databaseName = dbName;
}
LoadRemoteDocumentAndOpenViewTask::LoadRemoteDocumentAndOpenViewTask( const GUrl& url )
: Task(tr("Load remote document and open view"), TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), loadRemoteDocTask(NULL)
{
docUrl = url;
}
LoadRemoteDocumentAndOpenViewTask::LoadRemoteDocumentAndOpenViewTask(const QString& accId, const QString& dbName, const QString & fp)
: Task(tr("Load remote document and open view"), TaskFlags_NR_FOSCOE | TaskFlag_MinimizeSubtaskErrorText), loadRemoteDocTask(NULL) {
accNumber = accId;
databaseName = dbName;
fullpath = fp;
}
void LoadRemoteDocumentAndOpenViewTask::prepare()
{
if (docUrl.isEmpty()) {
loadRemoteDocTask = new LoadRemoteDocumentTask(accNumber, databaseName, fullpath);
} else {
loadRemoteDocTask = new LoadRemoteDocumentTask(docUrl);
}
addSubTask(loadRemoteDocTask);
}
QList<Task*> LoadRemoteDocumentAndOpenViewTask::onSubTaskFinished( Task* subTask) {
QList<Task*> subTasks;
if (subTask->hasError()) {
return subTasks;
}
if (subTask->isCanceled()) {
return subTasks;
}
if (subTask == loadRemoteDocTask ) {
// hack for handling errors with http requests with bad resource id
Document * d = loadRemoteDocTask->getDocument();
if(d->getDocumentFormatId() == BaseDocumentFormats::PLAIN_TEXT) {
setError(tr("Cannot find %1 in %2 database").arg(accNumber).arg(databaseName));
// try to delete file with response that was created
QFile::remove(d->getURLString());
// and remove it from downloaded cache
RecentlyDownloadedCache * cache = AppContext::getRecentlyDownloadedCache();
if( cache != NULL ) {
cache->remove(d->getURLString());
}
return subTasks;
}
QString fullPath = loadRemoteDocTask->getLocalUrl();
Project* proj = AppContext::getProject();
if (proj == NULL) {
subTasks.append(AppContext::getProjectLoader()->openWithProjectTask(fullPath));
} else {
Document* doc = loadRemoteDocTask->takeDocument();
SAFE_POINT(doc != NULL, "loadRemoteDocTask->takeDocument() returns NULL!", subTasks);
if (proj->getDocuments().contains(doc)) {
if (doc->isLoaded()) {
subTasks.append(new OpenViewTask(doc));
} else {
subTasks.append(new LoadUnloadedDocumentAndOpenViewTask(doc));
}
} else {
// Add document to project
subTasks.append(new AddDocumentTask(doc));
subTasks.append(new LoadUnloadedDocumentAndOpenViewTask(doc));
}
}
}
return subTasks;
}
AddDocumentAndOpenViewTask::AddDocumentAndOpenViewTask( Document* doc, const AddDocumentTaskConfig& conf)
:Task(tr("Opening view for document: %1").arg(doc->getURL().fileName()), TaskFlags_NR_FOSE_COSC)
{
setMaxParallelSubtasks(1);
addSubTask(new AddDocumentTask(doc, conf));
}
AddDocumentAndOpenViewTask::AddDocumentAndOpenViewTask( DocumentProviderTask* dp, const AddDocumentTaskConfig& conf )
:Task(tr("Opening view for document: %1").arg(dp->getDocumentDescription()), TaskFlags_NR_FOSE_COSC)
{
setMaxParallelSubtasks(1);
addSubTask(new AddDocumentTask(dp, conf));
}
QList<Task*> AddDocumentAndOpenViewTask::onSubTaskFinished(Task* t) {
QList<Task*> res;
AddDocumentTask* addTask = qobject_cast<AddDocumentTask*>(t);
if (addTask != NULL && !addTask->getStateInfo().isCoR()) {
Document* doc = addTask->getDocument();
assert(doc != NULL);
res << new LoadUnloadedDocumentAndOpenViewTask(doc);
}
return res;
}
}//namespace
| 35.713805 | 134 | 0.64514 | [
"object"
] |
aa926f66aed1d69a62ae638a0d4d3ef6643ddf8e | 2,986 | cpp | C++ | src/RaZ/Render/RenderGraph.cpp | Sausty/RaZ | 211cc1c0c4a7374520a3141fc069b7717e2e5e0f | [
"MIT"
] | null | null | null | src/RaZ/Render/RenderGraph.cpp | Sausty/RaZ | 211cc1c0c4a7374520a3141fc069b7717e2e5e0f | [
"MIT"
] | null | null | null | src/RaZ/Render/RenderGraph.cpp | Sausty/RaZ | 211cc1c0c4a7374520a3141fc069b7717e2e5e0f | [
"MIT"
] | null | null | null | #include "RaZ/Math/Transform.hpp"
#include "RaZ/Render/Camera.hpp"
#include "RaZ/Render/RenderGraph.hpp"
#include "RaZ/Render/RenderSystem.hpp"
namespace Raz {
bool RenderGraph::isValid() const {
if (!m_geometryPass.isValid())
return false;
for (const std::unique_ptr<RenderPass>& renderPass : m_nodes) {
if (!renderPass->isValid())
return false;
}
return true;
}
const Texture& RenderGraph::addTextureBuffer(unsigned int width, unsigned int height, int bindingIndex, ImageColorspace colorspace) {
return *m_buffers.emplace_back(std::make_unique<Texture>(width, height, bindingIndex, colorspace, false));
}
void RenderGraph::resizeViewport(unsigned int width, unsigned int height) {
for (std::unique_ptr<RenderPass>& renderPass : m_nodes)
renderPass->resizeWriteBuffers(width, height);
}
void RenderGraph::updateShaders() const {
for (const std::unique_ptr<RenderPass>& renderPass : m_nodes)
renderPass->getProgram().updateShaders();
}
void RenderGraph::execute(RenderSystem& renderSystem) const {
assert("Error: The render system needs a camera for the render graph to be executed." && (renderSystem.m_cameraEntity != nullptr));
m_geometryPass.getProgram().use();
const Framebuffer& geometryFramebuffer = m_geometryPass.getFramebuffer();
if (!geometryFramebuffer.isEmpty())
geometryFramebuffer.bind();
auto& camera = renderSystem.m_cameraEntity->getComponent<Camera>();
auto& camTransform = renderSystem.m_cameraEntity->getComponent<Transform>();
Mat4f viewProjMat;
if (camTransform.hasUpdated()) {
if (camera.getCameraType() == CameraType::LOOK_AT) {
camera.computeLookAt(camTransform.getPosition());
} else {
camera.computeViewMatrix(camTransform.computeTranslationMatrix(true),
camTransform.getRotation().inverse());
}
camera.computeInverseViewMatrix();
const Mat4f& viewMat = camera.getViewMatrix();
viewProjMat = viewMat * camera.getProjectionMatrix();
renderSystem.sendCameraMatrices(viewProjMat);
camTransform.setUpdated(false);
} else {
viewProjMat = camera.getViewMatrix() * camera.getProjectionMatrix();
}
for (const Entity* entity : renderSystem.m_entities) {
if (entity->isEnabled()) {
if (entity->hasComponent<Mesh>() && entity->hasComponent<Transform>()) {
const Mat4f modelMat = entity->getComponent<Transform>().computeTransformMatrix();
const ShaderProgram& geometryProgram = m_geometryPass.getProgram();
geometryProgram.sendUniform("uniModelMatrix", modelMat);
geometryProgram.sendUniform("uniMvpMatrix", modelMat * viewProjMat);
entity->getComponent<Mesh>().draw(geometryProgram);
}
}
}
if (renderSystem.hasCubemap())
renderSystem.getCubemap().draw(camera);
geometryFramebuffer.unbind();
for (const RenderPass* renderPass : m_geometryPass.getChildren())
renderPass->execute(geometryFramebuffer);
}
} // namespace Raz
| 31.765957 | 133 | 0.721031 | [
"mesh",
"render",
"transform"
] |
aa932ee5a94dfa046f7daa9ca9141d80bc8d1a48 | 6,048 | cpp | C++ | src/guidance.v2.02/libs/phylogeny/seqContainerTreeMap.cpp | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 4 | 2021-07-18T05:20:20.000Z | 2022-01-03T10:22:33.000Z | src/guidance.v2.02/libs/phylogeny/seqContainerTreeMap.cpp | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 1 | 2017-08-21T07:26:13.000Z | 2018-11-08T13:59:48.000Z | src/guidance.v2.02/libs/phylogeny/seqContainerTreeMap.cpp | jlanga/smsk_orthofinder | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 2 | 2021-07-18T05:20:26.000Z | 2022-03-31T18:23:31.000Z | // $Id: seqContainerTreeMap.cpp 12494 2014-08-06 15:54:00Z haim $
#include <stdlib.h>
#include "seqContainerTreeMap.h"
#include "logFile.h"
#include "treeUtil.h"
/********************************************************************************************
*********************************************************************************************/
void intersectNamesInTreeAndSequenceContainer(tree& et, sequenceContainer & sc, bool bLeavesOnly){
LOGnOUT(4,<<"\n intersectNames Tree vs Sequence. Before intersect numOfSeq= "<<sc.numberOfSeqs()<<" nunOfTaxa= "<<et.getLeavesNum()<<" Remove "<<abs(et.getLeavesNum() -sc.numberOfSeqs())<<" taxa"<<endl);
treeIterDownTopConst tIt(et);
vector<tree::nodeP> nodes2remove;
vector<int> seqIDs2remove;
//cout<<"tree names:"<<endl;
for (tree::nodeP mynode = tIt.first(); mynode != tIt.end(); mynode = tIt.next()) {
bool bFound = false;
bool bFound_more = false;
if (bLeavesOnly) {
if (mynode->isInternal())
continue;
}
sequenceContainer::constTaxaIterator it=sc.constTaxaBegin();
for (;it != sc.constTaxaEnd(); ++it)
{
string scName = it->name();
string treeNodeName = mynode->name();
if (it->name() == mynode->name())
{
if(bFound)
bFound_more = true;
bFound = true;
//break;
}
if (bFound_more == true)
{
string errMsg = "The taxID:\t";
errMsg += mynode->name();
errMsg += "\twas found again in the sequence file. Removed from sequence.";
LOGnOUT(4,<<errMsg<<endl);
seqIDs2remove.push_back(it->id());
bFound_more = false;
}
}
if (bFound == false)
{
string errMsg = "The taxID:\t";
errMsg += mynode->name();
errMsg += "\twas found in the tree file but not found in the sequence file. Removed from tree.";
LOGnOUT(4,<<errMsg<<endl);
nodes2remove.push_back(mynode);
}
}
for(int i=0; i<nodes2remove.size(); ++i){
et.removeLeaf(nodes2remove[i]);
}
sequenceContainer::constTaxaIterator myseq=sc.constTaxaBegin();
for (;myseq != sc.constTaxaEnd(); ++myseq){
bool bFound = false;
bool bFound_more = false;
for (tree::nodeP mynode = tIt.first(); mynode != tIt.end(); mynode = tIt.next()) {
if (bLeavesOnly)
{
if (mynode->isInternal())
continue;
}
if (myseq->name() == mynode->name())
{
if(bFound)
bFound_more = true;
bFound = true;
//break;
}
if (bFound_more == true)
{
string errMsg = "The taxID name:\t";
errMsg += myseq->name();
errMsg += "\twas found again in the tree file. Removed.";
LOGnOUT(4,<<errMsg<<endl);
nodes2remove.push_back(mynode);
bFound_more = false;
}
}
if (bFound == false)
{
string errMsg = "The taxID name:\t";
errMsg += myseq->name();
errMsg += "\twas found in the sequence file but not found in the tree file. Removed.";
LOGnOUT(4,<<errMsg<<endl);
seqIDs2remove.push_back(myseq->id());
}
}
for(int i=0; i<seqIDs2remove.size(); ++i){
sc.remove(seqIDs2remove[i]);
}
}
/********************************************************************************************
*********************************************************************************************/
//if bLeavesOnly == true then checks only leaves, otherwise the sequence container includes also internal nodes (as may be the result of simlations
void checkThatNamesInTreeAreSameAsNamesInSequenceContainer(const tree& et,const sequenceContainer & sc, bool bLeavesOnly){
treeIterDownTopConst tIt(et);
//cout<<"tree names:"<<endl;
for (tree::nodeP mynode = tIt.first(); mynode != tIt.end(); mynode = tIt.next()) {
bool bFound = false;
if (bLeavesOnly) {
if (mynode->isInternal())
continue;
}
sequenceContainer::constTaxaIterator it=sc.constTaxaBegin();
for (;it != sc.constTaxaEnd(); ++it)
{
string scName = it->name();
string treeNodeName = mynode->name();
if (it->name() == mynode->name())
{
bFound = true;
break;
}
}
if (bFound == false)
{
string errMsg = "The sequence name: ";
errMsg += mynode->name();
errMsg += " was found in the tree file but not found in the sequence file.\n";
errMsg += " Please, Re-run program with _intersectTreeAndSeq to produce new MSA and Tree.\n";
LOG(4,<<errMsg<<endl);
errorMsg::reportError(errMsg);
}
}
sequenceContainer::constTaxaIterator it=sc.constTaxaBegin();
for (;it != sc.constTaxaEnd(); ++it){
bool bFound = false;
for (tree::nodeP mynode = tIt.first(); mynode != tIt.end(); mynode = tIt.next()) {
if (bLeavesOnly)
{
if (mynode->isInternal())
continue;
}
if (it->name() == mynode->name())
{
bFound = true;
break;
}
}
if (bFound == false)
{
string errMsg = "The sequence name: ";
errMsg += it->name();
errMsg += " was found in the sequence file but not found in the tree file.\n";
errMsg += " Please, Re-run program with _intersectTreeAndSeq to produce new MSA and Tree.\n";
errorMsg::reportError(errMsg);
}
}
}
/********************************************************************************************
// input: a tree and a sequence-container containing all of the leaves sequences.
// output: fills sc_leaves with the sequences of the leaves only.
*********************************************************************************************/
void getLeavesSequences(const sequenceContainer& sc,
const tree& tr, sequenceContainer& sc_leaves) {
vector<string> leavesNames = getSequencesNames(tr);
vector<string>::iterator itr_leaves;
for (itr_leaves=leavesNames.begin();itr_leaves!=leavesNames.end();++itr_leaves) {
sequenceContainer::constTaxaIterator it_sc=sc.constTaxaBegin();
for (;it_sc != sc.constTaxaEnd(); ++it_sc) {
if (it_sc->name() == *(itr_leaves)) {
sc_leaves.add(*it_sc);
break;
}
}
}
if (tr.getLeavesNum() != sc_leaves.numberOfSeqs()) {
string errMsg = "getLeavesSequencese: the number of leaves is not equal to the number of leaves' sequences";
errorMsg::reportError(errMsg);
}
}
| 32.691892 | 204 | 0.583333 | [
"vector"
] |
aa9f6ba499dffca7a05a65a92041c275b22e8b25 | 66,077 | cpp | C++ | MMOCoreORB/src/server/zone/managers/structure/StructureManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/managers/structure/StructureManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/managers/structure/StructureManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
* StructureManager.cpp
*
* Created on: 01/08/2012
* Author: swgemu
*/
#include "StructureManager.h"
#include "engine/db/IndexDatabase.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "conf/ConfigManager.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/managers/gcw/GCWManager.h"
#include "server/zone/managers/object/ObjectManager.h"
#include "templates/tangible/SharedStructureObjectTemplate.h"
#include "templates/building/SharedBuildingObjectTemplate.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/zone/objects/tangible/deed/structure/StructureDeed.h"
#include "server/zone/objects/region/Region.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/player/sessions/PlaceStructureSession.h"
#include "server/zone/objects/player/sessions/DestroyStructureSession.h"
#include "server/zone/objects/player/sessions/PackupStructureSession.h"
#include "server/zone/objects/player/sessions/UnpackStructureSession.h"
#include "terrain/manager/TerrainManager.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/objects/region/CityRegion.h"
#include "server/zone/managers/city/CityManager.h"
#include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h"
#include "server/zone/objects/player/sui/transferbox/SuiTransferBox.h"
#include "server/zone/objects/player/sui/inputbox/SuiInputBox.h"
#include "server/zone/objects/player/sui/callbacks/StructurePayUncondemnMaintenanceSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/FindLostItemsSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/DeleteAllItemsSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/StructureStatusSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/StructureAssignDroidSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/NameStructureSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/StructurePayMaintenanceSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/StructureWithdrawMaintenanceSuiCallback.h"
#include "server/zone/objects/player/sui/callbacks/StructureSelectSignSuiCallback.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "terrain/layer/boundaries/BoundaryRectangle.h"
#include "tasks/DestroyStructureTask.h"
#include "tasks/DestroyPackedupStructureTask.h"
#include "server/zone/objects/intangible/PetControlDevice.h"
#include "server/zone/objects/intangible/StructureControlDevice.h"
#include "server/zone/managers/creature/PetManager.h"
#include "server/zone/objects/installation/harvester/HarvesterObject.h"
#include "server/zone/objects/player/sui/callbacks/FindLostItemsListSuiCallback.h"
namespace StorageManagerNamespace {
int indexCallback(DB *secondary, const DBT *key, const DBT *data, DBT *result) {
memset(result, 0, sizeof(DBT));
ObjectInputStream objectData;
LocalDatabase::uncompress(data->data, data->size, &objectData);
String zoneReference;
if (!Serializable::getVariable<String>(STRING_HASHCODE("SceneObject.zone"),
&zoneReference, &objectData)) {
return DB_DONOTINDEX;
} else {
auto data = (uint64*) malloc(sizeof(uint64)); //same size as an oid
*data = zoneReference.hashCode();
result->data = data;
result->size = sizeof(uint64);
result->flags = DB_DBT_APPMALLOC;
//Logger::console.info("setting new key " + String::valueOf(*data) + " in associate callback", true);
}
return 0;
}
}
StructureManager::StructureManager() : Logger("StructureManager") {
server = nullptr;
templateManager = TemplateManager::instance();
setGlobalLogging(true);
setLogging(false);
//Structure Packup Log
structurePackupLog.setLoggingName("Structure Packup Log");
StringBuffer structurePackupFileName;
structurePackupFileName << "log/structure/packup.log";
structurePackupLog.setFileLogger(structurePackupFileName.toString(), true);
structurePackupLog.setLogging(true);
//System Structure Packup Log
systemStructurePackupLog.setLoggingName("System Structure Packup Log");
StringBuffer systemStructurePackupFileName;
systemStructurePackupFileName << "log/structure/system_packup.log";
systemStructurePackupLog.setFileLogger(systemStructurePackupFileName.toString(), true);
systemStructurePackupLog.setLogging(true);
//Structure Destroy Log
structureDestroyLog.setLoggingName("Structure Destroy Log");
StringBuffer structureDestroyFileName;
structureDestroyFileName << "log/structure/structure_destroy.log";
structureDestroyLog.setFileLogger(structureDestroyFileName.toString(), true);
structureDestroyLog.setLogging(true);
}
IndexDatabase* StructureManager::createSubIndex() {
static auto initialized = [this] () -> IndexDatabase* { //this needs to run only once
auto dbManager = ObjectDatabaseManager::instance();
auto playerStructuresDatabase = dbManager->loadObjectDatabase("playerstructures", true);
auto playerStructuresDatabaseIndex = dbManager->loadIndexDatabase("playerstructuresindex", true);
fatal(playerStructuresDatabase && playerStructuresDatabaseIndex) << "Could not load the player structures databases.";
info(true) << "creating player structures index association";
playerStructuresDatabase->associate(playerStructuresDatabaseIndex, StorageManagerNamespace::indexCallback);
return playerStructuresDatabaseIndex;
} ();
fatal(initialized) << "Could not initialize player structures sub index.";
initialized->reloadParentAssociation(); //makes sure the thread local db handle reloads the association if needed
return initialized;
}
void StructureManager::loadPlayerStructures(const String& zoneName) {
info("Loading player structures for zone: " + zoneName);
auto playerStructuresDatabaseIndex = createSubIndex();
berkeley::CursorConfig config;
config.setReadUncommitted(true);
uint64 zoneHash = zoneName.hashCode();
IndexDatabaseIterator iterator(playerStructuresDatabaseIndex, config);
int i = 0;
uint64 objectID;
auto loadFunction = [this] (int& i, uint64 objectID, uint64 planet) {
//debug("loading 0x" + String::hexvalueOf(objectID) + " for planet 0x" + String::hexvalueOf(planet), true);
try {
auto object = server->getObject(objectID);
if (object == nullptr) {
error("Failed to deserialize structure with objectID: " + String::valueOf(objectID));
return;
}
++i;
if (object->isGCWBase()) {
Zone* zone = object->getZone();
if (zone != nullptr) {
GCWManager* gcwMan = zone->getGCWManager();
if (gcwMan != nullptr) {
gcwMan->registerGCWBase(cast<BuildingObject*>(object.get()), false);
}
}
}
if (ConfigManager::instance()->isProgressMonitorActivated())
printf("\r\tLoading player structures [%d] / [?]\t", i);
} catch (Exception& e) {
error("Database exception in StructureManager::loadPlayerStructures(): " + e.getMessage());
}
};
Timer loadTimer;
loadTimer.start();
Timer initialQueryPerf;
initialQueryPerf.start();
Timer iteratorPerf;
if (iterator.setKeyAndGetValue(zoneHash, objectID, nullptr)) {
initialQueryPerf.stop();
loadFunction(i, objectID, zoneHash);
iteratorPerf.start();
while (iterator.getNextKeyAndValue(zoneHash, objectID, nullptr)) {
iteratorPerf.stop();
loadFunction(i, objectID, zoneHash);
iteratorPerf.start();
}
iteratorPerf.stop();
}
auto elapsedMs = loadTimer.stopMs();
info(i > 0) << i << " player structures loaded for "
<< zoneName << " in "
<< elapsedMs << "ms "
<< "where the initial query took " << initialQueryPerf.getTotalTimeMs() << "ms "
<< "and iterator took " << iteratorPerf.getTotalTimeMs() << "ms.";
}
int StructureManager::getStructureFootprint(SharedStructureObjectTemplate* objectTemplate, int angle, float& l0, float& w0, float& l1, float& w1) {
if (objectTemplate == nullptr)
return 1;
const StructureFootprint* structureFootprint = objectTemplate->getStructureFootprint();
if (structureFootprint == nullptr)
return 1;
//float l = 5; //Along the x axis.
//float w = 5; //Along the y axis.
//if (structureFootprint->getRowSize() > structureFootprint->getColSize())
// angle = angle + 180;
float centerX = (structureFootprint->getCenterX() * 8) + 4;
float centerY = (structureFootprint->getCenterY() * 8) + 4;
//info ("centerX:" + String::valueOf(centerX) + " centerY:" + String::valueOf(centerY), true);
float topLeftX = -centerX;
float topLeftY = (structureFootprint->getRowSize() * 8 ) - centerY;
float bottomRightX = (8 * structureFootprint->getColSize() - centerX);
float bottomRightY = -centerY;
w0 = Math::min(topLeftX, bottomRightX);
l0 = Math::min(topLeftY, bottomRightY);
w1 = Math::max(topLeftX, bottomRightX);
l1 = Math::max(topLeftY, bottomRightY);
Matrix4 translationMatrix;
translationMatrix.setTranslation(0, 0, 0);
float rad = (float)(angle) * Math::DEG2RAD;
float cosRad = cos(rad);
float sinRad = sin(rad);
Matrix3 rot;
rot[0][0] = cosRad;
rot[0][2] = -sinRad;
rot[1][1] = 1;
rot[2][0] = sinRad;
rot[2][2] = cosRad;
Matrix4 rotateMatrix;
rotateMatrix.setRotationMatrix(rot);
Matrix4 moveAndRotate = (translationMatrix * rotateMatrix);
Vector3 pointBottom(w0, 0, l0);
Vector3 pointTop(w1, 0, l1);
Vector3 resultBottom = pointBottom * moveAndRotate;
Vector3 resultTop = pointTop * moveAndRotate;
w0 = Math::min(resultBottom.getX(), resultTop.getX());
l0 = Math::min(resultBottom.getZ(), resultTop.getZ());
w1 = Math::max(resultTop.getX(), resultBottom.getX());
l1 = Math::max(resultTop.getZ(), resultBottom.getZ());
//info("objectTemplate:" + objectTemplate->getFullTemplateString() + " :" + structureFootprint->toString(), true);
//info("angle:" + String::valueOf(angle) + " w0:" + String::valueOf(w0) + " l0:" + String::valueOf(l0) + " w1:" + String::valueOf(w1) + " l1:" + String::valueOf(l1), true);
return 0;
}
int StructureManager::placeStructureFromDeed(CreatureObject* creature, StructureDeed* deed, float x, float y, int angle) {
ManagedReference<Zone*> zone = creature->getZone();
//Already placing a structure?
if (zone == nullptr || creature->containsActiveSession(SessionFacadeType::PLACESTRUCTURE))
return 1;
ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager();
String serverTemplatePath = deed->getGeneratedObjectTemplate();
if (deed->getFaction() != 0 && creature->getFaction() != deed->getFaction()) {
creature->sendSystemMessage("You are not the correct faction");
return 1;
}
Reference<SharedStructureObjectTemplate*> serverTemplate =
dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));
//Check to see if this zone allows this structure.
if (serverTemplate == nullptr || !serverTemplate->isAllowedZone(zone->getZoneName())) {
creature->sendSystemMessage("@player_structure:wrong_planet"); //That deed cannot be used on this planet.
return 1;
}
if (!planetManager->isBuildingPermittedAt(x, y, creature)) {
creature->sendSystemMessage("@player_structure:not_permitted"); //Building is not permitted here.
return 1;
}
SortedVector<ManagedReference<ActiveArea*> > objects;
zone->getInRangeActiveAreas(x, y, &objects, true);
ManagedReference<CityRegion*> city;
for (int i = 0; i < objects.size(); ++i) {
ActiveArea* area = objects.get(i).get();
if (!area->isRegion())
continue;
city = dynamic_cast<Region*>(area)->getCityRegion().get();
if (city != nullptr)
break;
}
SortedVector<ManagedReference<QuadTreeEntry*> > inRangeObjects;
zone->getInRangeObjects(x, y, 128, &inRangeObjects, true, false);
float placingFootprintLength0 = 0, placingFootprintWidth0 = 0, placingFootprintLength1 = 0, placingFootprintWidth1 = 0;
if (!getStructureFootprint(serverTemplate, angle, placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1)) {
float x0 = x + placingFootprintWidth0;
float y0 = y + placingFootprintLength0;
float x1 = x + placingFootprintWidth1;
float y1 = y + placingFootprintLength1;
BoundaryRectangle placingFootprint(x0, y0, x1, y1);
//info("placing center x:" + String::valueOf(x) + " y:" + String::valueOf(y), true);
//info("placingFootprint x0:" + String::valueOf(x0) + " y0:" + String::valueOf(y0) + " x1:" + String::valueOf(x1) + " y1:" + String::valueOf(y1), true);
for (int i = 0; i < inRangeObjects.size(); ++i) {
SceneObject* scene = inRangeObjects.get(i).castTo<SceneObject*>();
if (scene == nullptr)
continue;
float l0 = -5; //Along the x axis.
float w0 = -5; //Along the y axis.
float l1 = 5;
float w1 = 5;
if (getStructureFootprint(dynamic_cast<SharedStructureObjectTemplate*>(scene->getObjectTemplate()), scene->getDirectionAngle(), l0, w0, l1, w1))
continue;
float xx0 = scene->getPositionX() + (w0 + 0.1);
float yy0 = scene->getPositionY() + (l0 + 0.1);
float xx1 = scene->getPositionX() + (w1 - 0.1);
float yy1 = scene->getPositionY() + (l1 - 0.1);
BoundaryRectangle rect(xx0, yy0, xx1, yy1);
//info("existing footprint xx0:" + String::valueOf(xx0) + " yy0:" + String::valueOf(yy0) + " xx1:" + String::valueOf(xx1) + " yy1:" + String::valueOf(yy1), true);
// check 4 points of the current rect
if (rect.containsPoint(x0, y0)
|| rect.containsPoint(x0, y1)
|| rect.containsPoint(x1, y0)
|| rect.containsPoint(x1, y1) ) {
//info("existing footprint contains placing point", true);
creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here..
return 1;
}
if (placingFootprint.containsPoint(xx0, yy0)
|| placingFootprint.containsPoint(xx0, yy1)
|| placingFootprint.containsPoint(xx1, yy0)
|| placingFootprint.containsPoint(xx1, yy1)
|| (xx0 == x0 && yy0 == y0 && xx1 == x1 && yy1 == y1)) {
//info("placing footprint contains existing point", true);
creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here.
return 1;
}
}
}
int rankRequired = serverTemplate->getCityRankRequired();
if (city == nullptr && rankRequired > 0) {
creature->sendSystemMessage("@city/city:build_no_city"); // You must be in a city to place that structure.
return 1;
}
if (city != nullptr) {
if (city->isZoningEnabled() && !city->hasZoningRights(creature->getObjectID())) {
creature->sendSystemMessage("@player_structure:no_rights"); //You don't have the right to place that structure in this city. The mayor or one of the city milita must grant you zoning rights first.
return 1;
}
if (rankRequired != 0 && city->getCityRank() < rankRequired) {
StringIdChatParameter param("city/city", "rank_req"); // The city must be at least rank %DI (%TO) in order for you to place this structure.
param.setDI(rankRequired);
param.setTO("city/city", "rank" + String::valueOf(rankRequired));
creature->sendSystemMessage(param);
return 1;
}
if (serverTemplate->isCivicStructure() && !city->isMayor(creature->getObjectID()) ) {
creature->sendSystemMessage("@player_structure:cant_place_civic");//"This structure must be placed within the borders of the city in which you are mayor."
return 1;
}
if (serverTemplate->isUniqueStructure() && city->hasUniqueStructure(serverTemplate->getServerObjectCRC())) {
creature->sendSystemMessage("@player_structure:cant_place_unique"); //This city can only support a single structure of this type.
return 1;
}
}
Locker _lock(deed, creature);
//Ensure that it is the correct deed, and that it is in a container in the creature's inventory.
if (!deed->isASubChildOf(creature)) {
creature->sendSystemMessage("@player_structure:no_possession"); //You no longer are in possession of the deed for this structure. Aborting construction.
return 1;
}
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost != nullptr) {
String abilityRequired = serverTemplate->getAbilityRequired();
if (!abilityRequired.isEmpty() && !ghost->hasAbility(abilityRequired)) {
creature->sendSystemMessage("@player_structure:" + abilityRequired);
return 1;
}
int lots = serverTemplate->getLotSize();
if (!ghost->hasLotsRemaining(lots)) {
StringIdChatParameter param("@player_structure:not_enough_lots");
param.setDI(lots);
creature->sendSystemMessage(param);
return 1;
}
}
//Validate that the structure can be placed at the given coordinates:
//Ensure that no other objects impede on this structures footprint, or overlap any city regions or no build areas.
//Make sure that the player has zoning rights in the area.
ManagedReference<PlaceStructureSession*> session = new PlaceStructureSession(creature, deed);
creature->addActiveSession(SessionFacadeType::PLACESTRUCTURE, session);
//Construct the structure.
session->constructStructure(x, y, angle);
//Remove the deed from it's container.
deed->destroyObjectFromWorld(true);
return 0;
}
StructureObject* StructureManager::placeStructure(CreatureObject* creature,
const String& structureTemplatePath, float x, float y, int angle, int persistenceLevel) {
ManagedReference<Zone*> zone = creature->getZone();
if (zone == nullptr)
return nullptr;
TerrainManager* terrainManager =
zone->getPlanetManager()->getTerrainManager();
SharedStructureObjectTemplate* serverTemplate =
dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(
structureTemplatePath.hashCode()));
if (serverTemplate == nullptr) {
info("server template is null");
return nullptr;
}
float z = zone->getHeight(x, y);
float floraRadius = serverTemplate->getClearFloraRadius();
bool snapToTerrain = serverTemplate->getSnapToTerrain();
Reference<const StructureFootprint*> structureFootprint =
serverTemplate->getStructureFootprint();
float w0 = -5; //Along the x axis.
float l0 = -5; //Along the y axis.
float l1 = 5;
float w1 = 5;
float zIncreaseWhenNoAvailableFootprint = 0.f; //TODO: remove this when it has been verified that all buildings have astructure footprint.
if (structureFootprint != nullptr) {
//If the angle is odd, then swap them.
getStructureFootprint(serverTemplate, angle, l0, w0, l1, w1);
} else {
if (!serverTemplate->isCampStructureTemplate())
warning(
"Structure with template '" + structureTemplatePath
+ "' has no structure footprint.");
zIncreaseWhenNoAvailableFootprint = 5.f;
}
if (floraRadius > 0 && !snapToTerrain)
z = terrainManager->getHighestHeight(x + w0, y + l0, x + w1, y + l1, 1)
+ zIncreaseWhenNoAvailableFootprint;
String strDatabase = "playerstructures";
bool bIsFactionBuilding = (serverTemplate->getGameObjectType()
== SceneObjectType::FACTIONBUILDING);
if (bIsFactionBuilding || serverTemplate->getGameObjectType() == SceneObjectType::DESTRUCTIBLE) {
strDatabase = "playerstructures";
}
ManagedReference<SceneObject*> obj =
ObjectManager::instance()->createObject(
structureTemplatePath.hashCode(), persistenceLevel, strDatabase);
if (obj == nullptr || !obj->isStructureObject()) {
if (obj != nullptr) {
Locker locker(obj);
obj->destroyObjectFromDatabase(true);
}
error(
"Failed to create structure with template: "
+ structureTemplatePath);
return nullptr;
}
StructureObject* structureObject = cast<StructureObject*>(obj.get());
Locker sLocker(structureObject);
structureObject->grantPermission("ADMIN", creature->getObjectID());
structureObject->setOwner(creature->getObjectID());
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost != nullptr) {
ghost->addOwnedStructure(structureObject);
}
if(structureObject->isTurret() || structureObject->isMinefield()){
structureObject->setFaction(creature->getFaction());
}
BuildingObject* buildingObject = nullptr;
if (structureObject->isBuildingObject()) {
buildingObject = cast<BuildingObject*>(structureObject);
if (buildingObject != nullptr)
buildingObject->createCellObjects();
}
structureObject->setPublicStructure(serverTemplate->isPublicStructure());
structureObject->initializePosition(x, z, y);
structureObject->rotate(angle);
zone->transferObject(structureObject, -1, true);
structureObject->createChildObjects();
structureObject->notifyStructurePlaced(creature);
return structureObject;
}
int StructureManager::destroyStructure(StructureObject* structureObject, bool playEffect, String reason) {
ManagedReference<CreatureObject*> creature = server->getObject(structureObject->getOwnerObjectID()).castTo<CreatureObject*>();
if (creature != nullptr && !reason.isEmpty()) {
StringBuffer msg;
msg << "Structure ID: " << structureObject->getObjectID() << " Owned By: " << creature->getFirstName() << " has been destroyed because " << reason;
structureDestroyLog.info(msg.toString());
}
if (structureObject->isPackedUp()) {
Reference<DestroyPackedupStructureTask*> task = new DestroyPackedupStructureTask(structureObject);
task->execute();
} else {
Reference<DestroyStructureTask*> task = new DestroyStructureTask(structureObject, playEffect);
task->execute();
}
return 0;
}
String StructureManager::getTimeString(uint32 timestamp) {
if( timestamp == 0 ){
return "";
}
static const String abbrvs[3] = { "minutes", "hours", "days" };
static const int intervals[3] = { 60, 3600, 86400 };
int values[3] = { 0, 0, 0 };
StringBuffer str;
for (int i = 2; i > -1; --i) {
values[i] = floor((float) timestamp / intervals[i]);
timestamp -= values[i] * intervals[i];
if (values[i] > 0) {
if (str.length() > 0){
str << ", ";
}
str << values[i] << " " << abbrvs[i];
}
}
return "(" + str.toString() + ")";
}
int StructureManager::declareResidence(CreatureObject* player, StructureObject* structureObject, bool isCityHall) {
if (!structureObject->isBuildingObject()) {
player->sendSystemMessage("@player_structure:residence_must_be_building"); //Your declared residence must be a building.
return 1;
}
PlayerObject* ghost = player->getPlayerObject();
if (!isCityHall && !player->checkCooldownRecovery("declare_residence") && !ghost->isPrivileged()) {
Time* timeremaining = player->getCooldownTime("declare_residence");
StringIdChatParameter params("player_structure", "change_residence_time"); //You cannot change residence for %NO hours.
params.setTO(String::valueOf(ceil(timeremaining->miliDifference() / -3600000.f)));
player->sendSystemMessage(params);
return 1;
}
ManagedReference<BuildingObject*> buildingObject = cast<BuildingObject*>(structureObject);
if (!buildingObject->isOwnerOf(player)) {
player->sendSystemMessage("@player_structure:declare_must_be_owner"); //You must be the owner of the building to declare residence.
return 1;
}
uint64 objectid = player->getObjectID();
uint64 declaredOidResidence = ghost->getDeclaredResidence();
ManagedReference<BuildingObject*> declaredResidence = server->getObject(declaredOidResidence).castTo<BuildingObject*>();
ManagedReference<CityRegion*> cityRegion = buildingObject->getCityRegion().get();
CityManager* cityManager = server->getCityManager();
if (declaredResidence != nullptr) {
if (declaredResidence == buildingObject) {
player->sendSystemMessage("@player_structure:already_residence"); //This building is already your residence.
return 1;
}
ManagedReference<CityRegion*> residentCity = declaredResidence->getCityRegion().get();
if (residentCity != nullptr) {
Locker lock(residentCity, player);
if (residentCity->isMayor(objectid)) {
player->sendSystemMessage("@city/city:mayor_residence_change"); //As a city Mayor, your residence is always the city hall of the city in which you are mayor. You cannot declare a new residence.
return 1;
}
cityManager->unregisterCitizen(residentCity, player);
}
player->sendSystemMessage("@player_structure:change_residence"); //You change your residence to this building.
} else {
player->sendSystemMessage("@player_structure:declared_residency"); //You have declared your residency here.
}
if (cityRegion != nullptr) {
Locker lock(cityRegion, player);
if (cityRegion->isMayor(objectid) && structureObject != cityRegion->getCityHall()) {
player->sendSystemMessage("@city/city:mayor_residence_change"); //As a city Mayor, your residence is always the city hall of the city in which you are mayor. You cannot declare a new residence.
return 1;
}
cityManager->registerCitizen(cityRegion, player);
}
//Set the characters home location to this structure.
ghost->setDeclaredResidence(buildingObject);
if(declaredResidence != nullptr) {
Locker oldLock(declaredResidence, player);
declaredResidence->setResidence(false);
}
Locker newLock(buildingObject,player);
buildingObject->setResidence(true);
player->addCooldown("declare_residence", 24 * 3600 * 1000); //1 day
return 0;
}
Reference<SceneObject*> StructureManager::getInRangeParkingGarage(SceneObject* obj, int range) {
ManagedReference<Zone*> zone = obj->getZone();
if (zone == nullptr)
return nullptr;
SortedVector<QuadTreeEntry*> closeSceneObjects;
CloseObjectsVector* closeObjectsVector = (CloseObjectsVector*) obj->getCloseObjects();
if (closeObjectsVector == nullptr) {
zone->getInRangeObjects(obj->getPositionX(), obj->getPositionY(), 128, &closeSceneObjects, true, false);
} else {
closeObjectsVector->safeCopyTo(closeSceneObjects);
}
for (int i = 0; i < closeSceneObjects.size(); ++i) {
SceneObject* scno = cast<SceneObject*>(closeSceneObjects.get(i));
if (scno == nullptr || scno == obj)
continue;
if (scno->isGarage() && scno->isInRange(obj, range))
return scno;
}
return nullptr;
}
int StructureManager::redeedStructure(CreatureObject* creature) {
ManagedReference<DestroyStructureSession*> session = creature->getActiveSession(SessionFacadeType::DESTROYSTRUCTURE).castTo<DestroyStructureSession*>();
if (session == nullptr)
return 0;
ManagedReference<StructureObject*> structureObject =
session->getStructureObject();
if (structureObject == nullptr)
return 0;
Locker _locker(structureObject);
ManagedReference<StructureDeed*> deed =
server->getObject(
structureObject->getDeedObjectID()).castTo<StructureDeed*>();
int maint = structureObject->getSurplusMaintenance();
int redeedCost = structureObject->getRedeedCost();
if (deed != nullptr && structureObject->isRedeedable()) {
Locker _lock(deed, structureObject);
ManagedReference<SceneObject*> inventory = creature->getSlottedObject(
"inventory");
bool isSelfPoweredHarvester = false;
HarvesterObject* harvester = structureObject.castTo<HarvesterObject*>();
if(harvester != nullptr)
isSelfPoweredHarvester = harvester->isSelfPowered();
if (inventory == nullptr || inventory->getCountableObjectsRecursive() > (inventory->getContainerVolumeLimit() - (isSelfPoweredHarvester ? 2 : 1))) {
if(isSelfPoweredHarvester) {
//This installation can not be destroyed because there is no room for the Self Powered Harvester Kit in your inventory.
creature->sendSystemMessage("@player_structure:inventory_full_selfpowered");
} else {
//This installation can not be redeeded because your inventory does not have room to put the deed.
creature->sendSystemMessage("@player_structure:inventory_full");
}
creature->sendSystemMessage("@player_structure:deed_reclaimed_failed"); //Structure destroy and deed reclaimed FAILED!
return session->cancelSession();
} else {
if(isSelfPoweredHarvester) {
Reference<SceneObject*> rewardSceno = server->createObject(STRING_HASHCODE("object/tangible/veteran_reward/harvester.iff"), 1);
if( rewardSceno == nullptr ){
creature->sendSystemMessage("@player_structure:deed_reclaimed_failed"); //Structure destroy and deed reclaimed FAILED!
return session->cancelSession();
}
// Transfer to player
if( !inventory->transferObject(rewardSceno, -1, false, true) ){ // Allow overflow
creature->sendSystemMessage("@player_structure:deed_reclaimed_failed"); //Structure destroy and deed reclaimed FAILED!
rewardSceno->destroyObjectFromDatabase(true);
return session->cancelSession();
}
harvester->setSelfPowered(false);
inventory->broadcastObject(rewardSceno, true);
creature->sendSystemMessage("@player_structure:selfpowered");
}
deed->setSurplusMaintenance(maint - redeedCost);
deed->setSurplusPower(structureObject->getSurplusPower());
structureObject->setDeedObjectID(0); //Set this to 0 so the deed doesn't get destroyed with the structure.
destroyStructure(structureObject, false, "the structure has been re deeded by the owner.");
inventory->transferObject(deed, -1, true);
inventory->broadcastObject(deed, true);
creature->sendSystemMessage("@player_structure:deed_reclaimed"); //Structure destroyed and deed reclaimed.
}
} else {
destroyStructure(structureObject, false, "the structure has been destroyed by the owner.");
creature->sendSystemMessage("@player_structure:structure_destroyed"); //Structured destroyed.
}
return session->cancelSession();
}
void StructureManager::promptDeleteAllItems(CreatureObject* creature,
StructureObject* structure) {
ManagedReference<SuiMessageBox*> sui = new SuiMessageBox(creature, 0x00);
sui->setUsingObject(structure);
sui->setPromptTitle("@player_structure:delete_all_items"); //Delete All Items
sui->setPromptText("@player_structure:delete_all_items_d"); //This command will delete every object in your house. Are you ABSOLUTELY sure you want to destroy every object in your house?
sui->setCancelButton(true, "@cancel");
sui->setCallback(new DeleteAllItemsSuiCallback(server));
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost != nullptr) {
ghost->addSuiBox(sui);
creature->sendMessage(sui->generateMessage());
}
}
void StructureManager::promptFindLostItems(CreatureObject* creature,
StructureObject* structure) {
ManagedReference<SuiListBox*> sui = new SuiListBox(creature, SuiWindowType::NONE, 0x00);
sui->setCallback(new FindLostItemsListSuiCallback(server));
sui->setUsingObject(structure);
sui->setPromptTitle("@player_structure:move_first_item"); //Find Lost Items
sui->setPromptText("This list contains all the objects inside this house. Select an object and click OK to have it moved to your location.");
Reference<BuildingObject*> build = cast<BuildingObject*>(structure);
for (uint32 i = 1; i <= build->getTotalCellNumber(); ++i) {
ManagedReference<CellObject*> cell = build->getCell(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
ManagedReference<SceneObject*> childObject = cell->getContainerObject(j);
if (!childObject->isTerminal() && !childObject->isVendor() && !childObject->isCreatureObject()) {
sui->addMenuItem(childObject->getDisplayedName(), childObject->getObjectID());
}
}
}
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost != nullptr) {
ghost->addSuiBox(sui);
creature->sendMessage(sui->generateMessage());
}
}
void StructureManager::moveFirstItemTo(CreatureObject* creature,
StructureObject* structure) {
if (!structure->isBuildingObject())
return;
ManagedReference<BuildingObject*> building =
cast<BuildingObject*>(structure);
Locker _lock(building, creature);
for (uint32 i = 1; i <= building->getTotalCellNumber(); ++i) {
ManagedReference<CellObject*> cell = building->getCell(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
ManagedReference<SceneObject*> childObject =
cell->getContainerObject(j);
if (childObject->isVendor())
continue;
//if (!building->containsChildObject(childObject) && !childObject->isCreatureObject()) {
if (creature->getParent() != nullptr
&& !building->containsChildObject(childObject)
&& !childObject->isCreatureObject()) {
if (creature->getParent().get()->getParent().get()
== childObject->getParent().get()->getParent().get()) {
childObject->teleport(creature->getPositionX(),
creature->getPositionZ(), creature->getPositionY(),
creature->getParentID());
creature->sendSystemMessage(
"@player_structure:moved_first_item"); //The first item in your house has been moved to your location.
}
return;
}
}
}
}
void StructureManager::reportStructureStatus(CreatureObject* creature,
StructureObject* structure) {
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr)
return;
//Close the window if it is already open.
ghost->closeSuiWindowType(SuiWindowType::STRUCTURE_STATUS);
ManagedReference<SuiListBox*> status = new SuiListBox(creature,
SuiWindowType::STRUCTURE_STATUS);
status->setPromptTitle("@player_structure:structure_status_t"); //Structure Status
status->setPromptText(
"@player_structure:structure_name_prompt "
+ structure->getDisplayedName()); //Structure Name:
if (structure->isPackedUp())
status->setUsingObject(structure->getControlDevice().get());
else
status->setUsingObject(structure);
status->setOkButton(true, "@refresh");
status->setCancelButton(true, "@cancel");
status->setCallback(new StructureStatusSuiCallback(server));
ManagedReference<SceneObject*> ownerObject = server->getObject(
structure->getOwnerObjectID());
if (ownerObject != nullptr && ownerObject->isCreatureObject()) {
CreatureObject* owner = cast<CreatureObject*>(ownerObject.get());
status->addMenuItem(
"@player_structure:owner_prompt " + owner->getFirstName());
}
uint64 declaredOidResidence = ghost->getDeclaredResidence();
ManagedReference<BuildingObject*> declaredResidence =
server->getObject(declaredOidResidence).castTo<BuildingObject*>();
if (declaredResidence == structure) {
status->addMenuItem("@player_structure:declared_residency"); //You have declared your residency here.
}
if (structure->isPrivateStructure() && !structure->isCivicStructure()) {
status->addMenuItem("@player_structure:structure_private"); //This structure is private
} else {
status->addMenuItem("@player_structure:structure_public"); //This structure is public
}
status->addMenuItem(
"@player_structure:condition_prompt "
+ String::valueOf(structure->getDecayPercentage()) + "%");
if (!structure->isCivicStructure() && !structure->isGCWBase()) {
// property tax
float propertytax = 0.f;
ManagedReference<CityRegion*> city = structure->getCityRegion().get();
if (city != nullptr) {
propertytax = city->getPropertyTax() / 100.f * structure->getMaintenanceRate();
status->addMenuItem("@city/city:property_tax_prompt : " + String::valueOf(ceil(propertytax)) + " cr/hr");
}
// maintenance
float secsRemainingMaint = 0.f;
if( structure->getSurplusMaintenance() > 0 ){
float totalrate = (float)structure->getMaintenanceRate() + propertytax;
secsRemainingMaint = ((float)structure->getSurplusMaintenance() / totalrate)*3600;
}
status->addMenuItem(
"@player_structure:maintenance_pool_prompt "
+ String::valueOf( (int) floor( (float) structure->getSurplusMaintenance()))
+ " "
+ getTimeString( (uint32)secsRemainingMaint ) );
status->addMenuItem(
"@player_structure:maintenance_rate_prompt "
+ String::valueOf(structure->getMaintenanceRate())
+ " cr/hr");
status->addMenuItem(
"@player_structure:maintenance_mods_prompt "
+ structure->getMaintenanceMods());
}
if (structure->isInstallationObject() && !structure->isGeneratorObject() && !structure->isCivicStructure()) {
InstallationObject* installation = cast<InstallationObject*>(structure);
installation->updateStructureStatus(); // update the hopper to get a current value, instead of from the last maintenance update
float secsRemainingPower = 0.f;
float basePowerRate = installation->getBasePowerRate();
float hopperCapacityMax = installation->getHopperSizeMax();
float hopperCapacity = installation->getHopperSize();
float hopperFilledPercent = 0.0f;
if (hopperCapacity > 0.0f) {
hopperFilledPercent = Math::getPrecision((hopperCapacity / hopperCapacityMax) * 100.0f, 2); // round % to two decimal places
}
if((installation->getSurplusPower() > 0) && (basePowerRate != 0)){
secsRemainingPower = ((float)installation->getSurplusPower() / (float)basePowerRate)*3600;
}
status->addMenuItem(
"@player_structure:power_reserve_prompt "
+ String::valueOf( (int) installation->getSurplusPower())
+ " "
+ getTimeString( (uint32)secsRemainingPower ) );
status->addMenuItem(
"@player_structure:power_consumption_prompt "
+ String::valueOf(
(int) installation->getBasePowerRate())
+ " @player_structure:units_per_hour");
status->addMenuItem(
"Capacity: " + String::valueOf(hopperFilledPercent) + "%");
}
if (structure->isGeneratorObject()) {
InstallationObject* generator = cast<InstallationObject*>(structure);
generator->updateStructureStatus();
float hopperCapacityMax = generator->getHopperSizeMax();
float hopperCapacity = generator->getHopperSize();
float hopperFilledPercent = 0.0f;
if (hopperCapacity > 0.0f) {
hopperFilledPercent = Math::getPrecision((hopperCapacity / hopperCapacityMax) * 100.0f, 2);
}
status->addMenuItem(
"Capacity: " + String::valueOf(hopperFilledPercent) + "%");
}
if (ghost->isPrivileged())
status->addMenuItem(structure->getDebugStructureStatus());
if (structure->isBuildingObject()) {
BuildingObject* building = cast<BuildingObject*>(structure);
uint32 playerItems = building->getCurrentNumberOfPlayerItems();
uint32 maxPlayerItems = building->getMaximumNumberOfPlayerItems();
if (building->isGCWBase()) {
Zone* zone = creature->getZone();
if (zone != nullptr) {
GCWManager* gcwMan = zone->getGCWManager();
if (gcwMan != nullptr)
status->addMenuItem(gcwMan->getVulnerableStatus(building, creature));
}
}
status->addMenuItem(
"@player_structure:items_in_building_prompt "
+ String::valueOf(playerItems) + "/" + String::valueOf(maxPlayerItems)); //Number of Items in Building:
#if ENABLE_STRUCTURE_JSON_EXPORT
if (creature->hasSkill("admin_base")) {
String exportNote = "Exported: " + building->exportJSON("reportStructureStatus");
building->info(exportNote, true);
status->addMenuItem(exportNote);
}
#endif
}
ghost->addSuiBox(status);
creature->sendMessage(status->generateMessage());
}
void StructureManager::promptNameStructure(CreatureObject* creature,
StructureObject* structure, TangibleObject* object) {
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr)
return;
ManagedReference<SuiInputBox*> inputBox = new SuiInputBox(creature,
SuiWindowType::OBJECT_NAME);
if (object == nullptr) {
inputBox->setUsingObject(structure);
} else {
inputBox->setUsingObject(object);
}
inputBox->setPromptTitle("@base_player:set_name"); //Set Name
inputBox->setPromptText("@player_structure:structure_name_prompt"); //Structure Name:
inputBox->setMaxInputSize(128);
inputBox->setCallback(new NameStructureSuiCallback(server));
inputBox->setForceCloseDistance(32);
ghost->addSuiBox(inputBox);
creature->sendMessage(inputBox->generateMessage());
}
void StructureManager::promptMaintenanceDroid(StructureObject* structure, CreatureObject* creature) {
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr)
return;
Vector<DroidObject*> droids;
ManagedReference<SceneObject*> datapad = creature->getSlottedObject("datapad");
if(datapad == nullptr) {
return;
}
for (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {
ManagedReference<SceneObject*> object = datapad->getContainerObject(i);
if (object != nullptr && object->isPetControlDevice()) {
PetControlDevice* device = cast<PetControlDevice*>( object.get());
if (device->getPetType() == PetManager::DROIDPET) {
DroidObject* pet = cast<DroidObject*>(device->getControlledObject());
if (pet != nullptr && pet->isMaintenanceDroid()) {
droids.add(pet);
}
}
}
}
if (droids.size() == 0) {
creature->sendSystemMessage("@player_structure:no_droids");
return;
}
ManagedReference<SuiListBox*> box = new SuiListBox(creature,SuiWindowType::STRUCTURE_ASSIGN_DROID);
box->setCallback(new StructureAssignDroidSuiCallback(creature->getZoneServer()));
box->setPromptText("@sui:assign_droid_prompt");
box->setPromptTitle("@sui:assign_droid_title"); // Configure Effects
box->setOkButton(true, "@ok");
// Check if player has a droid called with a maintenance module installed
for (int i = 0; i < droids.size(); ++i) {
DroidObject* droidObject = droids.elementAt(i);
box->addMenuItem(droidObject->getDisplayedName(),droidObject->getObjectID());
}
box->setUsingObject(structure);
ghost->addSuiBox(box);
creature->sendMessage(box->generateMessage());
}
void StructureManager::promptPayUncondemnMaintenance(CreatureObject* creature, StructureObject* structure) {
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr) {
return;
}
int uncondemnCost = -structure->getSurplusMaintenance();
ManagedReference<SuiMessageBox*> sui = nullptr;
String text;
if (creature->getBankCredits() >= uncondemnCost) {
//Owner can un-condemn the structure.
sui = new SuiMessageBox(creature, SuiWindowType::STRUCTURE_UNCONDEMN_CONFIRM);
if (sui == nullptr) {
return;
}
//TODO: investigate sui packets to see if it is possible to send StringIdChatParameter directly.
String textStringId =
"@player_structure:structure_condemned_owner_has_credits"; // "This structure has been condemned by the order of the Empire. You are not permitted to enter unless you pay %DI in maintenance costs. This will be automatically deducted from your bank account. Click Okay to confirm this transfer and regain access to this structure."
text =
StringIdManager::instance()->getStringId(
textStringId.hashCode()).toString();
text = text.replaceFirst("%DI", String::valueOf(uncondemnCost));
sui->setCancelButton(true, "@cancel");
sui->setCallback(
new StructurePayUncondemnMaintenanceSuiCallback(server));
} else {
//Owner cannot un-condemn the structure.
sui = new SuiMessageBox(creature, SuiWindowType::NONE);
if (sui == nullptr) {
return;
}
//TODO: investigate sui packets to see if it is possible to send StringIdChatParameter directly.
String textStringId =
"@player_structure:structure_condemned_owner_no_credits"; // "This structure has been condemned by the order of the Empire. It currently requires %DI credits to uncondemn this structure. You do not have sufficient funds in your bank account. Add sufficient funds to your account and return to regain access to this structure."
text =
StringIdManager::instance()->getStringId(
textStringId.hashCode()).toString();
text = text.replaceFirst("%DI", String::valueOf(uncondemnCost));
sui->setCancelButton(false, "@cancel");
}
sui->setPromptText(text);
sui->setOkButton(true, "@ok");
sui->setPromptTitle("@player_structure:fix_condemned_title"); // *******CONDEMNED STRUCTURE*******
sui->setUsingObject(structure);
ghost->addSuiBox(sui);
creature->sendMessage(sui->generateMessage());
}
void StructureManager::promptPayMaintenance(StructureObject* structure, CreatureObject* creature, SceneObject* terminal) {
int bank = creature->getBankCredits();
int cash = creature->getCashCredits();
int availableCredits = bank + cash;
if (availableCredits <= 0) {
creature->sendSystemMessage("@player_structure:no_money"); //You do not have any money to pay maintenance.
return;
}
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr)
return;
//Get the most up to date maintenance count.
structure->updateStructureStatus();
int surplusMaintenance = (int) floor(
(float) structure->getSurplusMaintenance());
ManagedReference<SuiTransferBox*> sui = new SuiTransferBox(creature,
SuiWindowType::STRUCTURE_MANAGE_MAINTENANCE);
sui->setCallback(new StructurePayMaintenanceSuiCallback(server));
sui->setPromptTitle("@player_structure:select_amount"); //Select Amount
if (structure->isPackedUp())
sui->setUsingObject(structure->getControlDevice().get());
else
sui->setUsingObject(structure);
sui->setPromptText(
"@player_structure:select_maint_amount \n@player_structure:current_maint_pool "
+ String::valueOf(surplusMaintenance));
sui->addFrom("@player_structure:total_funds",
String::valueOf(availableCredits),
String::valueOf(availableCredits), "1");
sui->addTo("@player_structure:to_pay", "0", "0", "1");
ghost->addSuiBox(sui);
creature->sendMessage(sui->generateMessage());
}
void StructureManager::promptWithdrawMaintenance(StructureObject* structure, CreatureObject* creature) {
if (!structure->isGuildHall()) {
return;
}
if (!structure->isOnAdminList(creature)) {
creature->sendSystemMessage("@player_structure:withdraw_admin_only"); // You must be an administrator to remove credits from the treasury.
return;
}
//Get the most up to date maintenance count.
structure->updateStructureStatus();
int surplusMaintenance = structure->getSurplusMaintenance();
if (surplusMaintenance <= 0) {
creature->sendSystemMessage("@player_structure:insufficient_funds_withdrawal"); // Insufficent funds for withdrawal.
return;
}
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr)
return;
ManagedReference<SuiInputBox*> sui = new SuiInputBox(creature, SuiWindowType::STRUCTURE_MANAGE_MAINTENANCE);
sui->setCallback(new StructureWithdrawMaintenanceSuiCallback(server));
sui->setPromptTitle("@player_structure:withdraw_maintenance"); // Withdraw From Treasury
sui->setUsingObject(structure);
sui->setPromptText("@player_structure:treasury_prompt " + String::valueOf(surplusMaintenance)); // Treasury:
ghost->addSuiBox(sui);
creature->sendMessage(sui->generateMessage());
}
void StructureManager::promptSelectSign(StructureObject* structure, CreatureObject* player){
if( !structure->isBuildingObject() )
return;
// Check building template has signs configured
Reference<SharedBuildingObjectTemplate*> buildingTemplate = dynamic_cast<SharedBuildingObjectTemplate*>(structure->getObjectTemplate());
if( buildingTemplate == nullptr ){
player->sendSystemMessage( "ERROR: Unable to get structure template" );
return;
}
if( buildingTemplate->getShopSignsSize() == 0 ){
player->sendSystemMessage( "This building does not have any additional signs configured" );
return;
}
SuiListBox* signBox = new SuiListBox(player, SuiWindowType::STRUCTURE_SELECT_SIGN);
signBox->setCallback(new StructureSelectSignSuiCallback(player->getZoneServer()));
signBox->setPromptTitle("@player_structure:changesign_title"); // "Sign Selection"
signBox->setPromptText("@player_structure:changesign_prompt"); // "Select the sign type that you would like to display"
signBox->setUsingObject(structure);
signBox->setCancelButton(true, "@cancel");
// Loop over all configured signs and add them to the list
for( int i=0; i < buildingTemplate->getShopSignsSize(); i++ ){
const SignTemplate* signTemplate = buildingTemplate->getShopSign(i);
// suiItem string can't be empty
if( signTemplate->getSuiItem().isEmpty() ){
continue;
}
// Check required skill (if any)
if( signTemplate->getRequiredSkill().isEmpty() ){
signBox->addMenuItem( signTemplate->getSuiItem() );
}
else{
if( player->hasSkill( signTemplate->getRequiredSkill() ) ){
signBox->addMenuItem( signTemplate->getSuiItem() );
}
}
}
player->sendMessage(signBox->generateMessage());
player->getPlayerObject()->addSuiBox(signBox);
}
void StructureManager::setSign(StructureObject* structure, CreatureObject* player, String signSuiItem ){
if( !structure->isBuildingObject() )
return;
// Check building template has shop signs configured
Reference<SharedBuildingObjectTemplate*> buildingTemplate = dynamic_cast<SharedBuildingObjectTemplate*>(structure->getObjectTemplate());
if( buildingTemplate == nullptr ){
player->sendSystemMessage( "ERROR: Unable to get structure template" );
return;
}
if( buildingTemplate->getShopSignsSize() == 0 ){
player->sendSystemMessage( "This building does not have any signs configured" );
return;
}
BuildingObject* building = cast<BuildingObject*>(structure);
if( building == nullptr )
return;
// Find matching sign in the template and change sign
for( int i=0; i < buildingTemplate->getShopSignsSize(); i++){
const SignTemplate* signTemplate = buildingTemplate->getShopSign(i);
if( signTemplate->getSuiItem() == signSuiItem ){
building->changeSign( signTemplate );
return;
}
}
}
void StructureManager::payMaintenance(StructureObject* structure,
CreatureObject* creature, int amount) {
if (amount < 0)
return;
int currentMaint = structure->getSurplusMaintenance();
if (currentMaint + amount > 100000000 || currentMaint + amount < currentMaint) {
creature->sendSystemMessage("The maximum maintenance a house can hold is 100.000.000");
return;
}
if (creature->getRootParent() != structure && !creature->isInRange(structure, 30.f) && !structure->isPackedUp()) {
creature->sendSystemMessage("@player_structure:pay_out_of_range"); //You have moved out of range of your original /payMaintenance target. Aborting...
return;
}
int bank = creature->getBankCredits();
int cash = creature->getCashCredits();
StringIdChatParameter params("base_player", "prose_pay_success"); //You successfully make a payment of %DI credits to %TT.
params.setTT(structure->getDisplayedName());
params.setDI(amount);
creature->sendSystemMessage(params);
if (cash < amount) {
int diff = amount - cash;
if (diff > bank){
creature->sendSystemMessage("@player_structure:insufficient_funds"); //You have insufficient funds to make this deposit.
return;
}
creature->subtractCashCredits(cash); //Take all from cash, since they didn't have enough to cover.
creature->subtractBankCredits(diff); //Take the rest from the bank.
} else {
creature->subtractCashCredits(amount); //Take all of the payment from cash.
}
structure->addMaintenance(amount);
PlayerObject* ghost = creature->getPlayerObject();
if (ghost->hasAbility("maintenance_fees_1")){
structure->setMaintenanceReduced(true);
} else {
structure->setMaintenanceReduced(false);
}
}
void StructureManager::withdrawMaintenance(StructureObject* structure, CreatureObject* creature, int amount) {
if (!structure->isGuildHall()) {
return;
}
if (!structure->isOnAdminList(creature)) {
creature->sendSystemMessage("@player_structure:withdraw_admin_only"); // You must be an administrator to remove credits from the treasury.
return;
}
if (amount < 0)
return;
int currentMaint = structure->getSurplusMaintenance();
if (currentMaint - amount < 0 || currentMaint - amount > currentMaint) {
creature->sendSystemMessage("@player_structure:insufficient_funds_withdrawal"); // Insufficent funds for withdrawal.
return;
}
StringIdChatParameter params("player_structure", "withdraw_credits"); // You withdraw %DI credits from the treasury.
params.setDI(amount);
creature->sendSystemMessage(params);
creature->addCashCredits(amount);
structure->subtractMaintenance(amount);
}
bool StructureManager::isInStructureFootprint(StructureObject* structure, float positionX, float positionY, int extraFootprintMargin){
if (structure == nullptr)
return false;
if (structure->getObjectTemplate() == nullptr)
return false;
Reference<SharedStructureObjectTemplate*> serverTemplate =
dynamic_cast<SharedStructureObjectTemplate*>(structure->getObjectTemplate());
float placingFootprintLength0 = 0, placingFootprintWidth0 = 0, placingFootprintLength1 = 0, placingFootprintWidth1 = 0;
if (getStructureFootprint(serverTemplate, structure->getDirectionAngle(), placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1) != 0)
return false;
float x0 = structure->getPositionX() + placingFootprintWidth0 + (placingFootprintWidth0 >= 0 ? extraFootprintMargin : (extraFootprintMargin * -1));
float y0 = structure->getPositionY() + placingFootprintLength0 + (placingFootprintLength0 >= 0 ? extraFootprintMargin : (extraFootprintMargin * -1));
float x1 = structure->getPositionX() + placingFootprintWidth1 + (placingFootprintWidth1 >= 0 ? extraFootprintMargin : (extraFootprintMargin * -1));
float y1 = structure->getPositionY() + placingFootprintLength1 + (placingFootprintLength1 >= 0 ? extraFootprintMargin : (extraFootprintMargin * -1));
BoundaryRectangle structureFootprint(x0, y0, x1, y1);
return structureFootprint.containsPoint(positionX, positionY);
}
int StructureManager::packupStructure(CreatureObject* creature) {
ManagedReference<PackupStructureSession*> session = creature->getActiveSession(SessionFacadeType::PACKUPSTRUCTURE).castTo<PackupStructureSession*>();
if (session == nullptr)
return 0;
ManagedReference<StructureObject*> structureObject = session->getStructureObject();
if (structureObject == nullptr)
return 0;
ManagedReference<StructureDeed*> deed = server->getObject(structureObject->getDeedObjectID()).castTo<StructureDeed*>();
if (deed == nullptr)
return 0;
Locker _locker(structureObject);
int maint = structureObject->getSurplusMaintenance();
int redeedCost = structureObject->getRedeedCost();
if (structureObject->isRedeedable()) {
ManagedReference<StructureControlDevice*> controlDevice = server->createObject(STRING_HASHCODE("object/intangible/house/generic_house_control_device.iff"), 1).castTo<StructureControlDevice*>();
if (controlDevice == nullptr)
return session->cancelSession();
Locker _lock(controlDevice, structureObject);
ManagedReference<SceneObject*> datapad = creature->getSlottedObject("datapad");
if (datapad == nullptr)
return session->cancelSession();
if (datapad->isContainerFullRecursive()) {
creature->sendSystemMessage("Structure Packup Failed: Your datapad is full!");
controlDevice->destroyObjectFromWorld(true);
controlDevice->destroyObjectFromDatabase(true);
return session->cancelSession();
} else {
ManagedReference<BuildingObject*> building = cast<BuildingObject*>(structureObject.get());
if (building == nullptr || !structureObject->unloadFromZone(true)) {
creature->sendSystemMessage("Structure Packup Failed! Building was null or it couldn't be unloaded from zone. Please open a support ticket reporting this error.");
controlDevice->destroyObjectFromWorld(true);
controlDevice->destroyObjectFromDatabase(true);
return session->cancelSession();
}
if (building->getCustomObjectName() != "")
controlDevice->setCustomObjectName(building->getCustomObjectName(), true);
else
controlDevice->setCustomObjectName(structureObject->getDisplayedName(), true);
controlDevice->setControlledObject(structureObject);
controlDevice->updateStatus(1);
structureObject->setSurplusMaintenance(maint - redeedCost);
structureObject->setControlDevice(controlDevice);
datapad->transferObject(controlDevice, -1);
datapad->broadcastObject(controlDevice, true);
StringBuffer msg;
msg << "Structure ID: " << structureObject->getObjectID() << " Owned By: " << creature->getFirstName() << " has been packed up by the player.";
structurePackupLog.info(msg.toString());
creature->sendSystemMessage("Structure Pack Up Successful! A structure control device has been placed in your datapad.");
}
}
return session->cancelSession();
}
void StructureManager::systemPackupStructure(StructureObject* structureObject, CreatureObject* creature) {
if (structureObject == nullptr || creature == nullptr)
return;
ManagedReference<StructureDeed*> deed = server->getObject(structureObject->getDeedObjectID()).castTo<StructureDeed*>();
if (deed == nullptr)
return;
ManagedReference<StructureControlDevice*> controlDevice = server->createObject(STRING_HASHCODE("object/intangible/house/generic_house_control_device.iff"), 1).castTo<StructureControlDevice*>();
if (controlDevice == nullptr)
return;
Locker _locker(structureObject);
Locker _lock(controlDevice, structureObject);
ManagedReference<SceneObject*> datapad = creature->getSlottedObject("datapad");
if (datapad == nullptr) {
error("System failed to packup structure: " + String::valueOf(structureObject->getObjectID()) + ". Creature datapad was null.");
controlDevice->destroyObjectFromWorld(true);
controlDevice->destroyObjectFromDatabase(true);
return;
} else {
ManagedReference<BuildingObject*> building = cast<BuildingObject*>(structureObject);
if (building == nullptr || !structureObject->unloadFromZone(true)) {
error("System failed to packup structure: " + String::valueOf(structureObject->getObjectID()) + ". Building was null or it couldn't be unloaded from zone.");
controlDevice->destroyObjectFromWorld(true);
controlDevice->destroyObjectFromDatabase(true);
return;
}
if (building->getCustomObjectName() != "")
controlDevice->setCustomObjectName(building->getCustomObjectName(), true);
else
controlDevice->setCustomObjectName(structureObject->getDisplayedName(), true);
controlDevice->setControlledObject(structureObject);
controlDevice->updateStatus(1);
structureObject->setControlDevice(controlDevice);
datapad->transferObject(controlDevice, -1);
datapad->broadcastObject(controlDevice, true);
StringBuffer msg;
msg << "Structure ID: " << structureObject->getObjectID() << " Owned By: " << creature->getFirstName() << " has been packed up by the system.";
systemStructurePackupLog.info(msg.toString());
}
}
int StructureManager::unpackStructureFromControlDevice(CreatureObject* creature, StructureObject* structure, float x, float y, int angle) {
ManagedReference<Zone*> zone = creature->getZone();
//Already un-packing a structure?
if (zone == nullptr || creature->containsActiveSession(SessionFacadeType::UNPACKSTRUCTURE))
return 1;
ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager();
String serverTemplatePath = structure->getObjectTemplate()->getFullTemplateString();
Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));
//Check to see if this zone allows this structure.
if (serverTemplate == nullptr || !serverTemplate->isAllowedZone(zone->getZoneName())) {
creature->sendSystemMessage("@player_structure:wrong_planet"); //That deed cannot be used on this planet.
return 1;
}
if (!planetManager->isBuildingPermittedAt(x, y, creature)) {
creature->sendSystemMessage("@player_structure:not_permitted"); //Building is not permitted here.
return 1;
}
SortedVector<ManagedReference<ActiveArea*> > objects;
zone->getInRangeActiveAreas(x, y, &objects, true);
ManagedReference<CityRegion*> city;
for (int i = 0; i < objects.size(); ++i) {
ActiveArea* area = objects.get(i).get();
if (!area->isRegion())
continue;
city = dynamic_cast<Region*>(area)->getCityRegion().get();
if (city != nullptr)
break;
}
SortedVector<ManagedReference<QuadTreeEntry*> > inRangeObjects;
zone->getInRangeObjects(x, y, 128, &inRangeObjects, true, false);
float placingFootprintLength0 = 0, placingFootprintWidth0 = 0, placingFootprintLength1 = 0, placingFootprintWidth1 = 0;
if (!getStructureFootprint(serverTemplate, angle, placingFootprintLength0, placingFootprintWidth0, placingFootprintLength1, placingFootprintWidth1)) {
float x0 = x + placingFootprintWidth0;
float y0 = y + placingFootprintLength0;
float x1 = x + placingFootprintWidth1;
float y1 = y + placingFootprintLength1;
BoundaryRectangle placingFootprint(x0, y0, x1, y1);
//info("placing center x:" + String::valueOf(x) + " y:" + String::valueOf(y), true);
//info("placingFootprint x0:" + String::valueOf(x0) + " y0:" + String::valueOf(y0) + " x1:" + String::valueOf(x1) + " y1:" + String::valueOf(y1), true);
for (int i = 0; i < inRangeObjects.size(); ++i) {
SceneObject* scene = inRangeObjects.get(i).castTo<SceneObject*>();
if (scene == nullptr)
continue;
float l0 = -5; //Along the x axis.
float w0 = -5; //Along the y axis.
float l1 = 5;
float w1 = 5;
if (getStructureFootprint(dynamic_cast<SharedStructureObjectTemplate*>(scene->getObjectTemplate()), scene->getDirectionAngle(), l0, w0, l1, w1))
continue;
float xx0 = scene->getPositionX() + (w0 + 0.1);
float yy0 = scene->getPositionY() + (l0 + 0.1);
float xx1 = scene->getPositionX() + (w1 - 0.1);
float yy1 = scene->getPositionY() + (l1 - 0.1);
BoundaryRectangle rect(xx0, yy0, xx1, yy1);
//info("existing footprint xx0:" + String::valueOf(xx0) + " yy0:" + String::valueOf(yy0) + " xx1:" + String::valueOf(xx1) + " yy1:" + String::valueOf(yy1), true);
// check 4 points of the current rect
if (rect.containsPoint(x0, y0)
|| rect.containsPoint(x0, y1)
|| rect.containsPoint(x1, y0)
|| rect.containsPoint(x1, y1) ) {
//info("existing footprint contains placing point", true);
creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here..
return 1;
}
if (placingFootprint.containsPoint(xx0, yy0)
|| placingFootprint.containsPoint(xx0, yy1)
|| placingFootprint.containsPoint(xx1, yy0)
|| placingFootprint.containsPoint(xx1, yy1)
|| (xx0 == x0 && yy0 == y0 && xx1 == x1 && yy1 == y1)) {
//info("placing footprint contains existing point", true);
creature->sendSystemMessage("@player_structure:no_room"); //there is no room to place the structure here.
return 1;
}
}
}
int rankRequired = serverTemplate->getCityRankRequired();
if (city == nullptr && rankRequired > 0) {
creature->sendSystemMessage("@city/city:build_no_city"); // You must be in a city to place that structure.
return 1;
}
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (city != nullptr) {
if (ghost != nullptr && !ghost->isAdmin()) {
if (city->isZoningEnabled() && !city->hasZoningRights(creature->getObjectID()) && !city->isMilitiaMember(creature->getObjectID())) {
creature->sendSystemMessage("@player_structure:no_rights"); //You don't have the right to place that structure in this city. The mayor or one of the city milita must grant you zoning rights first.
return 1;
}
}
if (rankRequired != 0 && city->getCityRank() < rankRequired) {
StringIdChatParameter param("city/city", "rank_req"); // The city must be at least rank %DI (%TO) in order for you to place this structure.
param.setDI(rankRequired);
param.setTO("city/city", "rank" + String::valueOf(rankRequired));
creature->sendSystemMessage(param);
return 1;
}
}
Locker _lock(structure, creature);
if (ghost != nullptr) {
String abilityRequired = serverTemplate->getAbilityRequired();
if (!abilityRequired.isEmpty() && !ghost->hasAbility(abilityRequired)) {
creature->sendSystemMessage("@player_structure:" + abilityRequired);
return 1;
}
}
//Validate that the structure can be placed at the given coordinates:
//Ensure that no other objects impede on this structures footprint, or overlap any city regions or no build areas.
//Make sure that the player has zoning rights in the area.
ManagedReference<UnpackStructureSession*> session = new UnpackStructureSession(creature, structure);
creature->addActiveSession(SessionFacadeType::UNPACKSTRUCTURE, session);
//Construct the structure.
session->constructStructure(x, y, angle);
return 0;
}
bool StructureManager::unpackStructure(CreatureObject* creature, StructureObject* structure, float x, float y, int angle, int persistenceLevel) {
if (creature == nullptr || structure == nullptr)
return false;
ManagedReference<Zone*> zone = creature->getZone();
if (zone == nullptr)
return false;
TerrainManager* terrainManager = zone->getPlanetManager()->getTerrainManager();
String serverTemplatePath = structure->getObjectTemplate()->getFullTemplateString();
Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));
if (serverTemplate == nullptr)
return false;
float z = zone->getHeight(x, y);
float floraRadius = serverTemplate->getClearFloraRadius();
bool snapToTerrain = serverTemplate->getSnapToTerrain();
Reference<const StructureFootprint*> structureFootprint = serverTemplate->getStructureFootprint();
float w0 = -5; //Along the x axis.
float l0 = -5; //Along the y axis.
float l1 = 5;
float w1 = 5;
float zIncreaseWhenNoAvailableFootprint = 0.f; //TODO: remove this when it has been verified that all buildings have astructure footprint.
if (structureFootprint != nullptr) {
//If the angle is odd, then swap them.
getStructureFootprint(serverTemplate, angle, l0, w0, l1, w1);
} else {
if (!serverTemplate->isCampStructureTemplate())
warning("Structure with template '" + serverTemplatePath + "' has no structure footprint.");
zIncreaseWhenNoAvailableFootprint = 5.f;
}
if (floraRadius > 0 && !snapToTerrain)
z = terrainManager->getHighestHeight(x + w0, y + l0, x + w1, y + l1, 1) + zIncreaseWhenNoAvailableFootprint;
ManagedReference<StructureControlDevice*> controlDevice = structure->getControlDevice().castTo<StructureControlDevice*>();
if (controlDevice == nullptr)
return false;
Locker sLocker(structure);
structure->initializePosition(x, z, y);
structure->setDirection(0);
structure->rotate(angle);
zone->transferObject(structure, -1, true);
structure->createChildObjects();
structure->notifyStructurePlaced(creature);
return structure;
}
| 35.989651 | 334 | 0.739395 | [
"object",
"vector"
] |
aaae54e420a6c69f7bc7d274a20f22fdd481cefa | 5,231 | cpp | C++ | test/CapabilitySet.cpp | MIPS/external-shaderc-spirv-tools | 410cd1fca9703990880d4ddc53bb0b367889b173 | [
"Apache-2.0"
] | null | null | null | test/CapabilitySet.cpp | MIPS/external-shaderc-spirv-tools | 410cd1fca9703990880d4ddc53bb0b367889b173 | [
"Apache-2.0"
] | null | null | null | test/CapabilitySet.cpp | MIPS/external-shaderc-spirv-tools | 410cd1fca9703990880d4ddc53bb0b367889b173 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "gmock/gmock.h"
#include "enum_set.h"
#include "UnitSPIRV.h"
namespace {
using libspirv::CapabilitySet;
using spvtest::ElementsIn;
using ::testing::Eq;
using ::testing::ValuesIn;
TEST(CapabilitySet, DefaultIsEmpty) {
CapabilitySet c;
for (uint32_t i = 0; i < 1000; ++i) {
EXPECT_FALSE(c.Contains(i));
EXPECT_FALSE(c.Contains(static_cast<SpvCapability>(i)));
}
}
TEST(CapabilitySet, ConstructSingleMemberMatrix) {
CapabilitySet s(SpvCapabilityMatrix);
EXPECT_TRUE(s.Contains(SpvCapabilityMatrix));
EXPECT_FALSE(s.Contains(SpvCapabilityShader));
EXPECT_FALSE(s.Contains(1000));
}
TEST(CapabilitySet, ConstructSingleMemberMaxInMask) {
CapabilitySet s(static_cast<SpvCapability>(63));
EXPECT_FALSE(s.Contains(SpvCapabilityMatrix));
EXPECT_FALSE(s.Contains(SpvCapabilityShader));
EXPECT_TRUE(s.Contains(63));
EXPECT_FALSE(s.Contains(64));
EXPECT_FALSE(s.Contains(1000));
}
TEST(CapabilitySet, ConstructSingleMemberMinOverflow) {
// Check the first one that forces overflow beyond the mask.
CapabilitySet s(static_cast<SpvCapability>(64));
EXPECT_FALSE(s.Contains(SpvCapabilityMatrix));
EXPECT_FALSE(s.Contains(SpvCapabilityShader));
EXPECT_FALSE(s.Contains(63));
EXPECT_TRUE(s.Contains(64));
EXPECT_FALSE(s.Contains(1000));
}
TEST(CapabilitySet, ConstructSingleMemberMaxOverflow) {
// Check the max 32-bit signed int.
CapabilitySet s(SpvCapability(0x7fffffffu));
EXPECT_FALSE(s.Contains(SpvCapabilityMatrix));
EXPECT_FALSE(s.Contains(SpvCapabilityShader));
EXPECT_FALSE(s.Contains(1000));
EXPECT_TRUE(s.Contains(0x7fffffffu));
}
TEST(CapabilitySet, AddEnum) {
CapabilitySet s(SpvCapabilityShader);
s.Add(SpvCapabilityKernel);
EXPECT_FALSE(s.Contains(SpvCapabilityMatrix));
EXPECT_TRUE(s.Contains(SpvCapabilityShader));
EXPECT_TRUE(s.Contains(SpvCapabilityKernel));
}
TEST(CapabilitySet, AddInt) {
CapabilitySet s(SpvCapabilityShader);
s.Add(42);
EXPECT_FALSE(s.Contains(SpvCapabilityMatrix));
EXPECT_TRUE(s.Contains(SpvCapabilityShader));
EXPECT_TRUE(s.Contains(42));
EXPECT_TRUE(s.Contains(static_cast<SpvCapability>(42)));
}
TEST(CapabilitySet, InitializerListEmpty) {
CapabilitySet s{};
for (uint32_t i = 0; i < 1000; i++) {
EXPECT_FALSE(s.Contains(i));
}
}
struct ForEachCase {
CapabilitySet capabilities;
std::vector<SpvCapability> expected;
};
using CapabilitySetForEachTest = ::testing::TestWithParam<ForEachCase>;
TEST_P(CapabilitySetForEachTest, CallsAsExpected) {
EXPECT_THAT(ElementsIn(GetParam().capabilities), Eq(GetParam().expected));
}
TEST_P(CapabilitySetForEachTest, CopyConstructor) {
CapabilitySet copy(GetParam().capabilities);
EXPECT_THAT(ElementsIn(copy), Eq(GetParam().expected));
}
TEST_P(CapabilitySetForEachTest, MoveConstructor) {
// We need a writable copy to move from.
CapabilitySet copy(GetParam().capabilities);
CapabilitySet moved(std::move(copy));
EXPECT_THAT(ElementsIn(moved), Eq(GetParam().expected));
// The moved-from set is empty.
EXPECT_THAT(ElementsIn(copy), Eq(std::vector<SpvCapability>{}));
}
TEST_P(CapabilitySetForEachTest, OperatorEquals) {
CapabilitySet assigned = GetParam().capabilities;
EXPECT_THAT(ElementsIn(assigned), Eq(GetParam().expected));
}
TEST_P(CapabilitySetForEachTest, OperatorEqualsSelfAssign) {
CapabilitySet assigned{GetParam().capabilities};
assigned = assigned;
EXPECT_THAT(ElementsIn(assigned), Eq(GetParam().expected));
}
INSTANTIATE_TEST_CASE_P(Samples, CapabilitySetForEachTest,
ValuesIn(std::vector<ForEachCase>{
{{}, {}},
{{SpvCapabilityMatrix}, {SpvCapabilityMatrix}},
{{SpvCapabilityKernel, SpvCapabilityShader},
{SpvCapabilityShader, SpvCapabilityKernel}},
{{static_cast<SpvCapability>(999)},
{static_cast<SpvCapability>(999)}},
{{static_cast<SpvCapability>(0x7fffffff)},
{static_cast<SpvCapability>(0x7fffffff)}},
// Mixture and out of order
{{static_cast<SpvCapability>(0x7fffffff),
static_cast<SpvCapability>(100),
SpvCapabilityShader, SpvCapabilityMatrix},
{SpvCapabilityMatrix, SpvCapabilityShader,
static_cast<SpvCapability>(100),
static_cast<SpvCapability>(0x7fffffff)}},
}), );
} // anonymous namespace
| 34.414474 | 76 | 0.695278 | [
"vector"
] |
82b4ee8cfc33cc8c94d88c0d9598b6d6aa4c37ec | 7,278 | hpp | C++ | plugins/EstimationPlugin/src/base/measurementfile/DataFile.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | plugins/EstimationPlugin/src/base/measurementfile/DataFile.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | plugins/EstimationPlugin/src/base/measurementfile/DataFile.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | //$Id: DataFile.hpp 1398 2011-04-21 20:39:37Z $
//------------------------------------------------------------------------------
// DataFile
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: 2009/07/16
//
/**
* Definition for the DataFile class used in GMAT measurement simulator and
* estimators
*/
//------------------------------------------------------------------------------
#ifndef DataFile_hpp
#define DataFile_hpp
#include "estimation_defs.hpp"
#include "GmatBase.hpp"
#include "ObType.hpp"
#include "DataFilter.hpp"
#include "MeasurementData.hpp"
#include "ObservationData.hpp"
/**
* DataFile is the container class for measurement data streams.
*
* The DataFile class provides the interfaces needed to script observation data
* into GMAT. Instances of the class identify the type of data stream used and
* the identifier for that stream.
*/
class ESTIMATION_API DataFile : public GmatBase
{
public:
DataFile(const std::string name);
virtual ~DataFile();
DataFile(const DataFile& df);
DataFile& operator=(const DataFile& df);
virtual GmatBase* Clone() const;
virtual bool Initialize();
virtual bool Finalize();
// Access methods derived classes can override
virtual std::string GetParameterText(const Integer id) const;
virtual std::string GetParameterUnit(const Integer id) const;
virtual Integer GetParameterID(const std::string &str) const;
virtual Gmat::ParameterType
GetParameterType(const Integer id) const;
virtual std::string GetParameterTypeString(const Integer id) const;
virtual std::string GetStringParameter(const Integer id) const;
virtual bool SetStringParameter(const Integer id,
const std::string &value);
virtual std::string GetStringParameter(const Integer id,
const Integer index) const;
virtual bool SetStringParameter(const Integer id,
const std::string &value,
const Integer index);
virtual std::string GetStringParameter(const std::string &label) const;
virtual bool SetStringParameter(const std::string &label,
const std::string &value);
virtual std::string GetStringParameter(const std::string &label,
const Integer index) const;
virtual bool SetStringParameter(const std::string &label,
const std::string &value,
const Integer index);
virtual const StringArray&
GetStringArrayParameter(const Integer id) const;
virtual const StringArray&
GetStringArrayParameter(const std::string &label) const;
virtual Real GetRealParameter(const Integer id) const;
virtual Real SetRealParameter(const Integer id,
const Real value);
virtual Real GetRealParameter(const std::string& label) const;
virtual Real SetRealParameter(const std::string& label,
const Real value);
virtual bool SetRefObject(GmatBase *obj, const UnsignedInt type,
const std::string &name = "");
virtual bool SetDataFilter(DataFilter *filter);
virtual std::vector<DataFilter*>& GetFilterList();
virtual bool SetStream(ObType *thisStream);
virtual bool OpenStream(bool simulate = false);
virtual bool IsOpen();
virtual void WriteMeasurement(MeasurementData* theMeas);
virtual ObservationData*
ReadObservation();
///// TBD: Determine if there is a more generic way to add these
virtual RampTableData*
ReadRampTableData();
virtual bool CloseStream();
ObservationData* FilteringData(ObservationData* dataObject, Integer& rejectedReason);
/// @todo: Check this
DEFAULT_TO_NO_CLONES
DEFAULT_TO_NO_REFOBJECTS
protected:
/// The stream for this DataFile
ObType *theDatastream;
/// Name of the data stream
std::string streamName;
/// Text description of the observation data type
std::string obsType;
/// This section is set for new design data filter
/// List of data filters
std::vector<DataFilter*> filterList;
/// This section is set for old design data filter
/// Data thinning ratio
Real thinningRatio; // data thinning ratio specify the ratio between the selected data records and total all records
/// List of station IDs
StringArray selectedStationIDs; // list of stationIDs included in data file
/// Range of epoch is specified by start epoch and end epoch and format used by epoch
std::string epochFormat;
std::string startEpoch;
std::string endEpoch;
/// Start epoch for the estimation
GmatEpoch estimationStart;
/// End epoch for the end of the estimation
GmatEpoch estimationEnd;
/// Class parameter ID enumeration
enum
{
StreamName = GmatBaseParamCount,
ObsType,
DataThinningRatio,
SelectedStationIDs,
EpochFormat,
StartEpoch,
EndEpoch,
DataFileParamCount
};
// Start with the parameter IDs and associates strings
/// Strings associated with the DataFile parameters
static const std::string
PARAMETER_TEXT[DataFileParamCount - GmatBaseParamCount];
/// Types of the DataFile parameters
static const Gmat::ParameterType
PARAMETER_TYPE[DataFileParamCount - GmatBaseParamCount];
private:
Real ConvertToRealEpoch(const std::string &theEpoch, const std::string &theFormat);
ObservationData* FilteringDataForNewSyntax(ObservationData* dataObject, Integer& filterIndex);
ObservationData* FilteringDataForOldSyntax(ObservationData* dataObject, Integer& rejectedReason);
ObservationData od_old;
Real acc;
Real epoch1;
Real epoch2;
};
#endif /* DataFile_hpp */
| 38.507937 | 139 | 0.62792 | [
"vector"
] |
82b5c1545afdcc5ca17e74ea7e9dba005a490e7a | 12,019 | cxx | C++ | 3p/VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/CylinderIntersector.cxx | Mason-Wmx/ViewFramework | d8117adc646c369ad29d64477788514c7a75a797 | [
"Apache-2.0"
] | 1 | 2021-10-03T16:47:04.000Z | 2021-10-03T16:47:04.000Z | 3p/VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/CylinderIntersector.cxx | Mason-Wmx/ViewFramework | d8117adc646c369ad29d64477788514c7a75a797 | [
"Apache-2.0"
] | null | null | null | 3p/VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/CylinderIntersector.cxx | Mason-Wmx/ViewFramework | d8117adc646c369ad29d64477788514c7a75a797 | [
"Apache-2.0"
] | null | null | null | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2015 UT-Battelle, LLC.
// Copyright 2015 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/VectorAnalysis.h>
#include <vtkm/cont/Algorithm.h>
#include <vtkm/rendering/raytracing/BVHTraverser.h>
#include <vtkm/rendering/raytracing/CylinderIntersector.h>
#include <vtkm/rendering/raytracing/RayOperations.h>
#include <vtkm/worklet/DispatcherMapTopology.h>
namespace vtkm
{
namespace rendering
{
namespace raytracing
{
namespace detail
{
template <typename Device>
class CylinderLeafIntersector : public vtkm::cont::ExecutionObjectBase
{
public:
using IdHandle = vtkm::cont::ArrayHandle<vtkm::Id3>;
using IdArrayPortal = typename IdHandle::ExecutionTypes<Device>::PortalConst;
using FloatHandle = vtkm::cont::ArrayHandle<vtkm::Float32>;
using FloatPortal = typename FloatHandle::ExecutionTypes<Device>::PortalConst;
IdArrayPortal CylIds;
FloatPortal Radii;
CylinderLeafIntersector(const IdHandle& cylIds, const FloatHandle& radii)
: CylIds(cylIds.PrepareForInput(Device()))
, Radii(radii.PrepareForInput(Device()))
{
}
template <typename vec3>
VTKM_EXEC vec3 cylinder(const vec3& ray_start,
const vec3& ray_direction,
const vec3& p,
const vec3& q,
float r) const
{
float t = 0;
vec3 d = q - p;
vec3 m = ray_start - p;
vec3 s = ray_start - q;
vtkm::Float32 mdotm = vtkm::Float32(vtkm::dot(m, m));
vec3 n = ray_direction * (vtkm::Max(mdotm, static_cast<vtkm::Float32>(vtkm::dot(s, s))) + r);
vtkm::Float32 mdotd = vtkm::Float32(vtkm::dot(m, d));
vtkm::Float32 ndotd = vtkm::Float32(vtkm::dot(n, d));
vtkm::Float32 ddotd = vtkm::Float32(vtkm::dot(d, d));
if ((mdotd < 0.0f) && (mdotd + ndotd < 0.0f))
{
return vec3(0.f, 0.f, 0.f);
}
if ((mdotd > ddotd) && (mdotd + ndotd > ddotd))
{
return vec3(0.f, 0.f, 0.f);
}
vtkm::Float32 ndotn = vtkm::Float32(vtkm::dot(n, n));
vtkm::Float32 nlen = vtkm::Float32(sqrt(ndotn));
vtkm::Float32 mdotn = vtkm::Float32(vtkm::dot(m, n));
vtkm::Float32 a = ddotd * ndotn - ndotd * ndotd;
vtkm::Float32 k = mdotm - r * r;
vtkm::Float32 c = ddotd * k - mdotd * mdotd;
if (fabs(a) < 1e-6)
{
if (c > 0.0)
{
return vec3(0, 0, 0);
}
if (mdotd < 0.0f)
{
t = -mdotn / ndotn;
}
else if (mdotd > ddotd)
{
t = (ndotd - mdotn) / ndotn;
}
else
t = 0;
return vec3(1, t * nlen, 0);
}
vtkm::Float32 b = ddotd * mdotn - ndotd * mdotd;
vtkm::Float32 discr = b * b - a * c;
if (discr < 0.0f)
{
return vec3(0, 0, 0);
}
t = (-b - vtkm::Sqrt(discr)) / a;
if (t < 0.0f || t > 1.0f)
{
return vec3(0, 0, 0);
}
vtkm::Float32 u = mdotd + t * ndotd;
if (u > ddotd)
{
if (ndotd >= 0.0f)
{
return vec3(0, 0, 0);
}
t = (ddotd - mdotd) / ndotd;
return vec3(
k + ddotd - 2 * mdotd + t * (2 * (mdotn - ndotd) + t * ndotn) <= 0.0f, t * nlen, 0);
}
else if (u < 0.0f)
{
if (ndotd <= 0.0f)
{
return vec3(0.0, 0.0, 0);
}
t = -mdotd / ndotd;
return vec3(k + 2 * t * (mdotn + t * ndotn) <= 0.0f, t * nlen, 0);
}
return vec3(1, t * nlen, 0);
}
template <typename PointPortalType, typename LeafPortalType, typename Precision>
VTKM_EXEC inline void IntersectLeaf(
const vtkm::Int32& currentNode,
const vtkm::Vec<Precision, 3>& origin,
const vtkm::Vec<Precision, 3>& dir,
const PointPortalType& points,
vtkm::Id& hitIndex,
Precision& closestDistance, // closest distance in this set of primitives
Precision& vtkmNotUsed(minU),
Precision& vtkmNotUsed(minV),
LeafPortalType leafs,
const Precision& minDistance) const // report intesections past this distance
{
const vtkm::Id cylCount = leafs.Get(currentNode);
for (vtkm::Id i = 1; i <= cylCount; ++i)
{
const vtkm::Id cylIndex = leafs.Get(currentNode + i);
if (cylIndex < CylIds.GetNumberOfValues())
{
vtkm::Id3 pointIndex = CylIds.Get(cylIndex);
vtkm::Float32 radius = Radii.Get(cylIndex);
vtkm::Vec<Precision, 3> bottom, top;
bottom = vtkm::Vec<Precision, 3>(points.Get(pointIndex[1]));
top = vtkm::Vec<Precision, 3>(points.Get(pointIndex[2]));
vtkm::Vec<vtkm::Float32, 3> ret;
ret = cylinder(origin, dir, bottom, top, radius);
if (ret[0] > 0)
{
if (ret[1] < closestDistance && ret[1] > minDistance)
{
//matid = vtkm::Vec<, 3>(points.Get(cur_offset + 2))[0];
closestDistance = ret[1];
hitIndex = cylIndex;
}
}
}
} // for
}
};
struct IntersectFunctor
{
template <typename Device, typename Precision>
VTKM_CONT bool operator()(Device,
CylinderIntersector* self,
Ray<Precision>& rays,
bool returnCellIndex)
{
VTKM_IS_DEVICE_ADAPTER_TAG(Device);
self->IntersectRaysImp(Device(), rays, returnCellIndex);
return true;
}
};
class CalculateNormals : public vtkm::worklet::WorkletMapField
{
public:
VTKM_CONT
CalculateNormals() {}
typedef void ControlSignature(FieldIn<>,
FieldIn<>,
FieldOut<>,
FieldOut<>,
FieldOut<>,
WholeArrayIn<Vec3RenderingTypes>,
WholeArrayIn<>);
typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7);
template <typename Precision, typename PointPortalType, typename IndicesPortalType>
VTKM_EXEC inline void operator()(const vtkm::Id& hitIndex,
const vtkm::Vec<Precision, 3>& intersection,
Precision& normalX,
Precision& normalY,
Precision& normalZ,
const PointPortalType& points,
const IndicesPortalType& indicesPortal) const
{
if (hitIndex < 0)
return;
vtkm::Id3 cylId = indicesPortal.Get(hitIndex);
vtkm::Vec<Precision, 3> a, b;
a = points.Get(cylId[1]);
b = points.Get(cylId[2]);
vtkm::Vec<Precision, 3> ap, ab;
ap = intersection - a;
ab = b - a;
Precision mag2 = vtkm::Magnitude(ab);
Precision len = vtkm::dot(ab, ap);
Precision t = len / mag2;
vtkm::Vec<Precision, 3> center;
center = a + t * ab;
vtkm::Vec<Precision, 3> normal = intersection - center;
vtkm::Normalize(normal);
//flip the normal if its pointing the wrong way
normalX = normal[0];
normalY = normal[1];
normalZ = normal[2];
}
}; //class CalculateNormals
template <typename Precision>
class GetScalar : public vtkm::worklet::WorkletMapField
{
private:
Precision MinScalar;
Precision invDeltaScalar;
public:
VTKM_CONT
GetScalar(const vtkm::Float32& minScalar, const vtkm::Float32& maxScalar)
: MinScalar(minScalar)
{
//Make sure the we don't divide by zero on
//something like an iso-surface
if (maxScalar - MinScalar != 0.f)
invDeltaScalar = 1.f / (maxScalar - MinScalar);
else
invDeltaScalar = 1.f / minScalar;
}
typedef void ControlSignature(FieldIn<>,
FieldInOut<>,
WholeArrayIn<ScalarRenderingTypes>,
WholeArrayIn<>);
typedef void ExecutionSignature(_1, _2, _3, _4);
template <typename ScalarPortalType, typename IndicesPortalType>
VTKM_EXEC void operator()(const vtkm::Id& hitIndex,
Precision& scalar,
const ScalarPortalType& scalars,
const IndicesPortalType& indicesPortal) const
{
if (hitIndex < 0)
return;
//TODO: this should be interpolated?
vtkm::Id3 pointId = indicesPortal.Get(hitIndex);
scalar = Precision(scalars.Get(pointId[0]));
//normalize
scalar = (scalar - MinScalar) * invDeltaScalar;
}
}; //class GetScalar
} // namespace detail
CylinderIntersector::CylinderIntersector()
: ShapeIntersector()
{
}
CylinderIntersector::~CylinderIntersector()
{
}
void CylinderIntersector::IntersectRays(Ray<vtkm::Float32>& rays, bool returnCellIndex)
{
vtkm::cont::TryExecute(detail::IntersectFunctor(), this, rays, returnCellIndex);
}
void CylinderIntersector::IntersectRays(Ray<vtkm::Float64>& rays, bool returnCellIndex)
{
vtkm::cont::TryExecute(detail::IntersectFunctor(), this, rays, returnCellIndex);
}
template <typename Device, typename Precision>
void CylinderIntersector::IntersectRaysImp(Device,
Ray<Precision>& rays,
bool vtkmNotUsed(returnCellIndex))
{
detail::CylinderLeafIntersector<Device> leafIntersector(this->CylIds, Radii);
BVHTraverser<detail::CylinderLeafIntersector> traverser;
traverser.IntersectRays(rays, this->BVH, leafIntersector, this->CoordsHandle, Device());
RayOperations::UpdateRayStatus(rays);
}
template <typename Precision>
void CylinderIntersector::IntersectionDataImp(Ray<Precision>& rays,
const vtkm::cont::Field* scalarField,
const vtkm::Range& scalarRange)
{
ShapeIntersector::IntersectionPoint(rays);
// TODO: if this is nodes of a mesh, support points
bool isSupportedField =
(scalarField->GetAssociation() == vtkm::cont::Field::Association::POINTS ||
scalarField->GetAssociation() == vtkm::cont::Field::Association::CELL_SET);
if (!isSupportedField)
throw vtkm::cont::ErrorBadValue("Field not accociated with a cell set");
vtkm::worklet::DispatcherMapField<detail::CalculateNormals>(detail::CalculateNormals())
.Invoke(rays.HitIdx,
rays.Intersection,
rays.NormalX,
rays.NormalY,
rays.NormalZ,
CoordsHandle,
CylIds);
vtkm::worklet::DispatcherMapField<detail::GetScalar<Precision>>(
detail::GetScalar<Precision>(vtkm::Float32(scalarRange.Min), vtkm::Float32(scalarRange.Max)))
.Invoke(rays.HitIdx, rays.Scalar, *scalarField, CylIds);
}
void CylinderIntersector::IntersectionData(Ray<vtkm::Float32>& rays,
const vtkm::cont::Field* scalarField,
const vtkm::Range& scalarRange)
{
IntersectionDataImp(rays, scalarField, scalarRange);
}
void CylinderIntersector::IntersectionData(Ray<vtkm::Float64>& rays,
const vtkm::cont::Field* scalarField,
const vtkm::Range& scalarRange)
{
IntersectionDataImp(rays, scalarField, scalarRange);
}
vtkm::Id CylinderIntersector::GetNumberOfShapes() const
{
return CylIds.GetNumberOfValues();
}
}
}
} //namespace vtkm::rendering::raytracing
| 31.712401 | 97 | 0.594059 | [
"mesh"
] |
82beddc57d6e1bf801db6a068d279ffc3cd913f7 | 51,350 | cpp | C++ | oneEngine/oneGame/source/physical/animation/CHKAnimation.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/physical/animation/CHKAnimation.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/physical/animation/CHKAnimation.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z |
#include "CHKAnimation.h"
#include "set/CHKAnimationSet.h"
/*
#include "Animation/Animation/Rig/hkaSkeletonUtils.h"
#include "Animation/Animation/Ik/TwoJoints/hkaTwoJointsIkSolver.h"
#include "Animation/Animation/Ik/LookAt/hkaLookAtIkSolver.h"
#include "Animation/Animation/Ik/FootPlacement/hkaFootPlacementIkSolver.h"
*/
//#include "RrCModel.h"
//#include "core/time/time.h"
#include "physical/skeleton/skeletonBone.h"
#include "physical/physics/CPhysics.h"
//#include "RrDebugDrawer.h"
Vector3f CHKAnimation::defaultJointVector (0,0,-1);
// class hkWorldCaster
// Class used by the IK to check collisions against the world.
/*class hkWorldCaster : public hkaRaycastInterface
{
public:
virtual hkBool castRay (const hkVector4 &fromWS, const hkVector4 &toWS, hkReal &hitFractionOut, hkVector4 &normalWSOut) override
{
return castRay( fromWS,toWS, Physics::GetCollisionFilter( Layers::PHYS_WORLD_TRACE ), hitFractionOut,normalWSOut );
}
virtual hkBool castRay (const hkVector4 &fromWS, const hkVector4 &toWS, hkUint32 collisionFilterInfo, hkReal &hitFractionOut, hkVector4 &normalWSOut) override
{
// Create the raycast information.
hkpWorldRayCastInput hkInputCastRay;
// Set the start position of the ray
hkInputCastRay.m_from = fromWS;
// Set the end position of the ray
hkInputCastRay.m_to = toWS;
// Set the ray's collision mask
hkInputCastRay.m_filterInfo = collisionFilterInfo;
// Create a ray hit accumulation object
{
hkpClosestRayHitCollector hkRayHitCollection;
// Cast a ray into the lovely world
//CPhysics::World()->castRay ( hkInputCastRay, hkRayHitCollection );
CPhysics::Raycast ( hkInputCastRay, hkRayHitCollection );
// If the collection has a hit recorded, then we want to grab the hit info.
// Otherwise, we want to set the outHitInfo to report no hit.
if ( hkRayHitCollection.hasHit() )
{
// Grab the hit info
hkpWorldRayCastOutput hkRayHitOutput = hkRayHitCollection.getHit();
hitFractionOut = hkRayHitOutput.m_hitFraction;
normalWSOut = hkRayHitOutput.m_normal;
return true;
}
}
return false;
}
};*/
// class animLerper
// Utility class used to blend a value "smoothly" to another value
class animLerper
{
public:
explicit animLerper ( const Real deltaTime ) : delta(deltaTime)
{
;
}
void operator() ( Real& io_value, const Real& n_target )
{
io_value += ( n_target - io_value ) * std::min<Real>( 0.5f*delta*40.0f, 0.97f );
}
private:
Real delta;
};
// Returns the ragdoll pose int vModelSkelly
void CHKAnimation::GetRagdollPose( skeletonBone_t* rootBone, std::vector<skeletonBone_t*> &vModelSkelly )
{
throw core::NotYetImplementedException();
//hkArray<hkQsTransform> nextTransforms;
//nextTransforms.setSize( mSkelly->m_bones.getSize() );
//hkArray<hkReal> tempReals;
//tempReals.setSize( mSkelly->m_bones.getSize() );
//hkaAnimation* mhkAnim = ((CHKAnimationSet*)pAnimationSet)->GetHKAnimation()->at(0);
//mhkAnim->sampleTracks( 0.0f, nextTransforms.begin(), tempReals.begin() );
//// set the ragdoll pose : D
//for ( int i = 0; i < nextTransforms.getSize(); ++i )
//{
// XTransform localTransform;
// localTransform.position = Vector3f(
// nextTransforms[i].m_translation.getComponent<0>(),
// nextTransforms[i].m_translation.getComponent<1>(),
// nextTransforms[i].m_translation.getComponent<2>() );
// localTransform.rotation = Quaternion(
// nextTransforms[i].m_rotation.m_vec.getComponent<0>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<1>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<2>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<3>() );
// localTransform.scale = Vector3f(
// nextTransforms[i].m_scale.getComponent<0>(),
// nextTransforms[i].m_scale.getComponent<1>(),
// nextTransforms[i].m_scale.getComponent<2>() );
// vModelSkelly[i]->animTransform = localTransform;
//}
//for ( int i = 0; i < nextTransforms.getSize(); ++i )
//{
// vModelSkelly[i]->SendTransformation();
// vModelSkelly[i]->transform.LateUpdate();
// vModelSkelly[i]->xRagdollPoseModel = XTransform(
// vModelSkelly[i]->transform.position, vModelSkelly[i]->transform.rotation, vModelSkelly[i]->transform.scale );
//}
}
// Cleanup
CHKAnimation::~CHKAnimation ( void )
{
throw core::NotYetImplementedException();
////delete mSkelly;
//mSkelly->removeReference();
////mAnimSkelly->removeReference();
//if ( mMirrorSkelly ) {
// mMirrorSkelly->removeReference();
//}
///*if ( mMirrorAnim ) {
// mMirrorAnim->removeReference();
//}*/
//for ( uint i = 0; i < mMirrorAnims.size(); ++i )
//{
// mMirrorAnims.at(i)->removeReference();
//}
}
void CHKAnimation::SkeletonToHkaSkeleton ( void )
{
throw core::NotYetImplementedException();
}
void CHKAnimation::Update ( const Real deltaTime )
{
throw core::NotYetImplementedException();
// // Create binding
// if ( mAnimBinding == NULL ) {
// mAnimBinding = new hkaAnimationBinding();
// mAnimBinding->m_animation = ((CHKAnimationSet*)pAnimationSet)->GetHKAnimation()->at(0);
// for ( hkInt16 i = 0; i < mSkelly->m_bones.getSize(); ++i ) {
// mAnimBinding->m_transformTrackToBoneIndices.pushBack(i);
// mAnimBinding->m_floatTrackToFloatSlotIndices.pushBack(i);
// }
// }
// // Setup mirrored animations
// //SetupMirrorMode();
//
// bool bFirstAnim = true;
// bool bFirstAimr = true;
// bool bHasAimr = false;
// Real fAimrWeight, fAimrBlend = 0.0f;
// Real fPropWeight [4] = {1,1,1,1};
//
// // Create temporary arrays
// hkArray<hkQsTransform> nextTransforms;
// nextTransforms.setSize( mSkelly->m_bones.getSize() );
// for ( int i = 0; i < nextTransforms.getSize(); ++i )
// {
// nextTransforms[i] = hkQsTransform(hkQsTransform::ZERO);
// }
// hkArray<hkQsTransform> tempTransforms;
// tempTransforms.setSize( mSkelly->m_bones.getSize() );
// tempTransforms = mSkelly->m_referencePose;
//
// hkArray<hkQsTransform> tempTransformsAdditive;
// tempTransformsAdditive.setSize( mSkelly->m_bones.getSize() );
// tempTransformsAdditive = mSkelly->m_referencePose;
//
// hkArray<hkQsTransform> aimrTransforms;
// aimrTransforms.setSize( mSkelly->m_bones.getSize() );
// aimrTransforms = mSkelly->m_referencePose;
//
// hkArray<hkQsTransform> refrTransforms;
// refrTransforms.setSize( mSkelly->m_bones.getSize() );
// refrTransforms = mSkelly->m_referencePose;
//
// hkArray<hkReal> tempReals;
// tempReals.setSize( mSkelly->m_bones.getSize() );
//
// //hkaAnimation* mhkAnim = ((CHKAnimationSet*)pAnimationSet)->GetHKAnimation();
// //hkaAnimation* mhkAnim = mMirrorAnim;
// /*if ( mhkAnim->m_numberOfTransformTracks == 0 )
// {
// std::cout << "Bad animation set on hkaAnimation: " << mhkAnim << std::endl;
// return;
// }*/
// std::vector<hkaAnimation*>* mAnim = ((CHKAnimationSet*)pAnimationSet)->GetHKAnimation();
// if ( !mMirrorAnims.empty() ) {
// mAnim = &mMirrorAnims;
// }
//
// // If no animations, just sample reference pose (frame0) and call it good
// if ( mAnimations.size() <= 2 )
// {
// //mhkAnim->sampleTracks( 1/30.0f, nextTransforms.begin(), tempReals.begin() );
// mAnim->at(0)->sampleTracks( 0.0f, nextTransforms.begin(), tempReals.begin() );
//
// hkaPose skeletonPose ( hkaPose::LOCAL_SPACE, mSkelly, nextTransforms );
// nextTransforms = skeletonPose.getSyncedPoseLocalSpace();
//
// for ( int i = 0; i < nextTransforms.getSize(); ++i )
// {
// ((XTransform*)animRefs[i])->position = Vector3f(
// nextTransforms[i].m_translation.getComponent<0>(),
// nextTransforms[i].m_translation.getComponent<1>(),
// nextTransforms[i].m_translation.getComponent<2>() );
// ((XTransform*)animRefs[i])->rotation = Quaternion(
// nextTransforms[i].m_rotation.m_vec.getComponent<0>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<1>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<2>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<3>() );
// ((XTransform*)animRefs[i])->scale = Vector3f(
// nextTransforms[i].m_scale.getComponent<0>(),
// nextTransforms[i].m_scale.getComponent<1>(),
// nextTransforms[i].m_scale.getComponent<2>() );
// }
// return;
// }
//
// { // Set default aimrTransforms
// mAnim->at(0)->sampleTracks( 0.0f, aimrTransforms.begin(), tempReals.begin() );
// mAnim->at(0)->sampleTracks( 0.0f, refrTransforms.begin(), tempReals.begin() );
// }
//
// // Before sampling actions, need to check events
// if ( bEventsRead ) {
// vEvents.clear();
// bEventsRead = false;
// }
// // Reset model motion
// vModelMotion = Vector3f(0,0,0);
//
// // Need to update smooth faders
// for ( auto it = fadeOutList.begin(); it != fadeOutList.end(); )
// {
// it->first->weight -= deltaTime / it->second;
// if ( it->first->weight <= 0 ) {
// //it->first->isPlaying = false;
// //it->first->weight = 0;
// it->first->Stop();
// it = fadeOutList.erase(it);
// }
// else {
// ++it;
// }
// }
//
// // Normalize weights
// for ( uchar i = 0; i < maxLayers; ++i ) {
// Normalize( i );
// }
//
// // First, loop through all the animations to setup sync tracks and the event system.
// AnimationAction* syncMaxers [5] = {0,0,0,0,0};
// Real syncFrames [5] = {0,0,0,0,0};
// AnimationAction* eventMaster = NULL;
// {
// std::map<string,AnimationAction>::iterator it = mAnimations.begin(); // Loop thru all the actions
// while ( it != mAnimations.end() )
// {
// AnimationAction& currentAction = it->second;
//
// // Setup sync-tracks
// if ( currentAction.sync_track )
// {
// if ( (syncMaxers[currentAction.sync_track] == NULL) || (syncMaxers[currentAction.sync_track]->weight < currentAction.weight) )
// {
// if ( syncMaxers[currentAction.sync_track] ) {
// syncMaxers[currentAction.sync_track]->SetMasterState( false );
// }
// currentAction.SetMasterState( true );
// syncMaxers[currentAction.sync_track] = ¤tAction;
// syncFrames[currentAction.sync_track] = currentAction.frame;
// }
// else
// {
// currentAction.SetMasterState( false );
// }
// }
//
// // Setup event system
// currentAction.SetEventsState(false);
// //if ( eventMaster == NULL || (currentAction.weight > 0.04f && eventMaster->weight < currentAction.weight && eventMaster->layer >= currentAction.layer) )
// if ( (currentAction.weight > 0.04f && currentAction.isPlaying) && (eventMaster == NULL || (eventMaster->layer < currentAction.layer) || (eventMaster->weight < currentAction.weight && eventMaster->layer <= currentAction.layer)) )
// {
// if ( eventMaster != NULL ) {
// eventMaster->SetEventsState(false);
// }
// eventMaster = ¤tAction;
// eventMaster->SetEventsState(true);
// }
//
// it++;
// }
// }
//
// // Loop through all the layers
// //if ( mAnimations.size() > 0 )
// //{
// for ( unsigned char layer = 0; layer < maxLayers; layer++ )
// {
// std::map<string,AnimationAction>::iterator it = mAnimations.begin(); // Loop thru all the actions
// do
// {
// AnimationAction& currentAction = it->second;
//
// // Check for a layer limit
// if ( currentAction.layer >= maxLayers )
// currentAction.layer = maxLayers-1;
// // And only sample+update the animation if it's on the current layer
// if ( currentAction.layer == layer )
// {
// // Update the animation
// currentAction.Update( deltaTime, syncFrames[currentAction.sync_track] );
//
// // Now, check the weight for valid values
// if ( currentAction.weight > 1 )
// currentAction.weight = 1;
// // And only sample if the weight is larger than zero
// if ( currentAction.weight > 0.001f )
// {
// Real currentTime;
// //currentTime = ( currentAction.GetStart()+currentAction.frame ) * (1/30.0f);
// currentTime = currentAction.frame * (1/30.0f);
//
// // Increase the weight to full if this is the first animation to be sampled
// Real temp = currentAction.weight;
// if ( bFirstAnim ) {
// currentAction.weight = 1;
// }
// // Increase the aimr weight to full and copy over the pose if this is the first aimr transform to be sampled
// if ( currentAction.tag == AnimationAction::TAG_ITEM ) {
// fAimrWeight = currentAction.weight;
// if ( !bHasAimr ) {
// // Set weight to full
// fAimrWeight = 1;
// bHasAimr = true;
// }
// }
//
// // Sample tracks
// //mhkAnim->sampleTracks( currentTime, tempTransforms.begin(), tempReals.begin() );
// mAnim->at(currentAction.index)->sampleTracks( currentTime, tempTransforms.begin(), tempReals.begin() );
// // Sample track first frame if needed
// if ( currentAction.extrapolateMotion[0] || currentAction.extrapolateMotion[1] || currentAction.extrapolateMotion[2] ) {
// //mAnim->at(0)->sampleTracks( currentAction.GetStart() * (1/30.0f), tempTransformsAdditive.begin(), tempReals.begin() );
// mAnim->at(currentAction.index)->sampleTracks( 0.0f, tempTransformsAdditive.begin(), tempReals.begin() );
// }
//
// // Mix the tracks
// std::vector<int> *pMixingList = currentAction.GetMixingList();
// if ( pMixingList->size() == 0 )
// {
// // Mix into the entire list
// for ( int i = 0; i < tempTransforms.getSize(); ++i )
// {
// // Aimer IK
// if ( currentAction.tag == AnimationAction::TAG_ITEM ) {
// aimrTransforms[i].setInterpolate4( aimrTransforms[i], tempTransforms[i], fAimrWeight );
// fAimrBlend += fAimrWeight;
// }
// // Motion extrapolation
// if ( i == 0 ) {
// Real speed = (currentAction.framesPerSecond/30.0f) * currentAction.playSpeed * (deltaTime * 30.0f);
// Real t_weight = currentAction.weight * speed;
// if ( currentAction.extrapolateMotion[0] ) {
// if ( currentAction.enableMotionExtrapolation[0] ) {
// vModelMotion.x += t_weight * (tempTransforms[i].getTranslation().getComponent<0>() - tempTransformsAdditive[i].getTranslation().getComponent<0>());
// }
// tempTransforms[i].m_translation.setComponent<0>( tempTransformsAdditive[i].getTranslation().getComponent<0>() );
// }
// if ( currentAction.extrapolateMotion[1] ) {
// if ( currentAction.enableMotionExtrapolation[1] ) {
// vModelMotion.y += t_weight * (tempTransforms[i].getTranslation().getComponent<1>() - tempTransformsAdditive[i].getTranslation().getComponent<1>());
// }
// tempTransforms[i].m_translation.setComponent<1>( tempTransformsAdditive[i].getTranslation().getComponent<1>() );
// }
// if ( currentAction.extrapolateMotion[2] ) {
// if ( currentAction.enableMotionExtrapolation[2] ) {
// vModelMotion.z += t_weight * (tempTransforms[i].getTranslation().getComponent<2>() - tempTransformsAdditive[i].getTranslation().getComponent<2>());
// }
// tempTransforms[i].m_translation.setComponent<2>( tempTransformsAdditive[i].getTranslation().getComponent<2>() );
// }
// }
// // Last, sample the animation
// nextTransforms[i].setInterpolate4( nextTransforms[i], tempTransforms[i], currentAction.weight );
// }
// }
// else
// {
// // Mix into the list specially
// int index;
// for ( uint32_t i = 0; i < pMixingList->size(); ++i )
// {
// index = (*pMixingList)[i];
// nextTransforms[index].setInterpolate4( nextTransforms[index], tempTransforms[index], currentAction.weight );
// // Aimer IK
// if ( currentAction.tag == AnimationAction::TAG_ITEM ) {
// aimrTransforms[index].setInterpolate4( aimrTransforms[index], tempTransforms[index], fAimrWeight );
// }
// // Motion extrapolation
// if ( index == 0 ) {
// if ( currentAction.extrapolateMotion[0] && currentAction.enableMotionExtrapolation[0] ) {
// vModelMotion.x += currentAction.weight * tempTransforms[index].getTranslation().getComponent<0>();
// }
// if ( currentAction.extrapolateMotion[1] && currentAction.enableMotionExtrapolation[1] ) {
// vModelMotion.y += currentAction.weight * tempTransforms[index].getTranslation().getComponent<1>();
// }
// if ( currentAction.extrapolateMotion[2] && currentAction.enableMotionExtrapolation[2] ) {
// vModelMotion.z += currentAction.weight * tempTransforms[index].getTranslation().getComponent<2>();
// }
// }
// }
// }
//
// if ( currentAction.tag == AnimationAction::TAG_ITEM && bFirstAimr ) {
// // Mix into the entire list
// for ( int i = 0; i < tempTransforms.getSize(); ++i )
// {
// //nextTransforms[i].setInterpolate4( nextTransforms[i], tempTransforms[i], currentAction.weight );
// // Aimer IK
// aimrTransforms[i].setInterpolate4( aimrTransforms[i], tempTransforms[i], fAimrWeight );
// fAimrBlend += fAimrWeight;
// }
// }
//
// // Perform prop weights
// fPropWeight[0] -= currentAction.prop_override[0];
// fPropWeight[1] -= currentAction.prop_override[1];
// fPropWeight[2] -= currentAction.prop_override[2];
// fPropWeight[3] -= currentAction.prop_override[3];
//
// // Restore previous weight
// currentAction.weight = temp;
// bFirstAnim = false; // No longer first animation to be sampled.
// if ( bHasAimr ) {
// bFirstAimr = false;
// }
// }
// }
//
// it++;
// }
// while ( it != mAnimations.end() );
// }
// //}
//
// // If no animations sampled, grab first frame
// if ( bFirstAnim )
// {
// //mhkAnim->sampleTracks( 1/30.0f, tempTransforms.begin(), tempReals.begin() );
// mAnim->at(0)->sampleTracks( 0.0f, tempTransforms.begin(), tempReals.begin() );
// // Mix into the entire list
// for ( int i = 0; i < tempTransforms.getSize(); ++i )
// {
// nextTransforms[i] = tempTransforms[i];
// }
// }
//
// /*if ( bHasAimr )
// {
// // Mix into the entire list
// for ( int i = 0; i < tempTransforms.getSize(); ++i )
// {
// nextTransforms[i] = aimrTransforms[i];
// }
// }*/
//
//#if defined(_ENGINE_DEBUG) && defined(_ENGINE_SAFE_CHECK_)
// // CHECK FUCKING EVERYTHING
// for ( int i = 0; i < tempTransforms.getSize(); ++i ) {
// if ( !tempTransforms[i].isOk() )
// cout << "BAD SHIT ON TT" << i << endl;
// }
// for ( int i = 0; i < nextTransforms.getSize(); ++i ) {
// if ( !nextTransforms[i].isOk() )
// cout << "BAD SHIT ON NT" << i << endl;
// }
// for ( int i = 0; i < aimrTransforms.getSize(); ++i ) {
// if ( !aimrTransforms[i].isOk() )
// cout << "BAD SHIT ON AM" << i << endl;
// }
//#endif
// fAimrBlend = std::max<Real>( 0, std::min<Real>( 1, fAimrBlend ) );
//
// // Create the pose
// hkaPose skeletonPose ( hkaPose::LOCAL_SPACE, mSkelly, nextTransforms );
// hkaPose referencePose ( hkaPose::LOCAL_SPACE, mSkelly, mSkelly->m_referencePose );
// //skeletonPose.syncModelSpace();
// //referencePose.syncModelSpace();
//
// // Grab the proper model scale
// hkVector4 t_modelScale;
// {
// t_modelScale = mSkelly->m_referencePose[0].m_scale;
// if ( fabs( t_modelScale.getComponent<0>().getReal() - 1.0f ) < 0.01f )
// {
// t_modelScale = mSkelly->m_referencePose[1].m_scale;
// }
// }
//
// // Create the model-to-world and world-to-model transforms
// hkQsTransform modelToWorld;
// {
// // First scale up by mSkelly->m_referencePose[0].m_scale
// // Next translate by skeletonPose.getBoneModelSpace( 0 ).getTranslation()
// // Next rotate by model->transform.rotation
// // Next translate by model->transform.position
// hkVector4 trans1pos = skeletonPose.getBoneModelSpace( 0 ).getTranslation();
// //trans1pos.div( mSkelly->m_referencePose[0].m_scale );
// hkQsTransform trans0(hkQsTransform::IDENTITY); trans0.setTranslation( trans1pos );
// //hkQuaternion trans1quat; trans1quat.setInverse( skeletonPose.getBoneModelSpace( 0 ).getRotation() );
// hkQsTransform trans1(hkQsTransform::IDENTITY); //trans1.setRotation( trans1quat );
// hkQsTransform trans2(hkQsTransform::IDENTITY); trans2.setScale( t_modelScale );
// //Quaternion trans3quat = pOwner->transform.rotation.getQuaternion();
// Quaternion trans3quat = mModelTransform.rotation;
// hkQsTransform trans3(hkQsTransform::IDENTITY); trans3.setRotation( hkQuaternion(trans3quat.x,trans3quat.y,trans3quat.z,trans3quat.w) );
// //hkQsTransform trans4(hkQsTransform::IDENTITY); trans4.setTranslation( hkVector4( pOwner->transform.position.x, pOwner->transform.position.y, pOwner->transform.position.z ) );
// hkQsTransform trans4(hkQsTransform::IDENTITY); trans4.setTranslation( hkVector4( mModelTransform.position.x, mModelTransform.position.y, mModelTransform.position.z ) );
//
// hkQsTransform transt0, transt1;
// transt0.setMulScaled( trans2, trans1 );
// transt1.setMulScaled( trans0, transt0 );
// transt0.setMulScaled( trans3, transt1 );
// modelToWorld.setMulScaled( trans4, transt0 );
// }
// hkQsTransform worldToModel;
// {
// // First move to engine-model space by subtracting position, then rotating by model inverse
// // Then subtract by the root bone
// // Then scale down by the scaling
// //hkQsTransform trans0(hkQsTransform::IDENTITY); trans0.setTranslation( hkVector4( -pOwner->transform.position.x, -pOwner->transform.position.y, -pOwner->transform.position.z ) );
// hkQsTransform trans0(hkQsTransform::IDENTITY); trans0.setTranslation( hkVector4( -mModelTransform.position.x, -mModelTransform.position.y, -mModelTransform.position.z ) );
// //Quaternion trans1quat = pOwner->transform.rotation.inverse().getQuaternion();
// Quaternion trans1quat = Rotator(mModelTransform.rotation).inverse().getQuaternion();
// hkQsTransform trans1(hkQsTransform::IDENTITY); trans1.setRotation( hkQuaternion(trans1quat.x,trans1quat.y,trans1quat.z,trans1quat.w) );
// hkVector4 trans2pos; trans2pos.setNeg3( skeletonPose.getBoneModelSpace( 0 ).getTranslation() ); trans2pos.zeroElement(3);
// hkQsTransform trans2(hkQsTransform::IDENTITY); trans2.setTranslation( trans2pos );
// hkVector4 trans3scal (1,1,1,1); trans3scal.div4( t_modelScale ); trans3scal.zeroElement(3);
// hkQsTransform trans3(hkQsTransform::IDENTITY); trans3.setScale( trans3scal );
//
// hkQsTransform transt0, transt1;
// transt0.setMulScaled( trans1, trans0 );
// transt1.setMulScaled( trans2, transt0 );
// worldToModel.setMulScaled( trans3, transt1 );
// }
//
// // Do IK
// int32_t headBone = -1, leyeBone = -1, reyeBone = -1;
// int32_t t_footIK_count = 0;
// int32_t t_aimrIK_count = 0;
// hkReal t_verticalOffset = 0;
// Real t_aimrIK_pushval = 0;
// // Do IK Prepass
// for ( uint i = 0; i < ikList.size(); ++i )
// {
// switch ( ikList[i].type )
// {
// case kModelIkLookAt:
// headBone = ikList[i].bone[0];
// leyeBone = ikList[i].bone[1];
// reyeBone = ikList[i].bone[2];
// break;
// case kModelIkFootstep:
// {
// // Perform ankle changes (lift up the character, because of digitgrade feet)
// if ( ikList[i].subinfo[0] > FTYPE_PRECISION )
// {
// // Calculate amount the model needs to be pushed up by
// hkReal verticalValue = 0;
// {
// hkVector4 footDistance = skeletonPose.getBoneModelSpace( ikList[i].bone[0] ).m_translation;
// footDistance.setComponent<1>( footDistance.getComponent<1>().getReal() * 0.1f );
// footDistance.setComponent<2>(0);
//
// verticalValue += std::max<hkReal>( 0, 20.0f - footDistance.length3() ) * 0.015f;
// }
// // Push up the model
// hkVector4 verticalOffset ( 0,0,verticalValue * ikList[i].subinfo[0] );
// skeletonPose.accessBoneModelSpace( 0, hkaPose::PROPAGATE ).m_translation.add( verticalOffset );
// t_verticalOffset += verticalValue;
// }
// }
// break;
// }
// }
// // Do IK Main Pass
// for ( uint i = 0; i < ikList.size(); ++i )
// {
// switch ( ikList[i].type )
// {
// case kModelIkLookAt:
// if ( ikList[i].enabled )
// {
// // Apply first transform based on old model rotation
// /*hkQuaternion prev_feedback( ikList[i].subinfo[0], ikList[i].subinfo[1], ikList[i].subinfo[2], ikList[i].subinfo[3] );
// if ( prev_feedback.isOk() )
// {
// skeletonPose.accessBoneLocalSpace( headBone ).m_rotation.setSlerp( skeletonPose.accessBoneLocalSpace( headBone ).m_rotation, prev_feedback, 0.5 );
// skeletonPose.syncModelSpace();
// }*/
//
// // Do the Head IK
//
// // Generate the Eye offset from the head base
// int32_t leyeBone = ikList[i].bone[1];
// int32_t reyeBone = ikList[i].bone[2];
// hkVector4 offset = referencePose.getBoneLocalSpace(leyeBone).getTranslation();
// offset.add( referencePose.getBoneLocalSpace(reyeBone).getTranslation() );
// offset.mul( 0.5f );
// offset.set( offset.getComponent(2), -offset.getComponent(1), offset.getComponent(0) );
//
// hkVector4 temp;
// // Create the target
// hkVector4 target = hkVector4( ikList[i].input.x, ikList[i].input.y, ikList[i].input.z );
// temp.setTransformedPos( worldToModel, target );
// //temp.sub( hkVector4(0,0,t_verticalOffset) );
// target = temp;
//
// // Create the second target
// hkVector4 subtarget = hkVector4( ikList[i].subinput0.x, ikList[i].subinput0.y, ikList[i].subinput0.z );
// temp.setTransformedPos( worldToModel, subtarget );
// //temp.sub( hkVector4(0,0,t_verticalOffset) );
// subtarget = temp;
//
// // "pose" is an hkaPose object that contains the current pose of our character
// hkaLookAtIkSolver::Setup setup;
// setup.m_fwdLS.set( 0,1,0 );
// setup.m_eyePositionLS = offset;
// setup.m_limitAxisMS.set( 0,-1,0 );
// setup.m_limitAxisMS.setRotatedDir( skeletonPose.getBoneModelSpace(ikList[i].bone[0]-1).getRotation(), hkVector4(0,1,0) );
// setup.m_limitAngle = HK_REAL_PI / 2.6f;
// // By using the PROPAGATE flag, all children of the head bone will be modified alongside the head
// // (their local transforms will remain constant)
// hkQuaternion t_prevrot = skeletonPose.getBoneModelSpace( headBone ).m_rotation;
// hkaLookAtIkSolver::solve (
// setup, target,
// 1.0f, skeletonPose.accessBoneModelSpace( headBone,hkaPose::PROPAGATE )
// );
// //skeletonPose.syncLocalSpace();
//
// // Solve for the eyes now
// subtarget.m_quad.v[2] += offset.getComponent(0);
// setup.m_fwdLS.set( 1,0,0 );
// setup.m_eyePositionLS.set( 0,0,0 );
// setup.m_limitAxisMS.setRotatedDir( skeletonPose.getBoneModelSpace(ikList[i].bone[0]).getRotation(), hkVector4(0,1,0) );
// setup.m_limitAngle = HK_REAL_PI / 1.0f;
// hkaLookAtIkSolver::solve (
// setup, subtarget,
// 1.0f, skeletonPose.accessBoneModelSpace( leyeBone,hkaPose::PROPAGATE )
// );
// setup.m_limitAxisMS.setRotatedDir( skeletonPose.getBoneModelSpace(ikList[i].bone[0]).getRotation(), hkVector4(0,1,0) );
// hkaLookAtIkSolver::solve (
// setup, subtarget,
// 1.0f, skeletonPose.accessBoneModelSpace( reyeBone,hkaPose::PROPAGATE )
// );
// //skeletonPose.syncLocalSpace();
//
// // Now feedback the head rotation
// hkQuaternion feedback = skeletonPose.getBoneLocalSpace( headBone ).getRotation();
// ikList[i].subinfo[0] = feedback.getComponent<0>();
// ikList[i].subinfo[1] = feedback.getComponent<1>();
// ikList[i].subinfo[2] = feedback.getComponent<2>();
// ikList[i].subinfo[3] = feedback.getComponent<3>();
// }
// break;
// case kModelIkAiming:
// if ( true /*bHasAimr && ikList[i].enabled*/ )
// {
// // Do AIMING IK
// hkaPose aimrPose ( hkaPose::LOCAL_SPACE, mSkelly, aimrTransforms );
// hkaPose refrPose ( hkaPose::LOCAL_SPACE, mSkelly, refrTransforms );
//
// //skeletonPose.syncModelSpace(); // Update the model space first
//
// t_aimrIK_count += 1;
// // Only perform spine aiming on the first aimer
// if ( t_aimrIK_count == 1 )
// {
// hkQsTransform spineTransform;
// hkQuaternion offsetRotation;
// hkQuaternion resultRotation;
//
// animLerper lerpHelp(deltaTime);
//
// // Perform spine rotations
// Real t_weightSpine = ikList[i].subinput0.y;
// if ( t_weightSpine > 0 )
// {
// lerpHelp( mSpineBlends[0], t_weightSpine );
//
// spineTransform = skeletonPose.getBoneModelSpace( ikList[i].bone[0] );
// offsetRotation.setAxisAngle( hkVector4(1,0,0), (Real)-degtorad(ikList[i].input.z*mSpineBlends[0]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
// spineTransform.m_rotation = resultRotation;
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].input.x*mSpineBlends[0]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( ikList[i].bone[0], spineTransform, hkaPose::PROPAGATE );
//
// t_aimrIK_pushval += mSpineBlends[0];
// }
// t_weightSpine -= ikList[i].subinput0.z;
// if ( t_weightSpine > 0 )
// {
// lerpHelp( mSpineBlends[1], t_weightSpine );
//
// spineTransform = skeletonPose.getBoneModelSpace( ikList[i].bone[1] );
// offsetRotation.setAxisAngle( hkVector4(1,0,0), (Real)-degtorad(ikList[i].input.z*mSpineBlends[1]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
// spineTransform.m_rotation = resultRotation;
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].input.x*mSpineBlends[1]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( ikList[i].bone[1], spineTransform, hkaPose::PROPAGATE );
//
// t_aimrIK_pushval += mSpineBlends[1];
// }
// t_weightSpine -= ikList[i].subinput0.z;
// if ( t_weightSpine > 0 )
// {
// lerpHelp( mSpineBlends[2], t_weightSpine );
//
// spineTransform = skeletonPose.getBoneModelSpace( ikList[i].bone[2] );
// offsetRotation.setAxisAngle( hkVector4(1,0,0), (Real)-degtorad(ikList[i].input.z*mSpineBlends[2]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
// spineTransform.m_rotation = resultRotation;
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].input.x*mSpineBlends[2]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( ikList[i].bone[2], spineTransform, hkaPose::PROPAGATE );
//
// t_aimrIK_pushval += mSpineBlends[2];
// }
// // Perform additional faceat rotations
// {
// spineTransform = skeletonPose.getBoneModelSpace( ikList[i].bone[0] );
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].subinput1.y*0.444f) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( ikList[i].bone[0], spineTransform, hkaPose::PROPAGATE );
// }
// {
// spineTransform = skeletonPose.getBoneModelSpace( ikList[i].bone[1] );
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].subinput1.y*0.333f) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( ikList[i].bone[1], spineTransform, hkaPose::PROPAGATE );
// }
// {
// spineTransform = skeletonPose.getBoneModelSpace( ikList[i].bone[2] );
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].subinput1.y*0.222f) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( ikList[i].bone[2], spineTransform, hkaPose::PROPAGATE );
// }
// // Perform neck and head rotations
// {
// lerpHelp( mSpineBlends[3], ikList[i].subinput0.x );
//
// spineTransform = skeletonPose.getBoneModelSpace( headBone );
// offsetRotation.setAxisAngle( hkVector4(1,0,0), (Real)-degtorad(ikList[i].input.z*mSpineBlends[3]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
// spineTransform.m_rotation = resultRotation;
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].input.x*mSpineBlends[3]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( headBone, spineTransform, hkaPose::PROPAGATE );
//
// t_aimrIK_pushval += mSpineBlends[3];
// }
// {
// lerpHelp( mSpineBlends[4], ikList[i].subinput1.x );
//
// spineTransform = skeletonPose.getBoneModelSpace( headBone-1 );
// offsetRotation.setAxisAngle( hkVector4(1,0,0), (Real)-degtorad(ikList[i].input.z*mSpineBlends[4]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
// spineTransform.m_rotation = resultRotation;
// offsetRotation.setAxisAngle( hkVector4(0,0,1), (Real)-degtorad(ikList[i].input.x*mSpineBlends[4]) );
// resultRotation.setMul( offsetRotation, spineTransform.m_rotation );
//
// spineTransform.m_rotation = resultRotation;
// skeletonPose.setBoneModelSpace( headBone-1, spineTransform, hkaPose::PROPAGATE );
//
// t_aimrIK_pushval += mSpineBlends[4];
// }
//
// // Update all space
// //skeletonPose.syncAll();
// }
//
// if ( bHasAimr )
// {
// for ( uint bb = 3; bb < 5; ++bb )
// {
// // First get the target position in model space
// hkQsTransform wristModelSource = aimrPose.getBoneModelSpace(ikList[i].bone[bb]+2); // Wrist bone
//
// hkQsTransform headModelAimer = aimrPose.getBoneModelSpace(headBone);
// hkQsTransform leyeModelAimer = aimrPose.getBoneModelSpace(leyeBone);
// hkQsTransform reyeModelAimer = aimrPose.getBoneModelSpace(reyeBone);
// hkQsTransform headModelTrans = skeletonPose.getBoneModelSpace(headBone);
// hkQsTransform leyeModelTrans = skeletonPose.getBoneModelSpace(leyeBone);
// hkQsTransform reyeModelTrans = skeletonPose.getBoneModelSpace(reyeBone);
// hkVector4 vBasePos, vOffsetPos;
// // vBasePos.setAdd( leyeModelAimer.m_translation, reyeModelAimer.m_translation );
// //vOffsetPos.setAdd( leyeModelTrans.m_translation, reyeModelTrans.m_translation );
// vBasePos = headModelAimer.m_translation;
// vOffsetPos = headModelTrans.m_translation;
//
// hkVector4 vHeadDistance;
// vHeadDistance.setSub( wristModelSource.getTranslation(), vBasePos );
//
// // Rotate the dif vect
// hkQuaternion lookatRot;
// Real t_armOffset = std::max<Real>( ikList[i].input.z, -10-70*ikList[i].subinfo[2] ) * std::max<Real>( 0, 1.0f - t_aimrIK_pushval + 0.2f*ikList[i].subinfo[2] );
// lookatRot.setAxisAngle( hkVector4(1,0,0), -(hkReal)degtorad(t_armOffset) );
// vHeadDistance.setRotatedDir( lookatRot, vHeadDistance );
//
// // Move to current head space
// hkVector4 vInvRotatedHeadDistance;
// vInvRotatedHeadDistance.setRotatedInverseDir( headModelAimer.m_rotation, vHeadDistance );
// vHeadDistance.setRotatedDir( headModelTrans.m_rotation, vInvRotatedHeadDistance );
//
// // Generate the target position by using the current skeleton
// hkVector4 targetPosition;
// targetPosition.setAdd( vHeadDistance, vOffsetPos );
///*
//#ifdef _ENGINE_DEBUG // Draw the wrist positions
// hkVector4 targetWorldPosition;
// targetWorldPosition.setTransformedPos( modelToWorld, targetPosition );
// Vector3f result ( targetWorldPosition.getComponent<0>(), targetWorldPosition.getComponent<1>(), targetWorldPosition.getComponent<2>() );
// debug::Drawer->DrawLine( result-Vector3f(0,0.5f,0), result+Vector3f(0,0.5f,0), Color(1,0,1,1) );
// debug::Drawer->DrawLine( result-Vector3f(0,0,0.5f), result+Vector3f(0,0,0.5f), Color(1,0,1,1) );
// debug::Drawer->DrawLine( result-Vector3f(0.5f,0,0), result+Vector3f(0.5f,0,0), Color(1,0,1,1) );
//#endif
//*/
// // Generate the target rotation
// hkQuaternion targetRotation = wristModelSource.getRotation();
// //lookatRot.setAxisAngle( hkVector4(1,0,0), -(hkReal)degtorad(std::min<Real>( (ikList[i].input.z*0.5f) - 25.0f, 5 )) );
// lookatRot.setAxisAngle( hkVector4(1,0,0), -(hkReal)degtorad(ikList[i].input.z * 0.7f) );
// //lookatRot.setAxisAngle( hkVector4(1,0,0), -(hkReal)degtorad(t_armOffset) );
// targetRotation.setMul( lookatRot, wristModelSource.getRotation() );
//
// // Setup an IK to run on the arm
// hkaTwoJointsIkSolver::Setup ik_info;
// ik_info.m_firstJointIdx = ikList[i].bone[bb];
// ik_info.m_secondJointIdx = ikList[i].bone[bb]+1;
// ik_info.m_endBoneIdx = ikList[i].bone[bb]+2;
//
// if ( bb == 4 ) { // Right arm
// ik_info.m_hingeAxisLS.set( 0,0,1 );
// ik_info.m_enforceEndRotation = true;
// ik_info.m_enforceEndPosition = true;
// }
// else if ( bb == 3 ) { // Left arm
// ik_info.m_hingeAxisLS.set( 0,0,1 );
// ik_info.m_enforceEndRotation = true;
// ik_info.m_enforceEndPosition = true;
// }
// ik_info.m_endTargetMS = targetPosition;
// ik_info.m_endTargetRotationMS = targetRotation;
//
// // Set IK Strength
// ik_info.m_firstJointIkGain = fAimrBlend * ikList[i].subinfo[3] * ikList[i].subinfo[bb-3];
// ik_info.m_secondJointIkGain = fAimrBlend * ikList[i].subinfo[3] * ikList[i].subinfo[bb-3];
// ik_info.m_endJointIkGain = fAimrBlend * ikList[i].subinfo[3] * ikList[i].subinfo[bb-3];
//
// // Now, run an IK on the final pose
// hkaTwoJointsIkSolver::solve( ik_info, skeletonPose );
// }
//
// // Get result
// //skeletonPose.syncAll();
// //skeletonPose.syncModelSpace();
// }
// }
// break;
// case kModelIkFootstep:
// if ( ikList[i].enabled )
// {
// // subinfo0 is the amount of offset ankles
// // subinfo3 is the calculted weight in
// // subinfo2 is the saved foot fraction
// // subinfo1 is the foot fader. If above 0.5, then it enables the foot IK. If it is below 0.5 it disables the foot IK similar to how when the target leaves the ground.
//
// // Perform ankle changes
// if ( ikList[i].subinfo[0] > FTYPE_PRECISION )
// {
// hkQsTransform ankleTransform = skeletonPose.accessBoneLocalSpace( ikList[i].bone[0] );
// hkQuaternion targetAngle ( hkVector4(0,0,1), -HK_REAL_PI/6 );
// ankleTransform.m_rotation.setSlerp( hkQuaternion(ankleTransform.m_rotation), targetAngle, ikList[i].subinfo[0] );
// //skeletonPose.setBoneLocalSpace( ikList[i].bone[0], ankleTransform );
// skeletonPose.accessBoneLocalSpace( ikList[i].bone[0] ).setRotation( ankleTransform.m_rotation );
// //skeletonPose.syncLocalSpace();
// //skeletonPose.syncModelSpace();
// //skeletonPose.syncAll();
// }
//
// // Setup the Joint IK
// hkaTwoJointsIkSolver::Setup ik_setup;
// ik_setup.m_firstJointIdx = ikList[i].bone[2];
// ik_setup.m_secondJointIdx = ikList[i].bone[1];
// ik_setup.m_endBoneIdx = ikList[i].bone[4];
//
// ik_setup.m_hingeAxisLS = hkVector4( 0,0,1 );
//
// ik_setup.m_firstJointIkGain = ikList[i].subinfo[3];
// ik_setup.m_secondJointIkGain = ikList[i].subinfo[3];
//
// ik_setup.m_enforceEndPosition = true;
// ik_setup.m_enforceEndRotation = false; // Do not change end rotation
//
// // Take the toe position, and raycast it.
// {
// hkVector4 toeModelSpace = skeletonPose.accessBoneModelSpace( ikList[i].bone[3] ).getTranslation();
// hkVector4 toeWorldSpace;
// toeWorldSpace.setTransformedPos( modelToWorld, toeModelSpace );
// hkVector4 fromPosition = toeWorldSpace;
// fromPosition.add( hkVector4( 0,0,2.0f ) );
// hkVector4 toPosition = toeWorldSpace;
// toPosition.add( hkVector4( 0,0,-2.0f ) );
//
// // Cast downwards
// hkReal resultFraction;
// hkVector4 resultNormal;
// hkWorldCaster lclCaster;
// hkBool hitGround = lclCaster.castRay( fromPosition, toPosition, Physics::GetCollisionFilter( Layers::PHYS_WORLD_TRACE ), resultFraction, resultNormal );
//
// if ( hitGround && ikList[i].subinfo[1] > 0.5f )
// {
// // Fade in IK
// ikList[i].subinfo[3] = std::min<Real>( 1, ikList[i].subinfo[3]+deltaTime*2.0f );
// // Save the result fraction
// ikList[i].subinfo[2] = resultFraction;
// }
// else
// {
// // Fade out IK
// ikList[i].subinfo[3] = std::max<Real>( 0, ikList[i].subinfo[3]-deltaTime*3.0f );
// // Set fraction to the saved value
// resultFraction = ikList[i].subinfo[2];//0.67f;
// }
// // Perform the IK regardless
// if ( ikList[i].subinfo[3] > FTYPE_PRECISION )
// {
// hkVector4 groundPosition;
// groundPosition.setInterpolate( fromPosition, toPosition, resultFraction );
///*
//#ifdef _ENGINE_DEBUG // Draw the toe positions
// Vector3f result ( toeWorldSpace.getComponent<0>(), toeWorldSpace.getComponent<1>(), toeWorldSpace.getComponent<2>() );
// debug::Drawer->DrawLine( result-Vector3f(0,0.5f,0), result+Vector3f(0,0.5f,0), Color(1,0,1,1) );
// debug::Drawer->DrawLine( result-Vector3f(0,0,0.5f), result+Vector3f(0,0,0.5f), Color(1,0,1,1) );
// debug::Drawer->DrawLine( result-Vector3f(0.5f,0,0), result+Vector3f(0.5f,0,0), Color(1,0,1,1) );
//#endif*/
// // Z is the ground. Compare with parent model Z=0
// hkVector4 targetPosition = toeWorldSpace;
// //hkReal zOffset = groundPosition.getComponent<2>().getReal() - pOwner->transform.position.z + ikList[i].subinfo[0]*(-t_verticalOffset+0.57f);
// hkReal zOffset = groundPosition.getComponent<2>().getReal() - mModelTransform.position.z + ikList[i].subinfo[0]*(-t_verticalOffset+0.57f);
// targetPosition.setComponent<2>( targetPosition.getComponent<2>().getReal() + zOffset );
// // Move the target position to model space
// ik_setup.m_endTargetMS.setTransformedPos( worldToModel, targetPosition );
// // Perform the IK
// hkaTwoJointsIkSolver::solve( ik_setup, skeletonPose );
// }
// }
// }
// t_footIK_count += 1;
// break;
// case kModelIkProps:
// //if ( ikList[i].enabled )
// {
// animLerper lerpHelp(deltaTime);
//
// fPropWeight[0] = std::max<Real>( 0, fPropWeight[0] );
// fPropWeight[1] = std::max<Real>( 0, fPropWeight[1] );
// fPropWeight[2] = std::max<Real>( 0, fPropWeight[2] );
// fPropWeight[3] = std::max<Real>( 0, fPropWeight[3] );
//
// lerpHelp( mPropBlends[0], fPropWeight[0] );
// lerpHelp( mPropBlends[1], fPropWeight[1] );
// lerpHelp( mPropBlends[2], fPropWeight[2] );
// lerpHelp( mPropBlends[3], fPropWeight[3] );
//
// // Loop through the prop bones. If the animations have nothing to say about it, give it a default prop value
// for ( uint bb = 0; bb < 4; ++bb )
// {
// int32_t propIndex = ikList[i].bone[bb];
//
// if ( propIndex && (mPropBlends[bb] > FTYPE_PRECISION) )
// {
// hkQuaternion targetRotation;
// targetRotation.setMul( hkQuaternion( hkVector4(0,1,0), HK_REAL_PI/2 ), hkQuaternion( hkVector4(1,0,0), HK_REAL_PI/2 ) );
// hkVector4 targetPosition;
// targetPosition = hkVector4( 1.4f,0.8f,-1.0f );
//
// hkQuaternion sourceRotation = skeletonPose.accessBoneLocalSpace(propIndex).m_rotation;
// hkVector4 sourcePosition = skeletonPose.accessBoneLocalSpace(propIndex).m_translation;
// skeletonPose.accessBoneLocalSpace(propIndex).m_rotation.setSlerp( sourceRotation, targetRotation, mPropBlends[bb] );
// skeletonPose.accessBoneLocalSpace(propIndex).m_translation.setInterpolate( sourcePosition, targetPosition, mPropBlends[bb] );
// }
// }
// }
// break;
// }
// }
//
// // Rotate all bones 180 degrees around X+
// /*for ( uint i = 0; i < nextTransforms.getSize(); ++i )
// {
// hkQsTransform t_transform = skeletonPose.getBoneModelSpace(i);
//
// //t_transform.m_rotation.mul( hkQuaternion(hkVector4(1,0,0),PI) );
// t_transform.m_rotation.setMul( t_transform.m_rotation, hkQuaternion(hkVector4(1,0,0),PI) );
//
// //hkVector4 t_axis;
// //t_axis.setRotatedDir( t_transform.m_rotation, hkVector4(1,0,0) );
// //t_transform.m_rotation.mul( hkQuaternion(t_axis, PI) );
//
// skeletonPose.setBoneModelSpace( i, t_transform, hkaPose::DONT_PROPAGATE );
// }*/
//
// /*
// // Animation flip
// for ( uint i = 0; i < nextTransforms.getSize(); ++i )
// {
// hkQsTransform t_transform = skeletonPose.getBoneModelSpace(i);
//
// //t_transform.m_rotation.mul( hkQuaternion(hkVector4(1,0,0),PI) );
// //t_transform.m_rotation.setMul( t_transform.m_rotation, hkQuaternion(hkVector4(1,0,0),PI) );
// t_transform.m_translation.set(
// -t_transform.m_translation.getComponent<0>(),
// t_transform.m_translation.getComponent<1>(),
// t_transform.m_translation.getComponent<2>(),
// t_transform.m_translation.getComponent<3>()
// );
// hkRotation t_rot;
// t_rot.set( t_transform.m_rotation );
// hkVector4 t_row;
//
// t_row = t_rot.getColumn<1>();
// t_row.setNeg<3>( t_row );
// t_rot.setColumn<1>( t_row );
//
// t_row = t_rot.getColumn<2>();
// t_row.setNeg<3>( t_row );
// t_rot.setColumn<2>( t_row );
//
// t_transform.m_rotation.set( t_rot );
//
//
// t_transform.m_scale.set(
// t_transform.m_scale.getComponent<0>(),
// t_transform.m_scale.getComponent<1>(),
// t_transform.m_scale.getComponent<2>(),
// t_transform.m_scale.getComponent<3>()
// );
//
// //hkVector4 t_axis;
// //t_axis.setRotatedDir( t_transform.m_rotation, hkVector4(1,0,0) );
// //t_transform.m_rotation.mul( hkQuaternion(t_axis, PI) );
//
// skeletonPose.setBoneModelSpace( i, t_transform, hkaPose::DONT_PROPAGATE );
// }*/
//
// nextTransforms = skeletonPose.getSyncedPoseLocalSpace();
// //tempTransforms = skeletonPose.getSyncedPoseLocalSpace();
// //nextTransforms = tempTransforms;
//
// bool tDontExport = false;
//#ifdef _ENGINE_DEBUG
// bool bad;
// // CHECK FUCKING EVERYTHING AGAIN
// bad = false;
// for ( int i = 0; i < tempTransforms.getSize(); ++i ) {
// if ( !tempTransforms[i].isOk() ) {
// bad = true;
// tempTransforms[i] = hkQsTransform();
// }
// }
//#ifdef _ENGINE_SAFE_CHECK_
// if ( bad ) cout << "BAD SHIT ON TT 2 " << endl;// << i << endl;
//#endif
// bad = false;
// for ( int i = 0; i < nextTransforms.getSize(); ++i ) {
// if ( !nextTransforms[i].isOk() ) {
// //cout << "BAD SHIT ON NT 2 " << i << endl;
// bad = true;
// tDontExport = true;
// nextTransforms[i] = hkQsTransform();
// }
// }
//#ifdef _ENGINE_SAFE_CHECK_
// if ( bad ) cout << "BAD SHIT ON NT 2 " << endl;// << i << endl;
//#endif
// bad = false;
// for ( int i = 0; i < aimrTransforms.getSize(); ++i ) {
// if ( !aimrTransforms[i].isOk() ) {
// //cout << "BAD SHIT ON AM 2 " << i << endl;
// bad = true;
// aimrTransforms[i] = hkQsTransform();
// }
// }
//#ifdef _ENGINE_SAFE_CHECK_
// if ( bad ) cout << "BAD SHIT ON AM 2 " << endl;// << i << endl;
//#endif
//#endif
//
// // Create the pose
// //hkaPose skeletonPose ( hkaPose::LOCAL_SPACE, mSkelly, nextTransforms );
// // We convert it into model space
// /*hkArray<hkQsTransform> poseModelSpace(mSkelly->m_referenceCount);
// poseModelSpace.setSize(mSkelly->m_referenceCount);
// for ( int i = 0; i < poseModelSpace.getSize(); ++i ) {
// hkaSkeletonUtils::getModelSpaceScale( *mSkelly, nextTransforms.begin(), i, poseModelSpace[i].m_scale );
// }
// hkaSkeletonUtils::transformLocalPoseToModelPose(mSkelly->m_referenceCount, mSkelly->m_parentIndices.begin(), nextTransforms.begin(), poseModelSpace.begin());
//
// // Do IK
// for ( uint i = 0; i < ikList.size(); ++i )
// {
// if ( bHasAimr && (ikList[i].type == kModelIkAiming) )
// {
// // Do AIMING IK
// //hkaPose aimrPose ( hkaPose::LOCAL_SPACE, mSkelly, aimrTransforms );
// hkArray<hkQsTransform> poseAimrModelSpace(mSkelly->m_referenceCount);
// poseAimrModelSpace.setSize(mSkelly->m_referenceCount);
// hkaSkeletonUtils::transformLocalPoseToModelPose(mSkelly->m_referenceCount, mSkelly->m_parentIndices.begin(), aimrTransforms.begin(), poseAimrModelSpace.begin());
//
// tempTransforms = nextTransforms;
//
// for ( uint bb = 0; bb < 5; ++bb )
// {
// cout << "BB: " << bb << " : " << ikList[i].bone[bb] << endl;
// //hkQsTransform tempModelAimrTrans = aimrPose.getSyncedPoseModelSpace()[ikList[i].bone[bb]];
// hkQsTransform tempModelAimrTrans = poseAimrModelSpace[ikList[i].bone[bb]];
//
// //hkQsTransform tempModelNextTrans = skeletonPose.getSyncedPoseModelSpace()[ikList[i].bone[bb]];
// hkQsTransform tempModelNextTrans = poseModelSpace[ikList[i].bone[bb]];
// tempModelNextTrans.setInverse( poseModelSpace[ikList[i].bone[bb]] );
// //tempModelNextTrans.fastRenormalize();
//
// hkQsTransform tempNextMul;
// //tempNextMul.setMulInverseMul( tempModelNextTrans, tempModelAimrTrans );
// tempNextMul.setMul( tempModelAimrTrans,tempModelNextTrans );
// //skeletonPose.setBoneModelSpace( ikList[i].bone[bb], tempModelTrans, hkaPose::DONT_PROPAGATE );
//
// hkQsTransform result;
// result.setMul( nextTransforms[ikList[i].bone[bb]], tempNextMul );
// tempTransforms[ikList[i].bone[bb]] = result;
// //nextTransforms[ikList[i].bone[bb]].setMul( nextTransforms[ikList[i].bone[bb]], tempNextMul );
// }
//
// nextTransforms = tempTransforms;
// }
// }*/
//
//
// // Now export all the animations
// //pAnimationSet->Export( animRefs );
// if ( !tDontExport )
// {
// for ( int i = 0; i < nextTransforms.getSize(); ++i )
// {
// //mhkAnim->
// /*int t = mAnimBinding->m_transformTrackToBoneIndices[i];
// ((XTransform*)animRefs[t])->position = Vector3f(
// nextTransforms[i].m_translation.getComponent<0>(),
// nextTransforms[i].m_translation.getComponent<1>(),
// nextTransforms[i].m_translation.getComponent<2>() );
// ((XTransform*)animRefs[t])->rotation = Quaternion(
// nextTransforms[i].m_rotation.m_vec.getComponent<0>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<1>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<2>(),
// nextTransforms[i].m_rotation.m_vec.getComponent<3>() );
// ((XTransform*)animRefs[t])->scale = Vector3f(
// nextTransforms[i].m_scale.getComponent<0>(),
// nextTransforms[i].m_scale.getComponent<1>(),
// nextTransforms[i].m_scale.getComponent<2>() );*/
// int16_t t_indexer = mAnimBinding->findTrackIndexFromBoneIndex(i);
// ((XTransform*)animRefs[i])->position = Vector3f(
// nextTransforms[t_indexer].m_translation.getComponent<0>(),
// nextTransforms[t_indexer].m_translation.getComponent<1>(),
// nextTransforms[t_indexer].m_translation.getComponent<2>() );
// ((XTransform*)animRefs[i])->rotation = Quaternion(
// nextTransforms[t_indexer].m_rotation.m_vec.getComponent<0>(),
// nextTransforms[t_indexer].m_rotation.m_vec.getComponent<1>(),
// nextTransforms[t_indexer].m_rotation.m_vec.getComponent<2>(),
// nextTransforms[t_indexer].m_rotation.m_vec.getComponent<3>() );
// ((XTransform*)animRefs[i])->scale = Vector3f(
// nextTransforms[t_indexer].m_scale.getComponent<0>(),
// nextTransforms[t_indexer].m_scale.getComponent<1>(),
// nextTransforms[t_indexer].m_scale.getComponent<2>() );
// }
// }
}
| 42.193919 | 233 | 0.665102 | [
"object",
"vector",
"model",
"transform"
] |
82c3277dc524ffb353c64c29dba22e04cad5a50e | 9,403 | cpp | C++ | emitter/data_printer.cpp | copy/llir-opt | 2fde7ebdf746d658ebfe60130cb18a9c3a4e091a | [
"MIT"
] | null | null | null | emitter/data_printer.cpp | copy/llir-opt | 2fde7ebdf746d658ebfe60130cb18a9c3a4e091a | [
"MIT"
] | null | null | null | emitter/data_printer.cpp | copy/llir-opt | 2fde7ebdf746d658ebfe60130cb18a9c3a4e091a | [
"MIT"
] | null | null | null | // This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#include <llvm/BinaryFormat/ELF.h>
#include <llvm/CodeGen/MachineModuleInfo.h>
#include <llvm/IR/Mangler.h>
#include <llvm/MC/MCSectionELF.h>
#include "core/cast.h"
#include "core/data.h"
#include "core/prog.h"
#include "core/block.h"
#include "emitter/isel_mapping.h"
#include "emitter/data_printer.h"
using MCSymbol = llvm::MCSymbol;
// -----------------------------------------------------------------------------
char DataPrinter::ID;
// -----------------------------------------------------------------------------
DataPrinter::DataPrinter(
const Prog &prog,
ISelMapping *isel,
llvm::MCContext *ctx,
llvm::MCStreamer *os,
const llvm::MCObjectFileInfo *objInfo,
const llvm::DataLayout &layout,
bool shared)
: llvm::ModulePass(ID)
, prog_(prog)
, isel_(isel)
, ctx_(ctx)
, os_(os)
, objInfo_(objInfo)
, layout_(layout)
, shared_(shared)
{
}
// -----------------------------------------------------------------------------
bool DataPrinter::runOnModule(llvm::Module &)
{
for (const Extern &ext : prog_.externs()) {
LowerExtern(ext);
}
for (const auto &data : prog_.data()) {
if (data.IsEmpty()) {
continue;
}
auto name = std::string(data.GetName());
os_->SwitchSection(GetSection(data));
if (name == ".data.caml") {
// OCaml data section, simply the data section with end markers.
auto emitMarker = [&] (const std::string_view name) {
auto *prefix = shared_ ? "caml_shared_startup__data" : "caml__data";
llvm::SmallString<128> mangledName;
llvm::Mangler::getNameWithPrefix(
mangledName,
std::string(prefix) + std::string(name),
layout_
);
auto *sym = ctx_->getOrCreateSymbol(mangledName);
if (shared_) {
os_->emitSymbolAttribute(sym, llvm::MCSA_Global);
}
os_->emitLabel(sym);
};
emitMarker("_begin");
LowerSection(data);
emitMarker("_end");
os_->emitIntValue(0, 8);
} else {
LowerSection(data);
}
}
return false;
}
// -----------------------------------------------------------------------------
llvm::StringRef DataPrinter::getPassName() const
{
return "LLIR Data Section Printer";
}
// -----------------------------------------------------------------------------
void DataPrinter::getAnalysisUsage(llvm::AnalysisUsage &AU) const
{
AU.setPreservesAll();
AU.addRequired<llvm::MachineModuleInfoWrapperPass>();
}
// -----------------------------------------------------------------------------
void DataPrinter::LowerExtern(const Extern &ext)
{
auto *sym = LowerSymbol(ext.getName());
EmitVisibility(sym, ext.GetVisibility());
if (auto value = ext.GetValue()) {
switch (value->GetKind()) {
case Value::Kind::GLOBAL: {
auto g = ::cast<Global>(value);
os_->emitAssignment(
sym,
llvm::MCSymbolRefExpr::create(LowerSymbol(g->getName()), *ctx_)
);
return;
}
case Value::Kind::CONST: {
switch (::cast<Constant>(value)->GetKind()) {
case Constant::Kind::INT: {
auto g = ::cast<ConstantInt>(value);
os_->emitAssignment(
sym,
llvm::MCConstantExpr::create(g->GetInt(), *ctx_, false, 8)
);
return;
}
case Constant::Kind::FLOAT: {
llvm_unreachable("not implemented");
}
llvm_unreachable("invalid constant kind");
}
return;
}
case Value::Kind::INST:
case Value::Kind::EXPR: {
llvm_unreachable("invalid alias");
}
}
llvm_unreachable("invalid value kind");
}
}
// -----------------------------------------------------------------------------
void DataPrinter::LowerSection(const Data &data)
{
for (const Object &object : data) {
LowerObject(object);
}
}
// -----------------------------------------------------------------------------
void DataPrinter::LowerObject(const Object &object)
{
for (const Atom &atom : object) {
LowerAtom(atom);
}
}
// -----------------------------------------------------------------------------
void DataPrinter::LowerAtom(const Atom &atom)
{
auto &moduleInfo = getAnalysis<llvm::MachineModuleInfoWrapperPass>().getMMI();
if (auto align = atom.GetAlignment()) {
os_->emitValueToAlignment(align->value());
}
auto *sym = LowerSymbol(atom.GetName());
EmitVisibility(sym, atom.GetVisibility());
os_->emitSymbolAttribute(sym, llvm::MCSA_ELF_TypeObject);
os_->emitLabel(sym);
for (const Item &item : atom) {
switch (item.GetKind()) {
case Item::Kind::INT8: os_->emitIntValue(item.GetInt8(), 1); continue;
case Item::Kind::INT16: os_->emitIntValue(item.GetInt16(), 2); continue;
case Item::Kind::INT32: os_->emitIntValue(item.GetInt32(), 4); continue;
case Item::Kind::INT64: os_->emitIntValue(item.GetInt64(), 8); continue;
case Item::Kind::FLOAT64: {
union U { double f; uint64_t i; } u = { .f = item.GetFloat64() };
os_->emitIntValue(u.i, 8);
continue;
}
case Item::Kind::EXPR32:
case Item::Kind::EXPR64: {
auto *expr = item.GetExpr();
switch (expr->GetKind()) {
case Expr::Kind::SYMBOL_OFFSET: {
auto *offsetExpr = static_cast<const SymbolOffsetExpr *>(expr);
if (auto *symbol = offsetExpr->GetSymbol()) {
MCSymbol *sym;
switch (symbol->GetKind()) {
case Global::Kind::BLOCK: {
auto *block = static_cast<const Block *>(symbol);
auto *bb = (*isel_)[block]->getBasicBlock();
sym = moduleInfo.getAddrLabelSymbol(bb);
break;
}
case Global::Kind::EXTERN:
case Global::Kind::FUNC:
case Global::Kind::ATOM: {
sym = LowerSymbol(symbol->GetName());
break;
}
}
if (auto offset = offsetExpr->GetOffset()) {
os_->emitValue(
llvm::MCBinaryExpr::createAdd(
llvm::MCSymbolRefExpr::create(sym, *ctx_),
llvm::MCConstantExpr::create(offset, *ctx_),
*ctx_
),
item.GetSize()
);
} else {
os_->emitSymbolValue(sym, item.GetSize());
}
} else {
os_->emitIntValue(0ull, item.GetSize());
}
continue;
}
}
llvm_unreachable("invalid expression kind");
}
case Item::Kind::SPACE: {
os_->emitZeros(item.GetSpace());
continue;
}
case Item::Kind::STRING: {
os_->emitBytes(item.getString());
continue;
}
}
llvm_unreachable("invalid item kind");
}
}
// -----------------------------------------------------------------------------
llvm::MCSymbol *DataPrinter::LowerSymbol(const std::string_view name)
{
llvm::SmallString<128> sym;
llvm::Mangler::getNameWithPrefix(sym, name.data(), layout_);
return ctx_->getOrCreateSymbol(sym);
}
// -----------------------------------------------------------------------------
void DataPrinter::EmitVisibility(llvm::MCSymbol *sym, Visibility visibility)
{
switch (visibility) {
case Visibility::LOCAL: {
return;
}
case Visibility::GLOBAL_DEFAULT: {
os_->emitSymbolAttribute(sym, llvm::MCSA_Global);
return;
}
case Visibility::GLOBAL_HIDDEN: {
os_->emitSymbolAttribute(sym, llvm::MCSA_Global);
os_->emitSymbolAttribute(sym, llvm::MCSA_Hidden);
return;
}
case Visibility::WEAK_DEFAULT: {
os_->emitSymbolAttribute(sym, llvm::MCSA_Weak);
return;
}
case Visibility::WEAK_HIDDEN: {
os_->emitSymbolAttribute(sym, llvm::MCSA_Weak);
os_->emitSymbolAttribute(sym, llvm::MCSA_Hidden);
return;
}
}
llvm_unreachable("invalid visibility attribute");
}
// -----------------------------------------------------------------------------
llvm::MCSection *DataPrinter::GetSection(const Data &data)
{
switch (objInfo_->getObjectFileType()) {
case llvm::MCObjectFileInfo::IsELF: {
unsigned type;
if (data.IsZeroed()) {
type = llvm::ELF::SHT_NOBITS;
} else {
type = llvm::ELF::SHT_PROGBITS;
}
unsigned flags = llvm::ELF::SHF_ALLOC;
if (data.IsWritable()) {
flags |= llvm::ELF::SHF_WRITE;
}
return ctx_->getELFSection(data.getName(), type, flags);
}
case llvm::MCObjectFileInfo::IsMachO: {
llvm_unreachable("Unsupported output: MachO");
}
case llvm::MCObjectFileInfo::IsCOFF: {
llvm_unreachable("Unsupported output: COFF");
}
case llvm::MCObjectFileInfo::IsWasm: {
llvm_unreachable("Unsupported output: Wasm");
}
case llvm::MCObjectFileInfo::IsLLIR: {
llvm_unreachable("Unsupported output: LLIR");
}
case llvm::MCObjectFileInfo::IsXCOFF: {
llvm_unreachable("Unsupported output: XCOFF");
}
}
llvm_unreachable("invalid section kind");
}
| 30.529221 | 80 | 0.527279 | [
"object"
] |
82c49c2c8ee17b289ca408c150ac2456f5eba28f | 5,908 | cpp | C++ | Engine/Source/Sapphire/Rendering/Vulkan/Buffers/VkFrameBuffer.cpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | 2 | 2020-03-18T09:06:21.000Z | 2020-04-09T00:07:56.000Z | Engine/Source/Sapphire/Rendering/Vulkan/Buffers/VkFrameBuffer.cpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | Engine/Source/Sapphire/Rendering/Vulkan/Buffers/VkFrameBuffer.cpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | // Copyright 2020 Sapphire development team. All Rights Reserved.
#include <Rendering/Vulkan/Buffers/VkFrameBuffer.hpp>
#include <Core/Algorithms/SizeOf.hpp>
#include <Rendering/Vulkan/System/VkMacro.hpp>
#include <Rendering/Vulkan/System/VkRenderPass.hpp>
#include <Rendering/Vulkan/System/Device/VkDevice.hpp>
#if SA_RENDERING_API == SA_VULKAN
namespace Sa::Vk
{
const IImageBuffer& FrameBuffer::GetInputAttachment(uint32 _index) const
{
SA_ASSERT(_index < SizeOf(mInputAttachments), OutOfRange, Rendering, _index, 0u, SizeOf(mInputAttachments));
return mInputAttachments[_index];
}
void FrameBuffer::Create(const Device& _device, const RenderPass& _renderPass,
const RenderPassDescriptor& _rpDescriptor,
const Vec2ui& _extent, uint32 _poolIndex, VkImage presentImage)
{
std::vector<VkImageView> attachementCreateInfos;
ImageBufferCreateInfos imageInfos;
imageInfos.extent = _extent;
for (auto subIt = _rpDescriptor.subPassDescs.begin(); subIt != _rpDescriptor.subPassDescs.end(); ++subIt)
{
for (auto attIt = subIt->attachmentDescs.begin(); attIt != subIt->attachmentDescs.end(); ++attIt)
{
imageInfos.format = attIt->format;
imageInfos.usage = 0u; // Reset usage.
imageInfos.sampling = subIt->sampling; // Reset sampling value.
if (subIt->sampling != SampleBits::Sample1Bit && !IsDepthFormat(attIt->format))
{
// Add multisampled buffer.
ImageBuffer& multSamplBuffer = mAttachments.emplace_back(ImageBuffer{});
multSamplBuffer.Create(_device, imageInfos);
attachementCreateInfos.push_back(multSamplBuffer);
if(attIt->loadMode == AttachmentLoadMode::Clear)
AddClearColor(attIt->format, attIt->clearColor);
imageInfos.sampling = SampleBits::Sample1Bit;
}
if (IsPresentFormat(attIt->format))
{
SA_ASSERT(presentImage != VK_NULL_HANDLE, InvalidParam, Rendering, L"Framebuffer with present format requiere a valid swapchain image!");
ImageBuffer& presentBuffer = mAttachments.emplace_back(ImageBuffer{});
presentBuffer.CreateFromImage(_device, imageInfos, presentImage);
attachementCreateInfos.push_back(presentBuffer);
}
else if (attIt->bInputNext)
{
imageInfos.usage = VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
ImageBuffer& inputBuffer = mInputAttachments.emplace_back(ImageBuffer{});
inputBuffer.Create(_device, imageInfos);
attachementCreateInfos.push_back(inputBuffer);
}
else
{
ImageBuffer& buffer = mAttachments.emplace_back(ImageBuffer{});
buffer.Create(_device, imageInfos);
attachementCreateInfos.push_back(buffer);
}
if (attIt->loadMode == AttachmentLoadMode::Clear)
AddClearColor(attIt->format, attIt->clearColor);
}
}
// === Create FrameBuffer ===
VkFramebufferCreateInfo framebufferCreateInfo{};
framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferCreateInfo.pNext = nullptr;
framebufferCreateInfo.flags = 0;
framebufferCreateInfo.renderPass = _renderPass;
framebufferCreateInfo.attachmentCount = SizeOf(attachementCreateInfos);
framebufferCreateInfo.pAttachments = attachementCreateInfos.data();
framebufferCreateInfo.width = _extent.x;
framebufferCreateInfo.height = _extent.y;
framebufferCreateInfo.layers = 1;
SA_VK_ASSERT(vkCreateFramebuffer(_device, &framebufferCreateInfo, nullptr, &mHandle),
CreationFailed, Rendering, L"Failed to create framebuffer!");
mExtent = _extent;
mRenderPass = _renderPass;
// === Create command buffer ===
commandBuffer = CommandBuffer::Allocate(_device, QueueType::Graphics, _poolIndex);
}
void FrameBuffer::Destroy(const Device& _device)
{
CommandBuffer::Free(_device, commandBuffer);
vkDestroyFramebuffer(_device, mHandle, nullptr);
// Destroy attachments.
for (auto it = mAttachments.begin(); it != mAttachments.end(); ++it)
it->Destroy(_device);
mAttachments.clear();
// Destroy input attachments.
for (auto it = mInputAttachments.begin(); it != mInputAttachments.end(); ++it)
it->Destroy(_device);
mInputAttachments.clear();
}
void FrameBuffer::Begin()
{
vkResetCommandBuffer(commandBuffer, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
// === Start Command buffer record ===
VkCommandBufferBeginInfo commandBufferBeginInfo{};
commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
commandBufferBeginInfo.pNext = nullptr;
commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
commandBufferBeginInfo.pInheritanceInfo = nullptr;
SA_VK_ASSERT(vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo),
LibCommandFailed, Rendering, L"Failed to begin command buffer!");
// === Start RenderPass record ===
VkRenderPassBeginInfo renderPassBeginInfo{};
renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassBeginInfo.pNext = nullptr;
renderPassBeginInfo.renderPass = mRenderPass;
renderPassBeginInfo.framebuffer = mHandle;
renderPassBeginInfo.renderArea = VkRect2D{ VkOffset2D{}, VkExtent2D{ mExtent.x, mExtent.y } };
renderPassBeginInfo.clearValueCount = SizeOf(mClearValues);
renderPassBeginInfo.pClearValues = mClearValues.data();
vkCmdBeginRenderPass(commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void FrameBuffer::NextSubpass()
{
vkCmdNextSubpass(commandBuffer, VK_SUBPASS_CONTENTS_INLINE);
}
void FrameBuffer::End()
{
// === End RenderPass record ===
vkCmdEndRenderPass(commandBuffer);
// === End Command buffer record ===
SA_VK_ASSERT(vkEndCommandBuffer(commandBuffer),
LibCommandFailed, Rendering, L"Failed to end command buffer!");
}
void FrameBuffer::AddClearColor(Format _format, const Color& _clearColor)
{
if (IsDepthFormat(_format))
mClearValues.emplace_back(VkClearValue{ { { 1.f, 0u } } });
else
mClearValues.emplace_back(_clearColor);
}
}
#endif | 33.005587 | 142 | 0.757448 | [
"vector"
] |
82cc4fb6b851c2f6375a78c1a4d6c545c7259ef0 | 4,957 | hpp | C++ | Game/ScriptSystem.hpp | Epitech-Tek2/superBonobros2 | 525ab414215f5b67829bf200797c2055141cb7b9 | [
"MIT"
] | null | null | null | Game/ScriptSystem.hpp | Epitech-Tek2/superBonobros2 | 525ab414215f5b67829bf200797c2055141cb7b9 | [
"MIT"
] | null | null | null | Game/ScriptSystem.hpp | Epitech-Tek2/superBonobros2 | 525ab414215f5b67829bf200797c2055141cb7b9 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** G-JAM-001-STG-0-1-jam-louis.kleiver
** File description:
** ScriptSystem
*/
#ifndef SCRIPTSYSTEM_HPP_
#define SCRIPTSYSTEM_HPP_
#include "ASystem.hpp"
#include "ECS.hpp"
#include "ScriptComponent.hpp"
#include "Transform2DComponent.hpp"
#include "MainForceComponent.hpp"
#include "SkeletonSonsComponent.hpp"
#include "SkeletonFatherComponent.hpp"
class ScriptSystem : virtual public gameEngine::ASystem {
public:
ScriptSystem(gameEngine::ECS *ecs) : ASystem(ecs) {}
~ScriptSystem() = default;
void init(gameEngine::ECS *ecs)
{
ecs->systemAddDependances<ScriptComponent>(this);
ecs->systemAddDependances<gameEngine::Transform2DComponent>(this);
ecs->systemAddDependances<gameEngine::MainForceComponent>(this);
}
protected:
private:
void readNext(std::shared_ptr<gameEngine::AEntity> entity, ScriptComponent &script, gameEngine::Transform2D &transform) {
if (!script._script.size())
return;
if (script._scriptPos < 0 || script._scriptPos >= (int) script._script.size() - 1)
script._scriptPos = 0;
else
++script._scriptPos;
auto it = script._script[script._scriptPos];
if (it.first == "x")
script.save = transform.getPosition().x;
else if (it.first == "y")
script.save = transform.getPosition().y;
else if (it.first == "wait")
script.save = it.second;
else if (it.first == "rot")
script.save = (int) (it.second) % 360;
else
std::cout << "Script Error" << std::endl;
}
void action(std::shared_ptr<gameEngine::AEntity> entity, float time)
{
static float speed = 100;
auto &script = _ecs->getEntityComponent<ScriptComponent>(entity);
auto &transform = _ecs->getEntityComponent<gameEngine::Transform2DComponent>(entity)._transform;
auto &mainForce = _ecs->getEntityComponent<gameEngine::MainForceComponent>(entity);
auto pos = transform.getPosition();
mainForce._mainForce = {0, 0};
if (script._scriptPos < 0)
readNext(entity, script, transform);
if (script._scriptPos < 0 || script._scriptPos >= (int) script._script.size())
return;
auto it = script._script[script._scriptPos];
if (it.first == "x") {
if (it.second > 0) {
if (it.second >= pos.x - script.save) {
mainForce._mainForce = {speed, 0};
}
else {
readNext(entity, script, transform);
}
} else {
if (it.second <= pos.x - script.save) {
mainForce._mainForce = {-speed, 0};
}
else {
readNext(entity, script, transform);
}
}
} else if (it.first == "y") {
if (it.second > 0) {
if (it.second >= pos.y - script.save) {
mainForce._mainForce = {0, speed};
}
else {
readNext(entity, script, transform);
}
} else {
if (it.second <= pos.y - script.save) {
mainForce._mainForce = {0, -speed};
}
else {
readNext(entity, script, transform);
}
}
} else if (it.first == "wait") {
script.save -= time;
if (script.save <= 0)
readNext(entity, script, transform);
} else if (it.first == "rot") {
try {
auto &sons = _ecs->getEntityComponent<gameEngine::SkeletonSonsComponent>(entity);
auto son = sons.getSon("FieldOfView");
auto &father = _ecs->getEntityComponent<gameEngine::SkeletonFatherComponent>(son);
float angle = (int) (it.second) % 360;
if (father._rotation < angle - 1)
father._rotation += time * 40;
else if (father._rotation > angle + 1)
father._rotation -= time * 40;
else
readNext(entity, script, transform);
} catch (const char *str) {
readNext(entity, script, transform);
}
script.save -= time;
if (script.save <= 0)
readNext(entity, script, transform);
}
}
};
#endif /* !SCRIPTSYSTEM_HPP_ */
| 38.726563 | 129 | 0.488199 | [
"transform"
] |
82cd2637a883810cfb1e8feb263ad15784ed762f | 2,657 | cpp | C++ | tests/unit-tests/test-fill-triangle.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 10 | 2016-12-28T22:06:31.000Z | 2021-05-24T13:42:30.000Z | tests/unit-tests/test-fill-triangle.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 4 | 2015-10-09T23:55:10.000Z | 2020-04-04T08:09:22.000Z | tests/unit-tests/test-fill-triangle.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | null | null | null | // -*- coding: us-ascii-unix -*-
#include <algorithm>
#include <array>
#include "test-sys/test.hh"
#include "tests/test-util/text-bitmap.hh"
#include "bitmap/bitmap.hh"
#include "bitmap/color.hh"
#include "bitmap/draw.hh"
using faint::IntPoint;
using triangle_t = std::array<IntPoint, 3>;
using triangles_t = std::vector<triangle_t>;
static triangles_t permutations(const IntPoint& p0,
const IntPoint& p1,
const IntPoint& p2)
{
triangle_t a = {{p0, p1, p2}};
std::sort(begin(a), end(a));
triangles_t v;
do{
v.push_back(a);
} while (std::next_permutation(begin(a), end(a)));
EQUAL(v.size(), 3*2*1);
return v;
}
inline void fill_triangle_color(faint::Bitmap& bmp,
const triangle_t& pts,
const faint::Color& c)
{
// Forward to the real function-under-test, to avoid repeating
// point-retrieval in each test.
using std::get;
fill_triangle_color(bmp, get<0>(pts), get<1>(pts), get<2>(pts), c);
}
void test_fill_triangle(){
using namespace faint;
const bitmap_value_map colors = {
{'.', color_white},
{'X', color_black}};
for (auto& pts : permutations({0,3}, {3,0}, {6,3})){
Bitmap bmp({7, 4}, color_white);
fill_triangle_color(bmp, pts, color_black);
FWD(check(bmp,
"...X..."
"..XXX.."
".XXXXX."
"XXXXXXX",
colors));
}
for (auto& pts : permutations({0, 0}, {3, 3}, {0, 6})){
Bitmap bmp({4, 7}, color_white);
fill_triangle_color(bmp, pts, color_black);
FWD(check(bmp,
"X..."
"XX.."
"XXX."
"XXXX"
"XXX."
"XX.."
"X...",
colors));
}
for (auto& pts : permutations({3, 0}, {0, 3}, {3, 6})){
Bitmap bmp({4, 7}, color_white);
fill_triangle_color(bmp, pts, color_black);
FWD(check(bmp,
"...X"
"..XX"
".XXX"
"XXXX"
".XXX"
"..XX"
"...X",
colors));
}
for (auto& pts : permutations({0, 0}, {3, 0}, {0, 3})){
Bitmap bmp({4, 4}, color_white);
fill_triangle_color(bmp, pts, color_black);
FWD(check(bmp,
"XXXX"
"XXX."
"XX.."
"X...",
colors))
}
for (auto& pts : permutations({3,0}, {3, 3}, {0, 3})){
Bitmap bmp({4, 4}, color_white);
fill_triangle_color(bmp, pts , color_black);
FWD(check(bmp,
"...X"
"..XX"
".XXX"
"XXXX",
colors));
}
for (auto& pts : permutations({0,7}, {4, 0}, {6, 8})){
Bitmap bmp({7, 9}, color_white);
fill_triangle_color(bmp, pts, color_black);
FWD(check(bmp,
"....X.."
"...XX.."
"...XX.."
"..XXXX."
"..XXXX."
".XXXXX."
".XXXXX."
"XXXXXXX"
"....XXX",
colors));
}
}
| 21.087302 | 69 | 0.54347 | [
"vector"
] |
82cd2ae7337d9fea99f0c07c4dce042cd2787796 | 1,992 | hpp | C++ | src/core/compute/program.hpp | Rythe-Interactive/Rythe-Core | 74dea147308c781412c0c72e59f25cb6c219b2d7 | [
"MIT"
] | 2 | 2022-03-16T23:39:17.000Z | 2022-03-18T20:22:58.000Z | src/core/compute/program.hpp | Rythe-Interactive/Rythe-Core | 74dea147308c781412c0c72e59f25cb6c219b2d7 | [
"MIT"
] | 3 | 2022-03-02T13:49:10.000Z | 2022-03-22T11:54:06.000Z | legion/engine/core/compute/program.hpp | Rythe-Interactive/Rythe-Engine.rythe-legacy | c119c494524b069a73100b12dc3d8b898347830d | [
"MIT"
] | null | null | null | #pragma once
#include "detail/cl_include.hpp"
#include <core/filesystem/resource.hpp>
#include <core/compute/kernel.hpp>
#include <functional>
#include <string>
/**
* @file program.hpp
*/
namespace legion::core::compute {
/** @class Program
* @brief A Mid-Level Wrapper around a cl_program, creates command-queues
* and Kernels for you automatically
*/
class Program
{
public:
Program(cl_context, cl_device_id, filesystem::basic_resource /*, bool source_is_il = false*/);
Program(const Program& other) = default;
Program(Program&& other) noexcept = default;
Program& operator=(const Program& other) = default;
Program& operator=(Program&& other) noexcept = default;
/**
* @brief Creates a wrapped Kernel
* @param name The name of the kernel you want to load/get
* @return A Kernel Object
*/
Kernel kernelContext(const std::string& name);
/**
* @brief Makes sure that a kernel is loaded, otherwise the kernel
* will be lazy initialized on first request
*
* @param name The name of the Kernel you want to load (function-name)
* @return A raw cl_kernel object
*/
cl_kernel prewarm(const std::string& name);
/**
* @brief Creates a Command Queue
*/
cl_command_queue make_cq() const
{
return make_command_queue();
}
static void from_resource(Program* value, const filesystem::basic_resource& resource);
private:
friend class filesystem::basic_resource;
template <class T, class C1,class C2,class C3>
friend T filesystem::from_resource(const filesystem::basic_resource& resource);
Program() = default;
std::function<cl_command_queue()> make_command_queue;
cl_program m_program;
std::unordered_map<std::string, cl_kernel> m_kernelCache;
};
}
| 29.294118 | 102 | 0.623494 | [
"object"
] |
82ce15e77e3da54484417e9c167e931265fd49a7 | 7,820 | hpp | C++ | src/mlpack/methods/reinforcement_learning/q_networks/categorical_dqn.hpp | laszlzso/mlpack | 52e123e56792638c957d0229b001ae14a9e94a75 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2019-07-09T21:52:01.000Z | 2020-07-29T19:14:33.000Z | src/mlpack/methods/reinforcement_learning/q_networks/categorical_dqn.hpp | laszlzso/mlpack | 52e123e56792638c957d0229b001ae14a9e94a75 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2020-06-21T17:36:46.000Z | 2020-08-07T07:16:01.000Z | src/mlpack/methods/reinforcement_learning/q_networks/categorical_dqn.hpp | laszlzso/mlpack | 52e123e56792638c957d0229b001ae14a9e94a75 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file methods/reinforcement_learning/q_networks/categorical_dqn.hpp
* @author Nishant Kumar
*
* This file contains the implementation of the categorical deep q network.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_RL_CATEGORICAL_DQN_HPP
#define MLPACK_METHODS_RL_CATEGORICAL_DQN_HPP
#include <mlpack/prereqs.hpp>
#include <mlpack/methods/ann/ffn.hpp>
#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>
#include <mlpack/methods/ann/layer/layer.hpp>
#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>
#include <mlpack/methods/ann/loss_functions/empty_loss.hpp>
#include "../training_config.hpp"
namespace mlpack {
namespace rl {
using namespace mlpack::ann;
/**
* Implementation of the Categorical Deep Q-Learning network.
* For more information, see the following.
*
* @code
* @misc{bellemare2017distributional,
* author = {Marc G. Bellemare, Will Dabney, Rémi Munos},
* title = {A Distributional Perspective on Reinforcement Learning},
* year = {2017},
* url = {http://arxiv.org/abs/1707.06887}
* }
* @endcode
*
* @tparam OutputLayerType The output layer type of the network.
* @tparam InitType The initialization type used for the network.
* @tparam NetworkType The type of network used for simple dqn.
*/
template<
typename OutputLayerType = EmptyLoss<>,
typename InitType = GaussianInitialization,
typename NetworkType = FFN<OutputLayerType, InitType>
>
class CategoricalDQN
{
public:
/**
* Default constructor.
*/
CategoricalDQN() : network(), isNoisy(false), atomSize(0), vMin(0.0), vMax(0.0)
{ /* Nothing to do here. */ }
/**
* Construct an instance of CategoricalDQN class.
*
* @param inputDim Number of inputs.
* @param h1 Number of neurons in hiddenlayer-1.
* @param h2 Number of neurons in hiddenlayer-2.
* @param outputDim Number of neurons in output layer.
* @param config Hyper-parameters for categorical dqn.
* @param isNoisy Specifies whether the network needs to be of type noisy.
* @param init Specifies the initialization rule for the network.
* @param outputLayer Specifies the output layer type for network.
*/
CategoricalDQN(const int inputDim,
const int h1,
const int h2,
const int outputDim,
TrainingConfig config,
const bool isNoisy = false,
InitType init = InitType(),
OutputLayerType outputLayer = OutputLayerType()):
network(outputLayer, init),
atomSize(config.AtomSize()),
vMin(config.VMin()),
vMax(config.VMax()),
isNoisy(isNoisy)
{
network.Add(new Linear<>(inputDim, h1));
network.Add(new ReLULayer<>());
if (isNoisy)
{
noisyLayerIndex.push_back(network.Model().size());
network.Add(new NoisyLinear<>(h1, h2));
network.Add(new ReLULayer<>());
noisyLayerIndex.push_back(network.Model().size());
network.Add(new NoisyLinear<>(h2, outputDim * atomSize));
}
else
{
network.Add(new Linear<>(h1, h2));
network.Add(new ReLULayer<>());
network.Add(new Linear<>(h2, outputDim * atomSize));
}
}
/**
* Construct an instance of CategoricalDQN class from a pre-constructed network.
*
* @param network The network to be used by CategoricalDQN class.
* @param config Hyper-parameters for categorical dqn.
* @param isNoisy Specifies whether the network needs to be of type noisy.
*/
CategoricalDQN(NetworkType& network,
TrainingConfig config,
const bool isNoisy = false):
network(std::move(network)),
atomSize(config.AtomSize()),
vMin(config.VMin()),
vMax(config.VMax()),
isNoisy(isNoisy)
{ /* Nothing to do here. */ }
/**
* Predict the responses to a given set of predictors. The responses will
* reflect the output of the given output layer as returned by the
* output layer function.
*
* If you want to pass in a parameter and discard the original parameter
* object, be sure to use std::move to avoid unnecessary copy.
*
* @param state Input state.
* @param actionValue Matrix to put output action values of states input.
*/
void Predict(const arma::mat state, arma::mat& actionValue)
{
arma::mat q_atoms;
network.Predict(state, q_atoms);
activations.copy_size(q_atoms);
actionValue.set_size(q_atoms.n_rows / atomSize, q_atoms.n_cols);
arma::rowvec support = arma::linspace<arma::rowvec>(vMin, vMax, atomSize);
for (size_t i = 0; i < q_atoms.n_rows; i += atomSize)
{
arma::mat activation = activations.rows(i, i + atomSize - 1);
arma::mat input = q_atoms.rows(i, i + atomSize - 1);
softMax.Forward(input, activation);
activations.rows(i, i + atomSize - 1) = activation;
actionValue.row(i/atomSize) = support * activation;
}
}
/**
* Perform the forward pass of the states in real batch mode.
*
* @param state The input state.
* @param dist The predicted distributions.
*/
void Forward(const arma::mat state, arma::mat& dist)
{
arma::mat q_atoms;
network.Forward(state, q_atoms);
activations.copy_size(q_atoms);
for (size_t i = 0; i < q_atoms.n_rows; i += atomSize)
{
arma::mat activation = activations.rows(i, i + atomSize - 1);
arma::mat input = q_atoms.rows(i, i + atomSize - 1);
softMax.Forward(input, activation);
activations.rows(i, i + atomSize - 1) = activation;
}
dist = activations;
}
/**
* Resets the parameters of the network.
*/
void ResetParameters()
{
network.ResetParameters();
}
/**
* Resets noise of the network, if the network is of type noisy.
*/
void ResetNoise()
{
for (size_t i = 0; i < noisyLayerIndex.size(); i++)
{
boost::get<NoisyLinear<>*>
(network.Model()[noisyLayerIndex[i]])->ResetNoise();
}
}
//! Return the Parameters.
const arma::mat& Parameters() const { return network.Parameters(); }
//! Modify the Parameters.
arma::mat& Parameters() { return network.Parameters(); }
/**
* Perform the backward pass of the state in real batch mode.
*
* @param state The input state.
* @param lossGradients The loss gradients.
* @param gradient The gradient.
*/
void Backward(const arma::mat state,
arma::mat& lossGradients,
arma::mat& gradient)
{
arma::mat activationGradients(arma::size(activations));
for (size_t i = 0; i < activations.n_rows; i += atomSize)
{
arma::mat activationGrad;
arma::mat lossGrad = lossGradients.rows(i, i + atomSize - 1);
arma::mat activation = activations.rows(i, i + atomSize - 1);
softMax.Backward(activation, lossGrad, activationGrad);
activationGradients.rows(i, i + atomSize - 1) = activationGrad;
}
network.Backward(state, activationGradients, gradient);
}
private:
//! Locally-stored network.
NetworkType network;
//! Locally-stored number of atoms.
size_t atomSize;
//! Locally-stored minimum value of support.
double vMin;
//! Locally-stored maximum value of support.
double vMax;
//! Locally-stored check for noisy network.
bool isNoisy;
//! Locally-stored indexes of noisy layers in the network.
std::vector<size_t> noisyLayerIndex;
//! Locally-stored softmax activation function.
Softmax<> softMax;
//! Locally-stored activations from softMax.
arma::mat activations;
};
} // namespace rl
} // namespace mlpack
#endif
| 31.659919 | 82 | 0.665473 | [
"object",
"vector",
"model"
] |
82d33e5330a82ae06db69dc1b3d367f41cf405da | 40,668 | cpp | C++ | modules/address-book/engine/src/AddressBookCloudUploader.cpp | heavencross/alexa-auto-sdk | 13baa3d1416c0d1582d0c78e6223212a745ed022 | [
"Apache-2.0"
] | null | null | null | modules/address-book/engine/src/AddressBookCloudUploader.cpp | heavencross/alexa-auto-sdk | 13baa3d1416c0d1582d0c78e6223212a745ed022 | [
"Apache-2.0"
] | null | null | null | modules/address-book/engine/src/AddressBookCloudUploader.cpp | heavencross/alexa-auto-sdk | 13baa3d1416c0d1582d0c78e6223212a745ed022 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 <typeinfo>
#include <rapidjson/error/en.h>
#include <rapidjson/pointer.h>
#include <rapidjson/writer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include <AACE/Engine/Core/EngineMacros.h>
#include <AACE/Engine/Network/NetworkEngineService.h>
#include <AACE/Engine/AddressBook/AddressBookCloudUploader.h>
namespace aace {
namespace engine {
namespace addressBook {
// String to identify log entries originating from this file.
static const std::string TAG("aace.addressBook.addressBookCloudUploader");
/// Upload entreis batch size
static const int UPLOAD_BATCH_SIZE = 100;
/// Max allowed phonenumbers per entry
static const int MAX_ALLOWED_ADDRESSES_PER_ENTRY = 30;
/// Max allowed characters
static const int MAX_ALLOWED_CHARACTERS = 1000;
/// Max allowed EntryId size
static const int MAX_ALLOWED_ENTRY_ID_SIZE = 200;
/// Max event retry
static const int MAX_EVENT_RETRY = 3;
/// Invalid Address Id
static const std::string INVALID_ADDRESS_BOOK_SOURCE_ID = "INVALID";
/// Program Name prefix for metrics
static const std::string METRIC_PROGRAM_NAME_PREFIX = "AlexaAuto";
/// Program Name for Metrics
static const std::string METRIC_PROGRAM_NAME_SUFFIX = "AddressBookCloudUploader";
/// Delimiter
static const std::string DELIMITER = "_";
/// Program Name for metrics
static const std::string METRIC_PROGRAM_NAME = METRIC_PROGRAM_NAME_PREFIX + DELIMITER + METRIC_PROGRAM_NAME_SUFFIX;
/// Metric for adding contact
static const std::string METRIC_ADD_ADDRESS_BOOK_CONTACT = "Add.Contact";
/// Count metric for adding navigation
static const std::string METRIC_ADD_ADDRESS_BOOK_NAVIGATION = "Add.Navigation";
/// Count metric for removing contact
static const std::string METRIC_REMOVE_ADDRESS_BOOK_CONTACT = "Remove.Contact";
/// Count metric for removing navigation address
static const std::string METRIC_REMOVE_ADDRESS_BOOK_NAVIGATION = "Remove.Navigation";
/// Latency metrics to track actual upload to cloud since add event
static const std::string METRIC_TIME_TO_UPLOAD_SINCE_ADD = "Latency.Add";
/// Latency metrics to track actual remove from cloud since remove event
static const std::string METRIC_TIME_TO_UPLOAD_SINCE_REMOVE = "Latency.Remove";
/// Latency metric uploading a one batch of entries to cloud (average time)
static const std::string METRIC_TIME_TO_UPLOAD_ONE_BATCH = "Network.BatchUploadLatency";
/// Metric for Bad User Input network response
static const std::string METRIC_NETWORK_BAD_USER_INPUT = "Network.BadUserInput";
/// Metric for any Network Error
static const std::string METRIC_NETWORK_ERROR = "Network.Error";
AddressBookCloudUploader::AddressBookCloudUploader() :
alexaClientSDK::avsCommon::utils::RequiresShutdown(TAG),
m_isShuttingDown(false),
m_isAuthRefreshed(false) {
}
std::shared_ptr<AddressBookCloudUploader> AddressBookCloudUploader::create(
std::shared_ptr<aace::engine::addressBook::AddressBookServiceInterface> addressBookService,
std::shared_ptr<alexaClientSDK::avsCommon::sdkInterfaces::AuthDelegateInterface> authDelegate,
std::shared_ptr<alexaClientSDK::avsCommon::utils::DeviceInfo> deviceInfo,
NetworkInfoObserver::NetworkStatus networkStatus,
std::shared_ptr<aace::engine::network::NetworkObservableInterface> networkObserver ) {
try {
auto addressBookCloudUploader = std::shared_ptr<AddressBookCloudUploader>( new AddressBookCloudUploader() );
ThrowIfNot( addressBookCloudUploader->initialize( addressBookService, authDelegate, deviceInfo, networkStatus, networkObserver ), "initializeAddressBookCloudUploaderFailed" );
return addressBookCloudUploader;
} catch( std::exception &ex ) {
AACE_ERROR(LX(TAG, "create").d("reason", ex.what()));
return nullptr;
}
}
bool AddressBookCloudUploader::initialize(
std::shared_ptr<aace::engine::addressBook::AddressBookServiceInterface> addressBookService,
std::shared_ptr<alexaClientSDK::avsCommon::sdkInterfaces::AuthDelegateInterface> authDelegate,
std::shared_ptr<alexaClientSDK::avsCommon::utils::DeviceInfo> deviceInfo,
NetworkInfoObserver::NetworkStatus networkStatus,
std::shared_ptr<aace::engine::network::NetworkObservableInterface> networkObserver ) {
try {
m_addressBookService = addressBookService;
m_authDelegate = authDelegate;
m_deviceInfo = deviceInfo;
m_networkStatus = networkStatus;
m_networkObserver = networkObserver;
m_addressBookCloudUploaderRESTAgent = aace::engine::addressBook::AddressBookCloudUploaderRESTAgent::create( authDelegate, m_deviceInfo );
ThrowIfNull( m_addressBookCloudUploaderRESTAgent, "createAddressBookCloudRESTAgentFailed" );
m_authDelegate->addAuthObserver( shared_from_this() );
if( m_networkObserver != nullptr ) { // This could be null when NetworkInfoProvider interface is not registered.
m_networkObserver->addObserver( shared_from_this() );
} else {
AACE_DEBUG(LX(TAG).m("networkObserverNotAvailable"));
}
m_addressBookService->addObserver( shared_from_this() );
// Infinite event loop
m_eventThread = std::thread{ &AddressBookCloudUploader::eventLoop, this };
return true;
} catch( std::exception &ex ) {
AACE_ERROR(LX(TAG, "initialize").d("reason", ex.what()));
return false;
}
}
void AddressBookCloudUploader::doShutdown() {
m_isShuttingDown = true;
m_waitStatusChange.notify_all();
if( m_eventThread.joinable() ) {
m_eventThread.join();
}
m_authDelegate->removeAuthObserver( shared_from_this() );
if( m_networkObserver != nullptr ) {
m_networkObserver->removeObserver( shared_from_this() );
m_networkObserver.reset();
}
m_addressBookService->removeObserver( shared_from_this() );
m_authDelegate.reset();
m_addressBookService.reset();
m_addressBookCloudUploaderRESTAgent.reset();
}
void AddressBookCloudUploader::onAuthStateChange( AuthObserverInterface::State newState, AuthObserverInterface::Error error ) {
std::lock_guard<std::mutex> guard( m_mutex );
m_isAuthRefreshed = ( AuthObserverInterface::State::REFRESHED == newState );
AACE_DEBUG(LX(TAG,"onAuthStateChange").d( "m_isAuthRefreshed", m_isAuthRefreshed ) );
if( m_isAuthRefreshed ) {
m_waitStatusChange.notify_all();
}
}
void AddressBookCloudUploader::onNetworkInfoChanged( NetworkInfoObserver::NetworkStatus status, int wifiSignalStrength ) {
std::lock_guard<std::mutex> guard( m_mutex );
if( m_networkStatus != status ) {
m_networkStatus = status;
AACE_DEBUG(LX(TAG,"onNetworkInfoChanged").d( "m_networkStatus", m_networkStatus ) );
if( status == NetworkInfoObserver::NetworkStatus::CONNECTED ) {
m_waitStatusChange.notify_all();
}
}
}
void AddressBookCloudUploader::onNetworkInterfaceChangeStatusChanged( const std::string& networkInterface, NetworkInterfaceChangeStatus status ) {
// No action required as we don't create and persist network connection using AVS LibCurlUtils.
}
bool AddressBookCloudUploader::addressBookAdded( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
std::string addressBookSourceId = INVALID_ADDRESS_BOOK_SOURCE_ID;
try {
ThrowIfNull( addressBookEntity, "invalidAddressBookEntity" );
addressBookSourceId = addressBookEntity->getSourceId();
// For Metrics
if( addressBookEntity->getType() == AddressBookType::CONTACT ) {
emitCounterMetrics( "addressBookAdded", METRIC_ADD_ADDRESS_BOOK_CONTACT, 1 );
} else if( addressBookEntity->getType() == AddressBookType::NAVIGATION ) {
emitCounterMetrics( "addressBookAdded", METRIC_ADD_ADDRESS_BOOK_NAVIGATION, 1 );
}
std::lock_guard<std::mutex> guard( m_mutex );
m_addressBookEventQ.emplace_back( Event::Type::ADD, addressBookEntity );
m_waitStatusChange.notify_all();
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addressBookAdded").d("addressBookSourceId", addressBookSourceId).d("reason", ex.what()));
return false;
}
}
bool AddressBookCloudUploader::addressBookRemoved( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
std::string addressBookSourceId = INVALID_ADDRESS_BOOK_SOURCE_ID;
try {
ThrowIfNull( addressBookEntity, "invalidAddressBook" );
addressBookSourceId = addressBookEntity->getSourceId();
// For Metrics
if( addressBookEntity->getType() == AddressBookType::CONTACT ) {
emitCounterMetrics( "addressBookRemoved", METRIC_REMOVE_ADDRESS_BOOK_CONTACT, 1 );
} else if( addressBookEntity->getType() == AddressBookType::NAVIGATION ) {
emitCounterMetrics( "addressBookRemoved", METRIC_REMOVE_ADDRESS_BOOK_NAVIGATION, 1 );
}
std::lock_guard<std::mutex> guard( m_mutex );
if( m_addressBookEventQ.size() > 0 ) {
if( isEventEnqueuedLocked( Event::Type::ADD, addressBookEntity ) ) {
AACE_INFO(LX(TAG,"removeAddressBook").m("removingCorrespondingAddEvent").d("addressBookSourceId", addressBookSourceId));
removeMatchingAddEventFromQueueLocked( addressBookEntity );
return true;
}
}
m_addressBookEventQ.emplace_back( Event::Type::REMOVE, addressBookEntity );
m_waitStatusChange.notify_all();
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addressBookRemoved").d("addressBookSourceId", addressBookSourceId).d("reason", ex.what()));
return false;
}
}
bool AddressBookCloudUploader::isEventEnqueuedLocked( aace::engine::addressBook::Event::Type type, std::shared_ptr<AddressBookEntity> addressBookEntity ) {
for( auto&& it : m_addressBookEventQ ) {
if( it.getType() == type ) {
if( it.getAddressBookEntity()->getSourceId() == addressBookEntity->getSourceId() ) {
return true;
}
}
}
return false;
}
void AddressBookCloudUploader::removeMatchingAddEventFromQueueLocked( std::shared_ptr<AddressBookEntity> addressBookEntity ){
for( auto it = m_addressBookEventQ.begin(); it != m_addressBookEventQ.end(); it++ ) {
if( it->getType() == Event::Type::ADD ) {
if( it->getAddressBookEntity()->getSourceId() == addressBookEntity->getSourceId() ) {
m_addressBookEventQ.erase( it );
return;
}
}
}
}
class AddressBookEntriesFactory : public aace::addressBook::AddressBook::IAddressBookEntriesFactory {
public:
AddressBookEntriesFactory( std::shared_ptr<AddressBookEntity> addressBookEntity, std::vector<std::shared_ptr<rapidjson::Document>>& documents ) :
m_addressBookEntity( std::move( addressBookEntity ) ),
m_documents( documents ) {
}
private:
bool isEntryPresent( const std::string& entryId ) {
auto it = m_ids.find( entryId );
if( it == m_ids.end() ) {
return false;
}
return true;
}
void createEntryDataField( const std::string& entryId ) {
auto it = m_ids.find( entryId );
if( it == m_ids.end() ) {
// For "m_ids[id] = m_ids.size();" on Ubuntu platform, [] seems to increment the m_ids
// size before assignment that causes incorrect indexes for later usage.
auto index = m_ids.size();
m_ids[entryId] = index;
auto bucketIndex = m_ids[entryId] / UPLOAD_BATCH_SIZE;
auto entriesIndex = m_ids[entryId] % UPLOAD_BATCH_SIZE;
// Check if bucket mapping to bucketIndex is new bucket to be created.
if( bucketIndex + 1 > ( m_documents.size() ) ) {
auto document = std::make_shared<rapidjson::Document>();
document->SetObject();
m_documents.push_back( document );
auto& allocator = document->GetAllocator();
rapidjson::Value entries(rapidjson::kArrayType);
document->AddMember( "entries", entries, allocator );
}
auto& document = *m_documents[bucketIndex];
auto& allocator = document.GetAllocator();
auto& entries = document["entries"];
if( entriesIndex + 1 > entries.Size() ) {
rapidjson::Value entry(rapidjson::kObjectType);
entry.AddMember( "entrySourceId", entryId, allocator );
rapidjson::Value data(rapidjson::kObjectType);
entry.AddMember( "data", data, allocator );
entries.PushBack( entry, allocator );
}
}
}
rapidjson::Value& getEntryDataField( const std::string& entryId ) {
auto bucketIndex = m_ids[entryId] / UPLOAD_BATCH_SIZE;
auto entriesIndex = m_ids[entryId] % UPLOAD_BATCH_SIZE;
auto& document = *m_documents[bucketIndex];
auto& entries = document["entries"];
return entries[entriesIndex]["data"];
}
rapidjson::Document::AllocatorType& GetAllocator( const std::string& entryId ) {
auto bucketIndex = m_ids[entryId] / UPLOAD_BATCH_SIZE;
auto& document = *m_documents[bucketIndex];
return document.GetAllocator();
}
public:
bool addName( const std::string& entryId, const std::string& name ) {
try {
ThrowIf( entryId.empty(), "entryIdEmpty" );
ThrowIf( entryId.size() > MAX_ALLOWED_ENTRY_ID_SIZE, "entryIdInvalid" );
ThrowIf( name.size() > MAX_ALLOWED_CHARACTERS, "nameInvalid" );
if( !isEntryPresent( entryId ) ) {
createEntryDataField( entryId );
}
auto& data = getEntryDataField( entryId );
auto& allocator = GetAllocator( entryId );
rapidjson::Value nameValue( rapidjson::kObjectType );
ThrowIf( data.HasMember( "name" ), "nameFound" );
if( !name.empty() ) nameValue.AddMember( "firstName", name, allocator );
data.AddMember( "name", nameValue, allocator );
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addName").d("entryId", entryId).d("reason", ex.what()));
return false;
}
}
bool addName( const std::string& entryId, const std::string& firstName, const std::string& lastName ) {
try {
ThrowIf( entryId.empty(), "entryIdEmpty" );
ThrowIf( entryId.size() > MAX_ALLOWED_ENTRY_ID_SIZE, "entryIdInvalid" );
ThrowIf( firstName.size() > MAX_ALLOWED_CHARACTERS, "firstNameInvalid" );
ThrowIf( lastName.size() > MAX_ALLOWED_CHARACTERS, "lastNameInvalid" );
ThrowIf( firstName.size() + lastName.size() > MAX_ALLOWED_CHARACTERS, "nameInvalid" );
if( !isEntryPresent( entryId ) ) {
createEntryDataField( entryId );
}
auto& data = getEntryDataField( entryId );
auto& allocator = GetAllocator( entryId );
rapidjson::Value name( rapidjson::kObjectType );
ThrowIf( data.HasMember( "name" ), "nameFound" );
if( !firstName.empty() ) name.AddMember( "firstName", firstName, allocator );
if( !lastName.empty() ) name.AddMember( "lastName", lastName, allocator );
data.AddMember( "name", name, allocator );
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addName").d("entryId", entryId).d("reason", ex.what()));
return false;
}
}
bool addName( const std::string& entryId, const std::string& firstName, const std::string& lastName, const std::string& nickname ) {
try {
ThrowIf( entryId.empty(), "entryIdEmpty" );
ThrowIf( entryId.size() > MAX_ALLOWED_ENTRY_ID_SIZE, "entryIdInvalid" );
ThrowIf( firstName.size() > MAX_ALLOWED_CHARACTERS, "firstNameInvalid" );
ThrowIf( lastName.size() > MAX_ALLOWED_CHARACTERS, "lastNameInvalid" );
ThrowIf( nickname.size() > MAX_ALLOWED_CHARACTERS, "nickNameInvalid" );
ThrowIf( ( firstName.size() + lastName.size() + nickname.size() ) > MAX_ALLOWED_CHARACTERS, "nameInvalid" );
if( !isEntryPresent( entryId ) ) {
createEntryDataField( entryId );
}
auto& data = getEntryDataField( entryId );
auto& allocator = GetAllocator( entryId );
rapidjson::Value name( rapidjson::kObjectType );
ThrowIf( data.HasMember( "name" ), "nameFound" );
if( !firstName.empty() ) name.AddMember( "firstName", firstName, allocator );
if( !lastName.empty() ) name.AddMember( "lastName", lastName, allocator );
if( !nickname.empty() ) name.AddMember( "nickName", nickname, allocator );
data.AddMember( "name", name, allocator );
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addName").d("entryId", entryId).d("reason", ex.what()));
return false;
}
}
bool addPhone( const std::string& entryId, const std::string& label, const std::string& number ) {
try {
ThrowIf( entryId.empty(), "entryIdEmpty" );
ThrowIf( entryId.size() > MAX_ALLOWED_ENTRY_ID_SIZE, "entryIdInvalid" );
ThrowIfNot( m_addressBookEntity->isAddressTypeSupported( AddressBookEntity::AddressType::PHONE ), "addressTypeNotSupported" );
if( !isEntryPresent( entryId ) ) {
createEntryDataField( entryId );
}
auto& data = getEntryDataField( entryId );
auto& allocator = GetAllocator( entryId );
if( !data.HasMember("addresses") ) {
auto addresses(rapidjson::kArrayType);
data.AddMember( "addresses", addresses, allocator );
}
auto& addresses = data["addresses"];
ThrowIf( isMaxAllowedReached( addresses ), "maxAllowedReached");
rapidjson::Value address(rapidjson::kObjectType);
address.AddMember( "addressType", "phonenumber", allocator );
if( !label.empty() ) address.AddMember( "rawType", label, allocator );
if( !number.empty() ) address.AddMember( "value", number, allocator );
addresses.PushBack( address, allocator );
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addPhone").d("entryId", entryId).d("reason", ex.what()));
return false;
}
}
bool addPostalAddress( const std::string& entryId,
const std::string& label,
const std::string& addressLine1,
const std::string& addressLine2,
const std::string& addressLine3,
const std::string& city,
const std::string& stateOrRegion,
const std::string& districtOrCounty,
const std::string& postalCode,
const std::string& countryCode,
float latitudeInDegrees,
float longitudeInDegrees,
float accuracyInMeters ) {
try {
ThrowIf( entryId.empty(), "entryIdEmpty" );
ThrowIf( entryId.size() > MAX_ALLOWED_ENTRY_ID_SIZE, "entryIdInvalid" );
int totalCharSize = addressLine1.size() + addressLine2.size() + addressLine3.size() + city.size() + stateOrRegion.size() + districtOrCounty.size() + postalCode.size() + countryCode.size();
ThrowIf( totalCharSize > MAX_ALLOWED_CHARACTERS, "postalAddressValueSizeExceedsLimit" );
ThrowIfNot( (latitudeInDegrees >= -90 && latitudeInDegrees <= 90 ), "latitudeInDegreesInvalid" );
ThrowIfNot( (longitudeInDegrees >= -180 && longitudeInDegrees <= 180 ), "longitudeInDegreesInvalid" );
ThrowIf( accuracyInMeters < 0, "accuracyInMetersInvalid" );
ThrowIfNot( m_addressBookEntity->isAddressTypeSupported( AddressBookEntity::AddressType::POSTALADDRESS ), "addressTypeNotSupported" );
if( !isEntryPresent( entryId ) ) {
createEntryDataField( entryId );
}
auto& data = getEntryDataField( entryId );
auto& allocator = GetAllocator( entryId );
if( !data.HasMember("addresses") ) {
auto addresses(rapidjson::kArrayType);
data.AddMember( "addresses", addresses, allocator );
}
auto& addresses = data["addresses"];
ThrowIf( isMaxAllowedReached( addresses ), "maxAllowedReached" );
rapidjson::Value address(rapidjson::kObjectType);
address.AddMember( "addressType", "postaladdress", allocator );
if( !label.empty() ) address.AddMember( "rawType", label, allocator );
rapidjson::Value postalAddressValue(rapidjson::kObjectType);
if( !addressLine1.empty() ) postalAddressValue.AddMember( "addressLine1", addressLine1, allocator );
if( !addressLine2.empty() ) postalAddressValue.AddMember( "addressLine2", addressLine2, allocator );
if( !addressLine3.empty() ) postalAddressValue.AddMember( "addressLine3", addressLine3, allocator );
if( !city.empty() ) postalAddressValue.AddMember( "city", city, allocator );
if( !stateOrRegion.empty() ) postalAddressValue.AddMember( "stateOrRegion", stateOrRegion, allocator );
if( !districtOrCounty.empty() ) postalAddressValue.AddMember( "districtOrCounty", districtOrCounty, allocator );
if( !postalCode.empty() ) postalAddressValue.AddMember( "postalCode", postalCode, allocator );
if( !countryCode.empty() ) postalAddressValue.AddMember( "countryCode", countryCode, allocator );
rapidjson::Value coordinate( rapidjson::kObjectType );
coordinate.AddMember( "latitudeInDegrees", latitudeInDegrees, allocator );
coordinate.AddMember( "longitudeInDegrees", longitudeInDegrees, allocator );
if( accuracyInMeters > 0 ) coordinate.AddMember( "accuracyInMeters", accuracyInMeters, allocator );
postalAddressValue.AddMember( "coordinate", coordinate, allocator );
address.AddMember( "postalAddress", postalAddressValue, allocator );
addresses.PushBack( address, allocator );
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"addPostalAddress").d("entryId", entryId).d("reason", ex.what()));
return false;
}
}
bool isMaxAllowedReached( rapidjson::Value& addresses ) {
if( addresses.IsArray() && addresses.Size() < MAX_ALLOWED_ADDRESSES_PER_ENTRY ) {
return false;
}
return true;
}
private:
std::shared_ptr<AddressBookEntity> m_addressBookEntity;
std::vector<std::shared_ptr<rapidjson::Document>>& m_documents;
std::unordered_map<std::string, rapidjson::SizeType> m_ids;
};
bool AddressBookCloudUploader::handleUpload( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
std::string addressBookSourceId = INVALID_ADDRESS_BOOK_SOURCE_ID;
try {
addressBookSourceId = addressBookEntity->getSourceId();
std::vector<std::shared_ptr<rapidjson::Document>> documents;
auto factory = std::make_shared<AddressBookEntriesFactory>( addressBookEntity, documents );
AACE_INFO(LX(TAG,"handleUpload").m("GettingAddressBookEntries").d("addressBookSourceId",addressBookSourceId));
if( !m_addressBookService->getEntries( addressBookSourceId, factory ) ) {
// getEntries can return false, it probably means OEM was not successful in providing all the entries.
// The common reason could be the address book may have become unavailable or not accessible, so do not retry.
AACE_WARN(LX(TAG,"handleUpload").d("addressBookSourceId", addressBookSourceId).d("reason", "getEntriesFailed"));
// Return true to drop this address book from retry.
return true;
}
if( documents.size() <= 0 ) {
// Its the empty document.
AACE_WARN(LX(TAG,"handleUpload").d("addressBookSourceId", addressBookSourceId).d("reason", "emptyDocumentToUpload"));
// Return true to drop this address book from retry.
return true;
}
int numberOfEntries = 0;
for( auto document : documents ) {
auto entries = document->FindMember("entries");
if( entries != document->MemberEnd() ) {
numberOfEntries += entries->value.Size();
}
}
//Preparing for the upload
auto cloudAddressBookId = prepareForUpload( addressBookEntity );
ThrowIf( cloudAddressBookId.empty(), "prepareUploadFailed" );
double uploadStartTimer = getCurrentTimeInMs();
//Upload json document in a loop.
for( auto document : documents ) {
ThrowIfNot( upload( cloudAddressBookId, document ), "uploadDocumentFailed" );
}
// It is assumed that between contacts and navigation addresses the difference is payload that should not
// influence the latency for uploading one batch of address book entries.
double totalDuration = getCurrentTimeInMs() - uploadStartTimer;
double timeToUploadOneBatch = totalDuration / documents.size();
emitTimerMetrics( "handleUpload", METRIC_TIME_TO_UPLOAD_ONE_BATCH, timeToUploadOneBatch );
AACE_INFO(LX(TAG,"handleUpload").m("SuccessfullyUploaded").d("addressBookSourceId",addressBookSourceId).d("numberOfEntries",numberOfEntries));
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"handleUpload").d("addressBookSourceId", addressBookSourceId).d("reason", ex.what()));
return false;
}
}
bool AddressBookCloudUploader::handleRemove( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
std::string addressBookSourceId = INVALID_ADDRESS_BOOK_SOURCE_ID;
try {
addressBookSourceId = addressBookEntity->getSourceId();
ThrowIfNot( deleteAddressBook( addressBookEntity ),"addressBookDeleteFailed" );
AACE_INFO(LX(TAG,"handleRemove").m("Removed Successfully").d("addressBookSourceId",addressBookSourceId));
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"handleRemove").d("addressBookSourceId",addressBookSourceId).d("reason", ex.what()));
return false;
}
}
void AddressBookCloudUploader::eventLoop() {
AACE_INFO(LX(TAG));
bool cleanAllAddressBookAtStart = true; // Delete all address books in Cloud at start.
while( !m_isShuttingDown ) {
// Clean up previous address books in cloud.
if( cleanAllAddressBookAtStart ) {
if( cleanAllCloudAddressBooks() ) {
cleanAllAddressBookAtStart = false;
} else {
continue;
}
}
AACE_DEBUG(LX(TAG).m("waitingForEvents"));
auto event = popNextEventFromQ(); // blocking call.
if( m_isShuttingDown ) {
AACE_INFO(LX(TAG).m("shutdownTriggeredExitEventLoop"));
break;
}
bool result = true;
if( Event::Type::INVALID != event.getType() ) {
if( Event::Type::ADD == event.getType() ) {
result = handleUpload( event.getAddressBookEntity() );
} else if( Event::Type::REMOVE == event.getType() ) {
result = handleRemove( event.getAddressBookEntity() );
}
bool enqueueBackPoppedEvent = false;
if( !result ) {
if( m_networkStatus != NetworkStatus::CONNECTED ) {
// If network lost, add back to queue.
enqueueBackPoppedEvent = true;
} else {
event.incrementRetryCount();
if( event.getRetryCount() < MAX_EVENT_RETRY ) {
enqueueBackPoppedEvent = true;
} else {
AACE_INFO(LX(TAG,"eventLoop").m("maxRetryReachedDropingtheEvent").d("addressBookSourceId",event.getAddressBookEntity()->getSourceId()).d("eventType",event.getType()));
}
}
if( enqueueBackPoppedEvent ) {
std::lock_guard<std::mutex> guard( m_mutex );
AACE_INFO(LX(TAG,"eventLoop").m("addingBackForRetry").d("addressBookSourceId",event.getAddressBookEntity()->getSourceId()).d("eventType",event.getType()));
if( !isEventEnqueuedLocked( Event::Type::REMOVE, event.getAddressBookEntity() ) ) {
m_addressBookEventQ.emplace_front ( event );
}
}
} else {
// For Metrics
if( Event::Type::ADD == event.getType() ) {
emitTimerMetrics( "eventLoop", METRIC_TIME_TO_UPLOAD_SINCE_ADD, getCurrentTimeInMs() - event.getEventCreateTime() );
} else {
emitTimerMetrics( "eventLoop", METRIC_TIME_TO_UPLOAD_SINCE_REMOVE, getCurrentTimeInMs() - event.getEventCreateTime() );
}
}
} else {
AACE_WARN(LX(TAG,"eventLoop").m("invalidEventFromQueue"));
}
}
}
const Event AddressBookCloudUploader::popNextEventFromQ() {
std::unique_lock<std::mutex> queueLock{m_mutex};
auto shouldNotWait = [this]() { return ( m_isShuttingDown || ( !m_addressBookEventQ.empty() && m_networkStatus == NetworkStatus::CONNECTED && m_isAuthRefreshed ) ); };
if( !shouldNotWait() ) {
m_waitStatusChange.wait( queueLock, shouldNotWait );
}
if( !m_addressBookEventQ.empty() ) {
auto event = m_addressBookEventQ.front();
m_addressBookEventQ.pop_front();
return event;
}
return Event::INVALID();
}
std::string AddressBookCloudUploader::prepareForUpload( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
try {
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->isAccountProvisioned(), "accountNotProvisioned");
// Try to delete any previous address book in cloud.
ThrowIfNot( deleteAddressBook( addressBookEntity ), "addressBookDeleteFailed" );
auto cloudAddressBookId = createAddressBook( addressBookEntity );
ThrowIf( cloudAddressBookId.empty(), "addressBookCreateFailed" );
return cloudAddressBookId;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"prepareForUpload").d("reason", ex.what()));
return std::string();
}
}
bool AddressBookCloudUploader::upload( const std::string& cloudAddressBookId, std::shared_ptr<rapidjson::Document> document ) {
try {
auto entries = document->FindMember("entries");
AACE_DEBUG(LX(TAG,"upload").d("entries.Size()", entries->value.Size()));
ThrowIfNot( uploadEntries( cloudAddressBookId, document ), "uploadEntriesFailed" );
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"upload").d("reason", ex.what()));
return false;
}
}
bool AddressBookCloudUploader::uploadEntries( const std::string& cloudAddressBookId, std::shared_ptr<rapidjson::Document> document ) {
HTTPResponse httpResponse;
auto flowState = UploadFlowState::POST;
bool success = true;
while( !m_isShuttingDown && flowState != UploadFlowState::FINISH ) {
auto nextFlowState = UploadFlowState::ERROR;
AACE_DEBUG(LX(TAG,"uploadEntries").d( "flowState", flowState ) );
switch( flowState ) {
case UploadFlowState::POST:
nextFlowState = handleUploadEntries( cloudAddressBookId, document, httpResponse );
break;
case UploadFlowState::PARSE:
nextFlowState = handleParseHTTPResponse( httpResponse );
break;
case UploadFlowState::ERROR:
nextFlowState = handleError( cloudAddressBookId );
success = false;
break;
case UploadFlowState::FINISH:
break;
}
flowState = nextFlowState;
}
return success;
}
AddressBookCloudUploader::UploadFlowState AddressBookCloudUploader::handleError(const std::string& cloudAddressBookId ) {
try {
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->deleteCloudAddressBook( cloudAddressBookId ), "deleteCloudAddressBookFailed" ) ;
} catch( std::exception &ex ) {
AACE_ERROR(LX(TAG,"handleError").d("reason", ex.what()));
}
return UploadFlowState::FINISH;
}
AddressBookCloudUploader::UploadFlowState AddressBookCloudUploader::handleUploadEntries( const std::string& addressBookId, std::shared_ptr<rapidjson::Document> document, HTTPResponse& httpResponse ) {
try {
httpResponse = m_addressBookCloudUploaderRESTAgent->uploadDocumentToCloud( document, addressBookId );
logNetworkMetrics( httpResponse );
switch( httpResponse.code ) {
case HTTPResponseCode::SUCCESS_OK:
return UploadFlowState::PARSE;
case HTTPResponseCode::HTTP_RESPONSE_CODE_UNDEFINED:
case HTTPResponseCode::SUCCESS_NO_CONTENT:
case HTTPResponseCode::REDIRECTION_START_CODE:
case HTTPResponseCode::REDIRECTION_END_CODE:
case HTTPResponseCode::BAD_REQUEST:
case HTTPResponseCode::FORBIDDEN:
case HTTPResponseCode::SERVER_INTERNAL_ERROR:
Throw( "handleUploadEntriesFailed" + m_addressBookCloudUploaderRESTAgent->getHTTPErrorString( httpResponse ) );
break;
}
return UploadFlowState::ERROR;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"handleUploadEntries").d("reason", ex.what()));
return UploadFlowState::ERROR; //On exception return ERROR.
}
}
AddressBookCloudUploader::UploadFlowState AddressBookCloudUploader::handleParseHTTPResponse( const HTTPResponse& httpResponse ) {
try {
std::queue<std::string> failedEntries;
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->parseCreateAddressBookEntryResponse( httpResponse, failedEntries ), "responseJsonParseFailed" );
// Continue to upload rest of the entries, even if there are one or more failed entries.
if( failedEntries.size() ) {
AACE_WARN(LX(TAG,"handleParse").d("NumberOfFailedEntries", failedEntries.size() ) );
}
return UploadFlowState::FINISH;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"handleParse").d("reason", ex.what()));
return UploadFlowState::ERROR;
}
}
void AddressBookCloudUploader::logNetworkMetrics( const HTTPResponse& httpResponse ) {
switch( httpResponse.code ) {
case HTTPResponseCode::SUCCESS_OK:
// Do Nothing
break;
case HTTPResponseCode::BAD_REQUEST:
emitCounterMetrics( "logNetworkMetrics", METRIC_NETWORK_BAD_USER_INPUT, 1 );
break;
case HTTPResponseCode::HTTP_RESPONSE_CODE_UNDEFINED:
case HTTPResponseCode::SUCCESS_NO_CONTENT:
case HTTPResponseCode::REDIRECTION_START_CODE:
case HTTPResponseCode::REDIRECTION_END_CODE:
case HTTPResponseCode::FORBIDDEN:
case HTTPResponseCode::SERVER_INTERNAL_ERROR:
emitCounterMetrics( "logNetworkMetrics", METRIC_NETWORK_ERROR, 1 );
}
}
std::string AddressBookCloudUploader::createAddressBook( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
try {
auto dsn = m_deviceInfo->getDeviceSerialNumber(); // Use DSN as addressBookSourceId.
auto cloudAddressBookId = m_addressBookCloudUploaderRESTAgent->createAndGetCloudAddressBook( dsn, addressBookEntity->toJSONAddressBookType() );
ThrowIf( cloudAddressBookId.empty(), "emptyCloudAddressBookId" );
return cloudAddressBookId;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"createAddressBook").d("reason", ex.what()));
return std::string();
}
}
bool AddressBookCloudUploader::deleteAddressBook( std::shared_ptr<AddressBookEntity> addressBookEntity ) {
try {
auto dsn = m_deviceInfo->getDeviceSerialNumber(); // Use DSN as addressBookSourceId.
std::string cloudAddressBookId;
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->getCloudAddressBookId( dsn, addressBookEntity->toJSONAddressBookType(), cloudAddressBookId ), "getCloudAddressBookIdFailed" );
if( !cloudAddressBookId.empty() ) {
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->deleteCloudAddressBook( cloudAddressBookId ), "deleteCloudAddressBookFailed" ) ;
}
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"deleteAddressBook").d("reason", ex.what()));
return false;
}
}
bool AddressBookCloudUploader::cleanAllCloudAddressBooks() {
AACE_DEBUG(LX(TAG));
try {
{
std::unique_lock<std::mutex> queueLock{m_mutex};
auto shouldNotWait = [this]() { return m_isShuttingDown || ( m_networkStatus == NetworkStatus::CONNECTED && m_isAuthRefreshed); };
if( !shouldNotWait() ) {
m_waitStatusChange.wait( queueLock, shouldNotWait );
}
}
if( m_isShuttingDown ) {
AACE_INFO(LX(TAG).m("shutdownTriggered"));
return false;
}
if( !m_addressBookCloudUploaderRESTAgent->isAccountProvisioned() ) {
// Account not provisioned, no further action required.
AACE_DEBUG(LX(TAG).m("accountNotProvisioned"));
return true;
}
auto dsn = m_deviceInfo->getDeviceSerialNumber();
// Delete Contact Address book
std::string cloudAddressBookId;
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->getCloudAddressBookId( dsn, "automotive", cloudAddressBookId ), "getCloudAddressBookIdFailed" );
if( !cloudAddressBookId.empty() ) {
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->deleteCloudAddressBook( cloudAddressBookId ), "deleteCloudAddressBookFailed" ) ;
}
// Delete Navigation Address book
cloudAddressBookId = "";
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->getCloudAddressBookId( dsn, "automotivePostalAddress", cloudAddressBookId ), "getCloudAddressBookIdFailed" );
if( !cloudAddressBookId.empty() ) {
ThrowIfNot( m_addressBookCloudUploaderRESTAgent->deleteCloudAddressBook( cloudAddressBookId ), "deleteCloudAddressBookFailed" ) ;
}
return true;
} catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"cleanAllCloudAddressBooks").d("reason", ex.what()));
return false;
}
}
void AddressBookCloudUploader::emitCounterMetrics( const std::string& methodName, const std::string& key, const int value ) {
auto metricEvent = std::shared_ptr<aace::engine::metrics::MetricEvent>(new aace::engine::metrics::MetricEvent( METRIC_PROGRAM_NAME, methodName ));
if( metricEvent ) {
metricEvent->addCounter( key, value );
metricEvent->record();
}
}
void AddressBookCloudUploader::emitTimerMetrics( const std::string& methodName, const std::string& key, const double value ) {
auto metricEvent = std::shared_ptr<aace::engine::metrics::MetricEvent>(new aace::engine::metrics::MetricEvent( METRIC_PROGRAM_NAME, methodName ));
if( metricEvent ) {
metricEvent->addTimer( key, value );
metricEvent->record();
}
}
double AddressBookCloudUploader::getCurrentTimeInMs() {
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
double duration = now_ms.count();
return duration;
}
} // aace::engine::addressBook
} // aace::engine
} // aace
| 42.539749 | 201 | 0.657888 | [
"vector"
] |
82d5a6bf2d3835e5fda53b4cc611fcec870f648a | 1,769 | cpp | C++ | Gems/Terrain/Code/Source/TerrainRenderer/Aabb2i.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-28T08:06:58.000Z | 2022-03-28T08:06:58.000Z | Gems/Terrain/Code/Source/TerrainRenderer/Aabb2i.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Terrain/Code/Source/TerrainRenderer/Aabb2i.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <TerrainRenderer/Aabb2i.h>
#include <AzCore/Math/MathUtils.h>
namespace Terrain
{
Aabb2i::Aabb2i(const Vector2i& min, const Vector2i& max)
: m_min(min)
, m_max(max)
{}
Aabb2i Aabb2i::operator+(const Vector2i& rhs) const
{
Aabb2i returnValue = *this;
returnValue += rhs;
return returnValue;
}
Aabb2i& Aabb2i::operator+=(const Vector2i& rhs)
{
m_min += rhs;
m_max += rhs;
return *this;
}
Aabb2i Aabb2i::operator-(const Vector2i& rhs) const
{
Aabb2i returnValue = *this;
returnValue -= rhs;
return returnValue;
}
Aabb2i& Aabb2i::operator-=(const Vector2i& rhs)
{
m_min -= rhs;
m_max -= rhs;
return *this;
}
bool Aabb2i::operator==(const Aabb2i& other) const
{
return m_min == other.m_min && m_max == other.m_max;
}
bool Aabb2i::operator!=(const Aabb2i& other) const
{
return !(*this == other);
}
Aabb2i Aabb2i::GetClamped(Aabb2i rhs) const
{
Aabb2i ret;
ret.m_min.m_x = AZ::GetMax(m_min.m_x, rhs.m_min.m_x);
ret.m_min.m_y = AZ::GetMax(m_min.m_y, rhs.m_min.m_y);
ret.m_max.m_x = AZ::GetMin(m_max.m_x, rhs.m_max.m_x);
ret.m_max.m_y = AZ::GetMin(m_max.m_y, rhs.m_max.m_y);
return ret;
}
bool Aabb2i::IsValid() const
{
// Intentionally strict, equal min/max not valid.
return m_min.m_x < m_max.m_x && m_min.m_y < m_max.m_y;
}
}
| 24.232877 | 100 | 0.585642 | [
"3d"
] |
82d7e27046d54e3445f3f8d201006dc0fd0b3bff | 361 | hpp | C++ | pathfinder.hpp | LesleyLai/Lai_CSCI2270_FinalProject | dbf71d4be4236cd8a5ce4629117952882d3509fe | [
"MIT"
] | null | null | null | pathfinder.hpp | LesleyLai/Lai_CSCI2270_FinalProject | dbf71d4be4236cd8a5ce4629117952882d3509fe | [
"MIT"
] | null | null | null | pathfinder.hpp | LesleyLai/Lai_CSCI2270_FinalProject | dbf71d4be4236cd8a5ce4629117952882d3509fe | [
"MIT"
] | null | null | null | #ifndef PATHFINDER_HPP
#define PATHFINDER_HPP
// Path finding algorithms
#include "type.hpp"
class Graph;
struct Vertex;
std::vector<Vertex*> depth_first_search(Vertex& start, Vertex& end);
std::vector<Vertex*> breath_first_search(Vertex& start, Vertex& end);
std::vector<Vertex*> dijkstras_algorithm(Vertex& start, Vertex& end);
#endif // PATHFINDER_HPP
| 21.235294 | 69 | 0.767313 | [
"vector"
] |
82dfa5526171eefeae14e0218f4f450adaf09764 | 11,235 | cc | C++ | test_prelude.cc | kdungs/cpp-prelude | 607bea876cbc41e497cc43c69bd0d4ac6e37a7a0 | [
"MIT"
] | 4 | 2015-12-27T03:12:50.000Z | 2021-07-22T20:54:43.000Z | test_prelude.cc | kdungs/cpp-prelude | 607bea876cbc41e497cc43c69bd0d4ac6e37a7a0 | [
"MIT"
] | null | null | null | test_prelude.cc | kdungs/cpp-prelude | 607bea876cbc41e497cc43c69bd0d4ac6e37a7a0 | [
"MIT"
] | null | null | null | #include "prelude.h"
#include <array>
#include <cassert>
#include <iostream>
#include <list>
#include <string>
#include <vector>
auto test_not_() -> void {
using Prelude::not_;
auto even = [](int x) { return x % 2 == 0; };
auto odd = not_<int>(even);
assert(odd(3) == true);
assert(odd(2) == false);
}
auto test_map() -> void {
using Prelude::map;
auto expect = std::vector<bool>{false, true, false, true, false};
auto even = [](int x) { return x % 2 == 0; };
auto result = map(even, std::vector<int>{1, 2, 3, 4, 5});
assert(result == expect);
}
auto test_join() -> void {
using Prelude::join;
auto expect = std::vector<int>{1, 2, 3, 4};
auto result = join(std::vector<int>{1, 2}, std::vector<int>{3, 4});
assert(result == expect);
}
auto test_filter() -> void {
using Prelude::filter;
auto expect = std::vector<int>{2, 4};
auto even = [](int x) { return x % 2 == 0; };
auto result = filter(even, std::vector<int>{1, 2, 3, 4, 5});
assert(result == expect);
}
auto test_head() -> void {
using Prelude::head;
auto expect = 1;
auto result = head(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_last() -> void {
using Prelude::last;
auto expect = 4;
auto result = last(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_tail() -> void {
using Prelude::tail;
auto expect = std::vector<int>{2, 3, 4};
auto result = tail(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_init() -> void {
using Prelude::init;
auto expect = std::vector<int>{1, 2, 3};
auto result = init(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_null() -> void {
using Prelude::null;
assert(null(std::vector<int>{}));
assert(!null(std::vector<int>{1}));
}
auto test_length() -> void {
using Prelude::length;
assert(length(std::vector<int>{}) == 0);
assert(length(std::vector<int>{1, 2, 3, 4}) == 4);
}
auto test_at() -> void {
using Prelude::at;
assert(at(std::vector<int>{1, 2, 3, 4}, 2) == 3);
}
auto test_reverse() -> void {
using Prelude::reverse;
auto expect = std::vector<int>{4, 3, 2, 1};
auto result = reverse(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_foldl() -> void {
using Prelude::foldl;
auto expect = 10;
auto result = foldl([](int acc, int x) { return acc + x; }, 0,
std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_foldl1() -> void {
using Prelude::foldl1;
auto expect = 10;
auto result = foldl1([](int acc, int x) { return acc + x; },
std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_foldr() -> void {
using Prelude::foldr;
auto expect = 10;
auto result = foldr([](int x, int acc) { return x + acc; }, 0,
std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_foldr1() -> void {
using Prelude::foldr1;
auto expect = 10;
auto result = foldr1([](int x, int acc) { return x + acc; },
std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_and_() -> void {
using Prelude::and_;
assert(and_(std::vector<bool>{true, true, true, true}) == true);
assert(and_(std::vector<bool>{true, true, false, true}) == false);
}
auto test_or_() -> void {
using Prelude::or_;
assert(or_(std::vector<bool>{false, false, false, false}) == false);
assert(or_(std::vector<bool>{false, true, false, true}) == true);
}
auto test_any() -> void {
using Prelude::any;
assert(any([](int x) { return x > 3; }, std::vector<int>{1, 2, 3, 4}) ==
true);
assert(any([](int x) { return x > 5; }, std::vector<int>{1, 2, 3, 4}) ==
false);
}
auto test_all() -> void {
using Prelude::all;
assert(all([](int x) { return x > 3; }, std::vector<int>{1, 2, 3, 4}) ==
false);
assert(all([](int x) { return x < 5; }, std::vector<int>{1, 2, 3, 4}) ==
true);
}
auto test_sum() -> void {
using Prelude::sum;
auto expect = 10;
auto result = sum(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_product() -> void {
using Prelude::product;
auto expect = 24;
auto result = product(std::vector<int>{1, 2, 3, 4});
assert(result == expect);
}
auto test_concat() -> void {
using Prelude::concat;
auto expect = std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9};
auto result = concat(
std::array<std::vector<int>, 3>{{{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}});
assert(result == expect);
}
auto test_concatMap() -> void {
using Prelude::concatMap;
auto expect = std::vector<int>{1, 1, 1, 2, 2, 2, 3, 3, 3};
auto result = concatMap([](int x) {
return std::vector<int>{x, x, x};
}, std::list<int>{1, 2, 3});
assert(result == expect);
}
auto test_maximum() -> void {
using Prelude::maximum;
auto expect = 23;
auto result = maximum(std::vector<int>{1, 2, 3, 23, 4, 5});
assert(result == expect);
}
auto test_minimum() -> void {
using Prelude::minimum;
auto expect = -23;
auto result = minimum(std::vector<int>{1, 2, 3, 4, -23, 5});
assert(result == expect);
}
auto test_take() -> void {
using Prelude::take;
auto expect = std::vector<int>{1, 2, 3, 4};
auto result = take(4, std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(result == expect);
// also check case for n > size
result = take(100, expect);
assert(result == expect && "Also has to work for n > size!");
}
auto test_drop() -> void {
using Prelude::drop;
auto expect = std::vector<int>{5, 6, 7, 8};
auto result = drop(4, std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(result == expect);
// also check case for n > size
result = drop(100, std::vector<int>{1, 2, 3, 4});
expect = std::vector<int>{};
assert(result == expect && "Also has to work for n > size!");
}
auto test_splitAt() -> void {
using Prelude::splitAt;
auto expectL = std::vector<int>{1, 2, 3, 4};
auto expectR = std::vector<int>{5, 6, 7, 8};
std::vector<int> resultL, resultR;
std::tie(resultL, resultR) =
splitAt(4, std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(resultL == expectL);
assert(resultR == expectR);
// empty first half
expectL = std::vector<int>{};
expectR = std::vector<int>{1, 2, 3, 4};
std::tie(resultL, resultR) = splitAt(0, std::vector<int>{1, 2, 3, 4});
assert(resultL == expectL);
assert(resultR == expectR);
// empty second half
expectL = std::vector<int>{1, 2, 3, 4};
expectR = std::vector<int>{};
std::tie(resultL, resultR) = splitAt(10, std::vector<int>{1, 2, 3, 4});
assert(resultL == expectL);
assert(resultR == expectR);
}
auto test_takeWhile() -> void {
using Prelude::takeWhile;
auto expect = std::vector<int>{1, 2, 3, 4};
auto result = takeWhile([](int x) { return x < 5; },
std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(result == expect);
}
auto test_dropWhile() -> void {
using Prelude::dropWhile;
auto expect = std::vector<int>{5, 6, 7, 8};
auto result = dropWhile([](int x) { return x < 5; },
std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(result == expect);
}
auto test_span() -> void {
using Prelude::span;
auto expectL = std::vector<int>{1, 2, 3, 4};
auto expectR = std::vector<int>{5, 6, 7, 8};
std::vector<int> resultL, resultR;
std::tie(resultL, resultR) = span([](int x) { return x < 5; },
std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(resultL == expectL);
assert(resultR == expectR);
}
auto test_break_() -> void {
using Prelude::break_;
auto expectL = std::vector<int>{1, 2, 3, 4};
auto expectR = std::vector<int>{5, 6, 7, 8};
std::vector<int> resultL, resultR;
std::tie(resultL, resultR) = break_([](int x) { return x >= 5; },
std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8});
assert(resultL == expectL);
assert(resultR == expectR);
}
auto test_zip() -> void {
using Prelude::zip;
auto expect = std::vector<std::tuple<int, bool>>{std::make_tuple(1, true),
std::make_tuple(2, false),
std::make_tuple(3, true)};
auto result =
zip(std::vector<int>{1, 2, 3}, std::list<bool>{true, false, true});
assert(result == expect);
}
auto test_zip3() -> void {
using Prelude::zip3;
auto expect = std::vector<std::tuple<int, bool, char>>{
std::make_tuple(1, true, 'a'), std::make_tuple(2, false, 'b'),
std::make_tuple(3, true, 'm')};
auto result =
zip3(std::vector<int>{1, 2, 3}, std::list<bool>{true, false, true},
std::vector<char>{'a', 'b', 'm'});
assert(result == expect);
}
auto test_zipWith() -> void {
using Prelude::zipWith;
auto expect = std::vector<int>{1, 0, 3, 0, 5, 0};
auto result = zipWith([](int x, bool y) { return y ? x : 0; },
std::vector<int>{1, 2, 3, 4, 5, 6},
std::list<bool>{true, false, true, false, true, false});
assert(result == expect);
}
auto test_zipWith3() -> void {
using Prelude::zipWith3;
auto expect = std::vector<std::string>{"aaa", "", "ccccc"};
auto result =
zipWith3([](int x, bool y, char z) { return y ? std::string(x, z) : ""; },
std::vector<int>{3, 4, 5}, std::list<bool>{true, false, true},
std::list<char>{'a', 'b', 'c'});
assert(result == expect);
}
auto test_unzip() -> void {
using Prelude::unzip;
auto expectL = std::vector<int>{1, 2, 3};
auto expectR = std::vector<bool>{true, false, true};
std::vector<int> resultL;
std::vector<bool> resultR;
std::tie(resultL, resultR) = unzip(std::vector<std::tuple<int, bool>>{
std::make_tuple(1, true), std::make_tuple(2, false),
std::make_tuple(3, true)});
assert(resultL == expectL);
assert(resultR == expectR);
}
auto test_unzip3() -> void {
using Prelude::unzip3;
auto expectL = std::vector<int>{1, 2, 3};
auto expectM = std::vector<char>{'a', 'b', 'c'};
auto expectR = std::vector<bool>{true, false, true};
std::vector<int> resultL;
std::vector<char> resultM;
std::vector<bool> resultR;
std::tie(resultL, resultM, resultR) =
unzip3(std::vector<std::tuple<int, char, bool>>{
std::make_tuple(1, 'a', true), std::make_tuple(2, 'b', false),
std::make_tuple(3, 'c', true)});
assert(resultL == expectL);
assert(resultM == expectM);
assert(resultR == expectR);
}
int main() {
test_not_();
// List operations
test_map();
test_join();
test_filter();
test_head();
test_last();
test_tail();
test_init();
test_null();
test_at();
test_reverse();
// Reducing lists (folds)
test_foldl();
test_foldl1();
test_foldr();
test_foldr1();
// Special folds
test_and_();
test_or_();
test_any();
test_all();
test_sum();
test_product();
test_concat();
test_concatMap();
test_maximum();
test_minimum();
// Sublists
test_take();
test_drop();
test_splitAt();
test_takeWhile();
test_dropWhile();
test_span();
test_break_();
// Zipping and unzipping lists
test_zip();
test_zip3();
test_zipWith();
test_zipWith3();
test_unzip();
test_unzip3();
std::cout << "Looking good!\n";
}
| 28.299748 | 80 | 0.576324 | [
"vector"
] |
82e4d1433a37f5aa2da5ac4946ec1ee6ca5394fc | 832 | cpp | C++ | UVa/uva 111.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | UVa/uva 111.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | UVa/uva 111.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | // By KRT girl xiplus
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int n;
int v[21];
int LIS(){
vector<int> lis;
lis.push_back(v[1]);
for(int q=2;q<=n;q++){
if(v[q]>lis.back()){
lis.push_back(v[q]);
}else {
lis[lower_bound(lis.begin(),lis.end(),v[q])-lis.begin()]=v[q];
}
}
return lis.size();
}
void flip(int arr[],int n){
int temp[n+1];
for(int q=1;q<=n;q++){
temp[arr[q]]=q;
}
for(int q=1;q<=n;q++){
arr[q]=temp[q];
}
}
int main(){
// ios::sync_with_stdio(false);
// cin.tie(0);
int k;
cin>>n;
int temp[n+1],ans[n+1];
for(int q=1;q<=n;q++){
cin>>temp[q];
}
flip(temp,n);
for(int q=1;q<=n;q++){
ans[temp[q]]=q;
}
while(cin>>temp[1]){
for(int q=2;q<=n;q++){
cin>>temp[q];
}
flip(temp,n);
for(int q=1;q<=n;q++){
v[q]=ans[temp[q]];
}
cout<<LIS()<<endl;
}
}
| 16 | 65 | 0.530048 | [
"vector"
] |
82e73f1f9b4095c0ad09dae054c69af22c355efd | 15,364 | cpp | C++ | vpx/snpe/LoadInputTensor.cpp | yindaheng98/nemo-libvpx | 10d8caadb28087577af27b0792f4ed3aef68ca16 | [
"BSD-3-Clause"
] | 2 | 2021-08-08T16:26:44.000Z | 2022-03-07T01:38:08.000Z | vpx/snpe/LoadInputTensor.cpp | yindaheng98/nemo-libvpx | 10d8caadb28087577af27b0792f4ed3aef68ca16 | [
"BSD-3-Clause"
] | null | null | null | vpx/snpe/LoadInputTensor.cpp | yindaheng98/nemo-libvpx | 10d8caadb28087577af27b0792f4ed3aef68ca16 | [
"BSD-3-Clause"
] | null | null | null | //==============================================================================
//
// Copyright (c) 2017-2019 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#include <iostream>
#include <vector>
#include <string>
#include <assert.h>
#include <unordered_map>
#include <cstring>
#include <cstdlib>
#include "LoadInputTensor.hpp"
#include "Util.hpp"
#include "SNPE/SNPE.hpp"
#include "SNPE/SNPEFactory.hpp"
#include "DlSystem/ITensor.hpp"
#include "DlSystem/StringList.hpp"
#include "DlSystem/TensorMap.hpp"
#include "DlSystem/TensorShape.hpp"
#ifdef __ANDROID_API__
#include <android/log.h>
#define TAG "LoadInputTensor JNI"
#define _UNKNOWN 0
#define _DEFAULT 1
#define _VERBOSE 2
#define _DEBUG 3
#define _INFO 4
#define _WARN 5
#define _ERROR 6
#define _FATAL 7
#define _SILENT 8
#define LOGUNK(...) __android_log_print(_UNKNOWN,TAG,__VA_ARGS__)
#define LOGDEF(...) __android_log_print(_DEFAULT,TAG,__VA_ARGS__)
#define LOGV(...) __android_log_print(_VERBOSE,TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(_DEBUG,TAG,__VA_ARGS__)
#define LOGI(...) __android_log_print(_INFO,TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(_WARN,TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(_ERROR,TAG,__VA_ARGS__)
#define LOGF(...) __android_log_print(_FATAL,TAG,__VA_ARGS__)
#define LOGS(...) __android_log_print(_SILENT,TAG,__VA_ARGS__)
#endif
std::unique_ptr<zdl::DlSystem::ITensor> loadInputTensorFromFloatBuffer(std::shared_ptr<zdl::SNPE::SNPE>& snpe , float * buffer, int number_of_elements){
std::unique_ptr<zdl::DlSystem::ITensor> input;
const auto &strList_opt = snpe->getInputTensorNames();
if (!strList_opt) throw std::runtime_error("Error obtaining Input tensor names");
const auto &strList = *strList_opt;
// Make sure the network requires only a single input
assert (strList.size() == 1);
std::vector<float> inputVec;
std::vector<float> loadedFile(buffer, buffer + number_of_elements);
inputVec.insert(inputVec.end(), loadedFile.begin(), loadedFile.end());
/* Create an input tensor that is correctly sized to hold the input of the network. Dimensions that have no fixed size will be represented with a value of 0. */
const auto &inputDims_opt = snpe->getInputDimensions(strList.at(0));
const auto &inputShape = *inputDims_opt;
/* Calculate the total number of elements that can be stored in the tensor so that we can check that the input contains the expected number of elements.
With the input dimensions computed create a tensor to convey the input into the network. */
input = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape);
//Padding the input vector so as to make the size of the vector to equal to an integer multiple of the batch size
zdl::DlSystem::TensorShape tensorShape= snpe->getInputDimensions();
size_t batchSize = tensorShape.getDimensions()[0];
if(1<batchSize) {
for(size_t j=0; j<batchSize-1; j++) {
std::vector<float> padding(input->getSize()/batchSize,0);
inputVec.insert(inputVec.end(),padding.begin(),padding.end());
}
}
if (input->getSize() != inputVec.size()) {
std::cerr << "Size of input does not match network.\n"
<< "Expecting: " << input->getSize() << "\n"
<< "Got: " << inputVec.size() << "\n";
std::exit(EXIT_FAILURE);
}
/* Copy the loaded input file contents into the networks input tensor. SNPE's ITensor supports C++ STL functions like std::copy() */
std::copy(inputVec.begin(), inputVec.end(), input->begin());
return std::move(input);
}
std::unique_ptr<zdl::DlSystem::ITensor> loadInputTensorFromByteBuffer(std::shared_ptr<zdl::SNPE::SNPE>& snpe , unsigned char * buffer, int number_of_elements){
std::unique_ptr<zdl::DlSystem::ITensor> input;
const auto &strList_opt = snpe->getInputTensorNames();
if (!strList_opt) throw std::runtime_error("Error obtaining Input tensor names");
const auto &strList = *strList_opt;
// Make sure the network requires only a single input
assert (strList.size() == 1);
std::vector<unsigned char> inputVec;
std::vector<unsigned char> loadedFile(buffer, buffer+number_of_elements);
inputVec.insert(inputVec.end(), loadedFile.begin(), loadedFile.end());
/* Create an input tensor that is correctly sized to hold the input of the network. Dimensions that have no fixed size will be represented with a value of 0. */
const auto &inputDims_opt = snpe->getInputDimensions(strList.at(0));
const auto &inputShape = *inputDims_opt;
/* Calculate the total number of elements that can be stored in the tensor so that we can check that the input contains the expected number of elements.
With the input dimensions computed create a tensor to convey the input into the network. */
input = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape);
//Padding the input vector so as to make the size of the vector to equal to an integer multiple of the batch size
zdl::DlSystem::TensorShape tensorShape= snpe->getInputDimensions();
size_t batchSize = tensorShape.getDimensions()[0];
if(1<batchSize) {
for(size_t j=0; j<batchSize-1; j++) {
std::vector<float> padding(input->getSize()/batchSize,0);
inputVec.insert(inputVec.end(),padding.begin(),padding.end());
}
}
if (input->getSize() != inputVec.size()) {
#if __ANDROID_API__
LOGE("Size of input does not match network.");
LOGE("Expecting: %d", input->getSize());
LOGE("Got: %d", inputVec.size());
#endif
std::cerr << "Size of input does not match network.\n"
<< "Expecting: " << input->getSize() << "\n"
<< "Got: " << inputVec.size() << "\n";
std::exit(EXIT_FAILURE);
}
/* Copy the loaded input file contents into the networks input tensor. SNPE's ITensor supports C++ STL functions like std::copy() */
std::copy(inputVec.begin(), inputVec.end(), input->begin());
return std::move(input);
}
// Load a batched single input tensor for a network which requires a single input
std::unique_ptr<zdl::DlSystem::ITensor> loadInputTensor (std::unique_ptr<zdl::SNPE::SNPE>& snpe , std::vector<std::string>& fileLines)
{
std::unique_ptr<zdl::DlSystem::ITensor> input;
const auto &strList_opt = snpe->getInputTensorNames();
if (!strList_opt) throw std::runtime_error("Error obtaining Input tensor names");
const auto &strList = *strList_opt;
// Make sure the network requires only a single input
assert (strList.size() == 1);
// If the network has a single input, each line represents the input file to be loaded for that input
std::vector<float> inputVec;
for(size_t i=0; i<fileLines.size(); i++) {
std::string filePath(fileLines[i]);
std::cout << "Processing DNN Input: " << filePath << "\n";
std::vector<float> loadedFile = loadFloatDataFile(filePath);
inputVec.insert(inputVec.end(), loadedFile.begin(), loadedFile.end());
}
/* Create an input tensor that is correctly sized to hold the input of the network. Dimensions that have no fixed size will be represented with a value of 0. */
const auto &inputDims_opt = snpe->getInputDimensions(strList.at(0));
const auto &inputShape = *inputDims_opt;
/* Calculate the total number of elements that can be stored in the tensor so that we can check that the input contains the expected number of elements.
With the input dimensions computed create a tensor to convey the input into the network. */
input = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape);
//Padding the input vector so as to make the size of the vector to equal to an integer multiple of the batch size
zdl::DlSystem::TensorShape tensorShape= snpe->getInputDimensions();
size_t batchSize = tensorShape.getDimensions()[0];
if(fileLines.size()<batchSize) {
for(size_t j=0; j<batchSize-fileLines.size(); j++) {
std::vector<float> padding(input->getSize()/batchSize,0);
inputVec.insert(inputVec.end(),padding.begin(),padding.end());
}
}
if (input->getSize() != inputVec.size()) {
std::cerr << "Size of input does not match network.\n"
<< "Expecting: " << input->getSize() << "\n"
<< "Got: " << inputVec.size() << "\n";
return nullptr;
}
/* Copy the loaded input file contents into the networks input tensor. SNPE's ITensor supports C++ STL functions like std::copy() */
std::copy(inputVec.begin(), inputVec.end(), input->begin());
return input;
}
// Load multiple input tensors for a network which require multiple inputs
std::tuple<zdl::DlSystem::TensorMap, bool> loadMultipleInput (std::unique_ptr<zdl::SNPE::SNPE>& snpe , std::vector<std::string>& fileLines)
{
zdl::DlSystem::TensorMap dummy; // dummy map for returning on failure
const auto& inputTensorNamesRef = snpe->getInputTensorNames();
if (!inputTensorNamesRef) throw std::runtime_error("Error obtaining Input tensor names");
const auto &inputTensorNames = *inputTensorNamesRef;
// Make sure the network requires multiple inputs
assert (inputTensorNames.size() > 1);
if (inputTensorNames.size()) std::cout << "Processing DNN Input: " << std::endl;
std::vector<std::unique_ptr<zdl::DlSystem::ITensor>> inputs(inputTensorNames.size());
zdl::DlSystem::TensorMap inputTensorMap;
for(size_t i=0; i<fileLines.size(); i++) {
std::string fileLine(fileLines[i]);
// Treat each line as a space-separated list of input files
std::vector<std::string> filePaths;
split(filePaths, fileLine, ' ');
for (size_t j = 0; j<inputTensorNames.size(); j++) {
// print out which file is being processed
std::string filePath(filePaths[j]);
std::cout << "\t" << j + 1 << ") " << filePath << std::endl;
std::string inputName(inputTensorNames.at(j));
std::vector<float> inputVec = loadFloatDataFile(filePath);
const auto &inputShape_opt = snpe->getInputDimensions(inputTensorNames.at(j));
const auto &inputShape = *inputShape_opt;
inputs[j] = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape);
if (inputs[j]->getSize() != inputVec.size()) {
std::cerr << "Size of input does not match network.\n"
<< "Expecting: " << inputs[j]->getSize() << "\n"
<< "Got: " << inputVec.size() << "\n";
return std::make_tuple(dummy, false);
}
std::copy(inputVec.begin(), inputVec.end(), inputs[j]->begin());
inputTensorMap.add(inputName.c_str(), inputs[j].release());
}
}
std::cout << "Finished processing inputs for current inference \n";
return std::make_tuple(inputTensorMap, true);
}
bool loadInputUserBufferTf8(std::unordered_map<std::string, std::vector<uint8_t>>& applicationBuffers,
std::unique_ptr<zdl::SNPE::SNPE>& snpe,
std::vector<std::string>& fileLines,
zdl::DlSystem::UserBufferMap& inputMap)
{
// get input tensor names of the network that need to be populated
const auto& inputNamesOpt = snpe->getInputTensorNames();
if (!inputNamesOpt) throw std::runtime_error("Error obtaining input tensor names");
const zdl::DlSystem::StringList& inputNames = *inputNamesOpt;
assert(inputNames.size() > 0);
if (inputNames.size()) std::cout << "Processing DNN Input: " << std::endl;
for(size_t i=0; i<fileLines.size(); i++) {
std::string fileLine(fileLines[i]);
// treat each line as a space-separated list of input files
std::vector<std::string> filePaths;
split(filePaths, fileLine, ' ');
for (size_t j = 0; j < inputNames.size(); j++) {
const char *name = inputNames.at(j);
std::string filePath(filePaths[j]);
// print out which file is being processed
std::cout << "\t" << j + 1 << ") " << filePath << std::endl;
// load file content onto application storage buffer,
// on top of which, SNPE has created a user buffer
unsigned char stepEquivalentTo0;
float quantizedStepSize;
if(!loadByteDataFileBatchedTf8(filePath, applicationBuffers.at(name), i, stepEquivalentTo0, quantizedStepSize))
{
return false;
}
auto userBufferEncoding = dynamic_cast<zdl::DlSystem::UserBufferEncodingTf8 *>(&inputMap.getUserBuffer(name)->getEncoding());
userBufferEncoding->setStepExactly0(stepEquivalentTo0);
userBufferEncoding->setQuantizedStepSize(quantizedStepSize);
}
}
return true;
}
// Load multiple batched input user buffers
bool loadInputUserBufferFloat(std::unordered_map<std::string, std::vector<uint8_t>>& applicationBuffers,
std::unique_ptr<zdl::SNPE::SNPE>& snpe,
std::vector<std::string>& fileLines)
{
// get input tensor names of the network that need to be populated
const auto& inputNamesOpt = snpe->getInputTensorNames();
if (!inputNamesOpt) throw std::runtime_error("Error obtaining input tensor names");
const zdl::DlSystem::StringList& inputNames = *inputNamesOpt;
assert(inputNames.size() > 0);
if (inputNames.size()) std::cout << "Processing DNN Input: " << std::endl;
for(size_t i=0; i<fileLines.size(); i++) {
std::string fileLine(fileLines[i]);
// treat each line as a space-separated list of input files
std::vector<std::string> filePaths;
split(filePaths, fileLine, ' ');
for (size_t j = 0; j < inputNames.size(); j++) {
const char *name = inputNames.at(j);
std::string filePath(filePaths[j]);
// print out which file is being processed
std::cout << "\t" << j + 1 << ") " << filePath << std::endl;
// load file content onto application storage buffer,
// on top of which, SNPE has created a user buffer
if(!loadByteDataFileBatched(filePath, applicationBuffers.at(name), i))
{
return false;
}
}
}
return true;
}
void loadInputUserBuffer(std::unordered_map<std::string, GLuint>& applicationBuffers,
std::unique_ptr<zdl::SNPE::SNPE>& snpe,
const GLuint inputglbuffer)
{
// get input tensor names of the network that need to be populated
const auto& inputNamesOpt = snpe->getInputTensorNames();
if (!inputNamesOpt) throw std::runtime_error("Error obtaining input tensor names");
const zdl::DlSystem::StringList& inputNames = *inputNamesOpt;
assert(inputNames.size() > 0);
for (size_t i = 0; i < inputNames.size(); i++) {
const char* name = inputNames.at(i);
applicationBuffers.at(name) = inputglbuffer;
};
}
| 45.862687 | 164 | 0.648139 | [
"vector"
] |
82ead6890c728bfeb5987183063211eec19d1efc | 3,535 | cpp | C++ | shader.cpp | bannid/CardGame | c5df2adb7a96df506fa24544cd8499076bb3ebbc | [
"Zlib"
] | null | null | null | shader.cpp | bannid/CardGame | c5df2adb7a96df506fa24544cd8499076bb3ebbc | [
"Zlib"
] | null | null | null | shader.cpp | bannid/CardGame | c5df2adb7a96df506fa24544cd8499076bb3ebbc | [
"Zlib"
] | null | null | null | #include "shader.h"
void AttachShader(Shader * shader) {
Assert(shader->compiledAndLinked);
glUseProgram(shader->program);
}
void SetIntShader(Shader * shader, const char * name, int value){
AttachShader(shader);
glUniform1i(glGetUniformLocation(shader->program, name), value);
}
void SetBoolShader(Shader * shader, const char * name, bool value){
AttachShader(shader);
glUniform1i(glGetUniformLocation(shader->program, name), value);
}
void SetFloatShader(Shader * shader, const char * name, float value){
AttachShader(shader);
glUniform1f(glGetUniformLocation(shader->program, name), value);
}
void SetVec3Shader(Shader * shader, const char * name, glm::vec3 vector){
AttachShader(shader);
glUniform3fv(glGetUniformLocation(shader->program, name),
1,
glm::value_ptr(vector));
}
void SetVec4Shader(Shader * shader, const char * name, glm::vec4 vector){
AttachShader(shader);
glUniform4fv(glGetUniformLocation(shader->program, name),
1,
glm::value_ptr(vector));
}
void SetMat4Shader(Shader * shader, const char * name, glm::mat4 mat){
AttachShader(shader);
glUniformMatrix4fv(glGetUniformLocation(shader->program, name), 1, GL_FALSE, glm::value_ptr(mat));
}
bool CompileAndLinkShader(Shader * shader, const char * vertexShaderPath, const char * fragmentShaderPath, const char * shaderName){
shader->name = std::string(shaderName);
win32_file vertexShaderSource;
win32_file fragmentShaderSouce;
if (!read_entire_file(vertexShaderPath, &vertexShaderSource)){
return false;
}
if (!read_entire_file(fragmentShaderPath, &fragmentShaderSouce)){
close_file(&vertexShaderSource);
return false;
}
int success;
//Vertex shader
shader->vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(shader->vertexShader, 1,(const char**) &vertexShaderSource, NULL);
glCompileShader(shader->vertexShader);
glGetShaderiv(shader->vertexShader, GL_COMPILE_STATUS, &success);
//Check if the vertex shader compiled
if (!success){
glGetShaderInfoLog(shader->vertexShader, 512, NULL, shader->infoLog);
close_file(&vertexShaderSource);
close_file(&fragmentShaderSouce);
return false;
}
//Fragment shader
shader->fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(shader->fragmentShader, 1, (const char**) &fragmentShaderSouce, NULL);
glCompileShader(shader->fragmentShader);
glGetShaderiv(shader->fragmentShader, GL_COMPILE_STATUS, &success);
//Check if the fragment shader compiled successfully
if (!success){
glGetShaderInfoLog(shader->fragmentShader, 512, NULL, shader->infoLog);
close_file(&vertexShaderSource);
close_file(&fragmentShaderSouce);
return false;
}
//Close the files
close_file(&vertexShaderSource);
close_file(&fragmentShaderSouce);
shader->program = glCreateProgram();
glAttachShader(shader->program, shader->vertexShader);
glAttachShader(shader->program, shader->fragmentShader);
glLinkProgram(shader->program);
glGetProgramiv(shader->program, GL_LINK_STATUS, &success);
//Delete the shaders
glDeleteShader(shader->vertexShader);
glDeleteShader(shader->fragmentShader);
if (!success){
glGetProgramInfoLog(shader->program, 512, NULL, shader->infoLog);
return false;
}
shader->compiledAndLinked = true;
return true;
} | 36.443299 | 132 | 0.703536 | [
"vector"
] |
82f0c0338a6b1b57cacda10940fa034087f84960 | 9,097 | cpp | C++ | src/sort.cpp | georgebrock/task | 00204e01912aeb9e39b94ac7ba16562fdd5b5f2c | [
"MIT"
] | 1 | 2017-10-13T06:00:59.000Z | 2017-10-13T06:00:59.000Z | src/sort.cpp | georgebrock/task | 00204e01912aeb9e39b94ac7ba16562fdd5b5f2c | [
"MIT"
] | null | null | null | src/sort.cpp | georgebrock/task | 00204e01912aeb9e39b94ac7ba16562fdd5b5f2c | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <algorithm>
#include <vector>
#include <string>
#include <stdlib.h>
#include <Context.h>
#include <Duration.h>
#include <Task.h>
#include <text.h>
#include <i18n.h>
extern Context context;
static std::vector <Task>* global_data = NULL;
static std::vector <std::string> global_keys;
static bool sort_compare (int, int);
////////////////////////////////////////////////////////////////////////////////
void sort_tasks (
std::vector <Task>& data,
std::vector <int>& order,
const std::string& keys)
{
context.timer_sort.start ();
global_data = &data;
// Split the key defs.
global_keys.clear ();
split (global_keys, keys, ',');
// Only sort if necessary.
if (order.size ())
std::stable_sort (order.begin (), order.end (), sort_compare);
context.timer_sort.stop ();
}
////////////////////////////////////////////////////////////////////////////////
// Re-implementation, using direct Task access instead of data copies that
// require re-parsing.
//
// Essentially a static implementation of a dynamic operator<.
static bool sort_compare (int left, int right)
{
std::string field;
bool ascending;
Column* column;
int left_number;
int right_number;
float left_real;
float right_real;
char left_char;
char right_char;
std::vector <std::string>::iterator k;
for (k = global_keys.begin (); k != global_keys.end (); ++k)
{
context.decomposeSortField (*k, field, ascending);
// Urgency.
if (field == "urgency")
{
left_real = (*global_data)[left].urgency ();
right_real = (*global_data)[right].urgency ();
if (left_real == right_real)
continue;
return ascending ? (left_real < right_real)
: (left_real > right_real);
}
// Number.
else if (field == "id")
{
left_number = (*global_data)[left].id;
right_number = (*global_data)[right].id;
if (left_number == right_number)
continue;
return ascending ? (left_number < right_number)
: (left_number > right_number);
}
// Depends string.
else if (field == "depends")
{
// Raw data is a comma-separated list of uuids
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
if (left_string == "" && right_string != "")
return ascending;
if (left_string != "" && right_string == "")
return !ascending;
// Sort on the first dependency.
left_number = context.tdb2.id (left_string.substr (0, 36));
right_number = context.tdb2.id (right_string.substr (0, 36));
if (left_number == right_number)
continue;
return ascending ? (left_number < right_number)
: (left_number > right_number);
}
// String.
else if (field == "description" ||
field == "project" ||
field == "status" ||
field == "tags" ||
field == "uuid")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
return ascending ? (left_string < right_string)
: (left_string > right_string);
}
// Priority.
else if (field == "priority")
{
left_char = ((*global_data)[left].get (field))[0];
right_char = ((*global_data)[right].get (field))[0];
if (left_char == right_char)
continue;
if (ascending)
return (left_char == '\0' && right_char != '\0') ||
(left_char == 'L' && (right_char == 'M' || right_char == 'H')) ||
(left_char == 'M' && right_char == 'H');
return (left_char != '\0' && right_char == '\0') ||
(left_char == 'M' && right_char == 'L') ||
(left_char == 'H' && (right_char == 'M' || right_char == 'L'));
}
// Due Date.
else if (field == "due")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string != "" && right_string == "")
return true;
if (left_string == "" && right_string != "")
return false;
if (left_string == right_string)
continue;
return ascending ? (left_string < right_string)
: (left_string > right_string);
}
// Date.
else if (field == "end" ||
field == "entry" ||
field == "start" ||
field == "until" ||
field == "wait")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
return ascending ? (left_string < right_string)
: (left_string > right_string);
}
// Duration.
else if (field == "recur")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
Duration left_duration (left_string);
Duration right_duration (right_string);
return ascending ? (left_duration < right_duration)
: (left_duration > right_duration);
}
// UDAs.
else if ((column = context.columns[field]) != NULL)
{
std::string type = column->type ();
if (type == "numeric")
{
const float left_real = strtof (((*global_data)[left].get_ref (field)).c_str (), NULL);
const float right_real = strtof (((*global_data)[right].get_ref (field)).c_str (), NULL);
if (left_real == right_real)
continue;
return ascending ? (left_real < right_real)
: (left_real > right_real);
}
else if (type == "string")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
return ascending ? (left_string < right_string)
: (left_string > right_string);
}
else if (type == "date")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
return ascending ? (left_string < right_string)
: (left_string > right_string);
}
else if (type == "duration")
{
const std::string& left_string = (*global_data)[left].get_ref (field);
const std::string& right_string = (*global_data)[right].get_ref (field);
if (left_string == right_string)
continue;
Duration left_duration (left_string);
Duration right_duration (right_string);
return ascending ? (left_duration < right_duration)
: (left_duration > right_duration);
}
}
else
throw format (STRING_INVALID_SORT_COL, field);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
| 31.696864 | 97 | 0.565461 | [
"vector"
] |
82f8716776aeb7f2fc9aff98609313e06d51edf2 | 5,655 | cc | C++ | src/ufo/gnssro/QC/BackgroundCheckRONBAM.cc | fmahebert/ufo | 2af9b91433553ca473c72fcd131400a01c3aabdb | [
"Apache-2.0"
] | 1 | 2021-10-08T16:37:25.000Z | 2021-10-08T16:37:25.000Z | src/ufo/gnssro/QC/BackgroundCheckRONBAM.cc | fmahebert/ufo | 2af9b91433553ca473c72fcd131400a01c3aabdb | [
"Apache-2.0"
] | 9 | 2021-06-25T17:18:06.000Z | 2021-10-08T17:40:31.000Z | src/ufo/gnssro/QC/BackgroundCheckRONBAM.cc | fmahebert/ufo | 2af9b91433553ca473c72fcd131400a01c3aabdb | [
"Apache-2.0"
] | 31 | 2021-06-24T18:07:53.000Z | 2021-10-08T15:40:39.000Z | /*
* (C) Copyright 2017-2018 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/gnssro/QC/BackgroundCheckRONBAM.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
#include "eckit/config/Configuration.h"
#include "ioda/ObsDataVector.h"
#include "ioda/ObsSpace.h"
#include "ioda/ObsVector.h"
#include "oops/interface/ObsFilter.h"
#include "oops/util/Logger.h"
#include "ufo/filters/QCflags.h"
#include "ufo/GeoVaLs.h"
namespace ufo {
// -----------------------------------------------------------------------------
BackgroundCheckRONBAM::BackgroundCheckRONBAM(ioda::ObsSpace & obsdb,
const eckit::Configuration & config,
std::shared_ptr<ioda::ObsDataVector<int> > flags,
std::shared_ptr<ioda::ObsDataVector<float> > obserr)
: FilterBase(obsdb, config, flags, obserr)
{
oops::Log::trace() << "BackgroundCheckRONBAM contructor: "
<< "using NBAM style BackgroundCheck for GnssroBndNBAM" << std::endl;
oops::Log::debug() << "BackgroundCheckRONBAM: config = " << config << std::endl;
allvars_ += Variables(filtervars_, "HofX");
}
// -----------------------------------------------------------------------------
BackgroundCheckRONBAM::~BackgroundCheckRONBAM() {
oops::Log::trace() << "BackgroundCheckRONBAM destructed" << std::endl;
}
// -----------------------------------------------------------------------------
void BackgroundCheckRONBAM::applyFilter(const std::vector<bool> & apply,
const Variables & filtervars,
std::vector<std::vector<bool>> & flagged) const {
oops::Log::trace() << "BackgroundCheckRONBAM postFilter" << std::endl;
const oops::Variables observed = obsdb_.obsvariables();
const float missing = util::missingValue(missing);
oops::Log::debug() << "BackgroundCheckRONBAM flags: " << flags_;
ioda::ObsDataVector<float> obs(obsdb_, filtervars.toOopsVariables(), "ObsValue");
ioda::ObsDataVector<float> bias(obsdb_, filtervars.toOopsVariables(), "ObsBias", false);
ioda::ObsDataVector<float> impactparameter(obsdb_, "impact_parameter", "MetaData");
ioda::ObsDataVector<float> latitude(obsdb_, "latitude", "MetaData");
ioda::ObsDataVector<float> earthradius(obsdb_, "earth_radius_of_curvature",
"MetaData");
ioda::ObsDataVector<float> temperature(obsdb_, "virtual_temperature",
"MetaData"); // background virtual temperature at obs location
Variables varhofx(filtervars, "HofX");
for (size_t jv = 0; jv < filtervars.nvars(); ++jv) {
size_t iv = observed.find(filtervars.variable(jv).variable());
// H(x)
std::vector<float> hofx;
data_.get(varhofx.variable(jv), hofx);
for (size_t jobs = 0; jobs < obsdb_.nlocs(); ++jobs) {
if (apply[jobs] && (*flags_)[iv][jobs] == 0) {
size_t iobs = observed.size() * jobs + iv;
ASSERT(obs[jv][jobs] != util::missingValue(obs[jv][jobs]));
ASSERT(hofx[jobs] != util::missingValue(hofx[jobs]));
ASSERT(impactparameter[0][iobs] != util::missingValue(impactparameter[0][iobs]));
float imp = impactparameter[0][jobs]/1000.0 - earthradius[0][jobs]/1000.0;
float lat = latitude[0][jobs]*0.01745329251; // deg2rad
float tmp = temperature[0][jobs];
// Threshold for current observation
float cutoff = std::numeric_limits<float>::max();
float cutoff1 = std::numeric_limits<float>::max();
float cutoff2 = std::numeric_limits<float>::max();
float cutoff3 = std::numeric_limits<float>::max();
float cutoff4 = std::numeric_limits<float>::max();
float cutoff12 = std::numeric_limits<float>::max();
float cutoff23 = std::numeric_limits<float>::max();
float cutoff34 = std::numeric_limits<float>::max();
cutoff = 0.0;
cutoff1 = (-4.725+0.045*imp+0.005*imp*imp)*2.0/3.0;
cutoff2 = 1.5+cos(lat);
cutoff3 = 4.0/3.0;
if (tmp > 240.0) cutoff3 = ( 0.005*tmp*tmp-2.3*tmp+266.0 )*2.0/3.0;
cutoff4 = (4.0+8.0*cos(lat))*2.0/3.0;
cutoff12 = ( (36.0-imp)/2.0)*cutoff2 + ((imp-34.0)/2.0)*cutoff1;
cutoff23 = ( (11.0-imp)/2.0)*cutoff3 + ((imp-9.0)/2.0)*cutoff2;
cutoff34 = ( (6.0-imp)/2.0)*cutoff4 + ((imp-4.0)/2.0)*cutoff3;
if (imp > 36.0) cutoff = cutoff1;
if (imp <= 36.0 && imp > 34.0) cutoff = cutoff12;
if (imp <= 34.0 && imp > 11.0) cutoff = cutoff2;
if (imp <= 11.0 && imp > 9.0) cutoff = cutoff23;
if (imp <= 9.0 && imp > 6.0) cutoff = cutoff3;
if (imp <= 6.0 && imp > 4.0) cutoff = cutoff34;
if (imp <= 4.0) cutoff = cutoff4;
cutoff = 0.03*cutoff;
ASSERT(cutoff < std::numeric_limits<float>::max() && cutoff > 0.0);
// Apply bias correction
float yy = obs[jv][jobs] + bias[jv][jobs];
// NBAM style background check: if omb/o is greater than a cutoff
if (std::abs(static_cast<float>(hofx[jobs])-yy) > yy*cutoff) {
flagged[jv][jobs] = true; }
}
}
}
}
// -----------------------------------------------------------------------------
void BackgroundCheckRONBAM::print(std::ostream & os) const {
os << "BackgroundCheckRONBAM::print not yet implemented ";
}
// -----------------------------------------------------------------------------
} // namespace ufo
| 40.392857 | 99 | 0.564103 | [
"vector"
] |
82f98cb64cb4fa9236da0056c1659933bd5ba02f | 2,336 | cpp | C++ | fileoperationdialog.cpp | haraki/farman | 9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297 | [
"MIT"
] | 5 | 2018-08-19T05:45:45.000Z | 2020-10-09T09:37:57.000Z | fileoperationdialog.cpp | haraki/farman | 9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297 | [
"MIT"
] | 95 | 2018-04-26T12:13:24.000Z | 2020-05-03T08:23:56.000Z | fileoperationdialog.cpp | haraki/farman | 9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297 | [
"MIT"
] | 1 | 2018-08-19T05:46:02.000Z | 2018-08-19T05:46:02.000Z | #include <QStandardItemModel>
#include <QFileDialog>
#include "fileoperationdialog.h"
#include "ui_fileoperationdialog.h"
namespace Farman
{
FileOperationDialog::FileOperationDialog(OperationType type,
const QString& srcDirPath,
const QList<QFileInfo>& srcFileInfos,
const QString& dstDirPath,
QWidget *parent/* = Q_NULLPTR*/) :
QDialog(parent),
ui(new Ui::FileOperationDialog)
{
ui->setupUi(this);
this->setWindowTitle((type == OperationType::Copy) ? tr("Copy file(s)") : (type == OperationType::Move) ? tr("Move file(s)") : tr("Delete file(s)"));
ui->srcFolderPathLabel->setText(srcDirPath);
QStandardItemModel* model = new QStandardItemModel();
foreach(auto &fileInfo, srcFileInfos)
{
QStandardItem* item = new QStandardItem();
QString fileName = fileInfo.fileName();
if(fileInfo.isDir())
{
fileName += " <Folder>";
}
item->setText(fileName);
item->setEditable(false);
model->appendRow(item);
}
ui->srcFileNamesListView->setModel(model);
if(type == OperationType::Remove)
{
ui->dstLabel->setVisible(false);
ui->dstFolderPathEdit->setVisible(false);
ui->dstFolderPathSelectButton->setVisible(false);
}
else
{
ui->dstLabel->setVisible(true);
ui->dstFolderPathEdit->setVisible(true);
ui->dstFolderPathSelectButton->setVisible(true);
ui->dstFolderPathEdit->setText(dstDirPath);
}
}
FileOperationDialog::~FileOperationDialog()
{
delete ui;
}
QString FileOperationDialog::getDstDirPath() const
{
return ui->dstFolderPathEdit->text();
}
void FileOperationDialog::on_dstFolderPathSelectButton_clicked()
{
QString dirPath = QFileDialog::getExistingDirectory(this,
tr("Choose folder."),
getDstDirPath(),
QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly);
if(!dirPath.isEmpty())
{
ui->dstFolderPathEdit->setText(dirPath);
}
}
} // namespace Farman
| 29.56962 | 153 | 0.576199 | [
"model"
] |
82fc3a45dd3a8a29b60fddba2a7d30e76909acf0 | 3,911 | cpp | C++ | Game/OGRE/OgreMain/src/OgreResource.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/OgreMain/src/OgreResource.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/OgreMain/src/OgreResource.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://ogre.sourceforge.net/
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.
-----------------------------------------------------------------------------
*/
// Ogre includes
#include "OgreStableHeaders.h"
#include "OgreResource.h"
#include "OgreResourceManager.h"
#include "OgreLogManager.h"
namespace Ogre
{
//-----------------------------------------------------------------------
Resource::Resource(ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader)
: mCreator(creator), mName(name), mGroup(group), mHandle(handle),
mIsLoaded(false), mSize(0), mIsManual(isManual), mLoader(loader)
{
}
//-----------------------------------------------------------------------
Resource::~Resource()
{
}
//-----------------------------------------------------------------------
void Resource::load(void)
{
OGRE_LOCK_AUTO_MUTEX
if (!mIsLoaded)
{
if (mIsManual)
{
// Load from manual loader
if (mLoader)
{
mLoader->loadResource(this);
}
else
{
// Warn that this resource is not reloadable
LogManager::getSingleton().logMessage(
"WARNING: " + mCreator->getResourceType() +
" instance '" + mName + "' was defined as manually "
"loaded, but no manual loader was provided. This Resource "
"will be lost if it has to be reloaded.");
}
}
else
{
if (mGroup == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME)
{
// Derive resource group
changeGroupOwnership(
ResourceGroupManager::getSingleton()
.findGroupContainingResource(mName));
}
loadImpl();
}
// Calculate resource size
mSize = calculateSize();
// Now loaded
mIsLoaded = true;
// Notify manager
if(mCreator)
mCreator->_notifyResourceLoaded(this);
}
}
//-----------------------------------------------------------------------
void Resource::changeGroupOwnership(const String& newGroup)
{
if (mGroup != newGroup)
{
String oldGroup = mGroup;
mGroup = newGroup;
ResourceGroupManager::getSingleton()
._notifyResourceGroupChanged(oldGroup, this);
}
}
//-----------------------------------------------------------------------
void Resource::unload(void)
{
OGRE_LOCK_AUTO_MUTEX
if (mIsLoaded)
{
unloadImpl();
mIsLoaded = false;
// Notify manager
if(mCreator)
mCreator->_notifyResourceUnloaded(this);
}
}
//-----------------------------------------------------------------------
void Resource::reload(void)
{
OGRE_LOCK_AUTO_MUTEX
if (mIsLoaded)
{
unload();
load();
}
}
//-----------------------------------------------------------------------
void Resource::touch(void)
{
OGRE_LOCK_AUTO_MUTEX
// make sure loaded
load();
if(mCreator)
mCreator->_notifyResourceTouched(this);
}
//-----------------------------------------------------------------------
}
| 28.547445 | 88 | 0.56405 | [
"object"
] |
d2011b89d5edf4d573f254e1103a3ac2aa22f462 | 1,920 | cpp | C++ | 1301-1400/1301-Number of Paths with Max Score/1301-Number of Paths with Max Score.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 1301-1400/1301-Number of Paths with Max Score/1301-Number of Paths with Max Score.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 1301-1400/1301-Number of Paths with Max Score/1301-Number of Paths with Max Score.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
vector<int> pathsWithMaxScore(vector<string>& board) {
int n = board.size();
int MOD = 1e9 + 7;
vector<int> maxSum1(n), count1(n);
count1[n - 1] = 1;
for (int j = n - 2; j >= 0; --j) {
if (board[n - 1][j] == 'X') {
break;
}
else {
maxSum1[j] = maxSum1[j + 1] + board[n - 1][j] - '0';
count1[j] = 1;
}
}
for (int i = n - 2; i >= 0; --i) {
vector<int> maxSum2(n), count2(n);
if (count1[n - 1] > 0 && board[i][n - 1] != 'X') {
maxSum2[n - 1] = maxSum1[n - 1] + board[i][n - 1] - '0';
count2[n - 1] = 1;
}
for (int j = n - 2; j >= 0; --j) {
if (board[i][j] != 'X' && (count2[j + 1] || count1[j] || count1[j + 1])) {
maxSum2[j] = maxSum2[j + 1];
count2[j] = count2[j + 1];
if (maxSum1[j] > maxSum2[j]) {
maxSum2[j] = maxSum1[j];
count2[j] = count1[j];
}
else if (maxSum1[j] == maxSum2[j])
count2[j] = (count2[j] + count1[j]) % MOD;
if (maxSum1[j + 1] > maxSum2[j]) {
maxSum2[j] = maxSum1[j + 1];
count2[j] = count1[j + 1];
}
else if (maxSum1[j + 1] == maxSum2[j])
count2[j] = (count2[j] + count1[j + 1]) % MOD;
if (board[i][j] != 'E')
maxSum2[j] += board[i][j] - '0';
}
}
maxSum1 = move(maxSum2);
count1 = move(count2);
}
return {maxSum1[0], count1[0]};
}
};
| 35.555556 | 90 | 0.326563 | [
"vector"
] |
d20983c2e9b7df1a3a7aa32b3702543dfe4368a7 | 2,883 | cpp | C++ | sem_4/ded/sorting/src/collections/views/highlighter.cpp | KingCakeTheFruity/mipt | e32cfe5e53236cdd2933d8b666ca995508300f0f | [
"MIT"
] | null | null | null | sem_4/ded/sorting/src/collections/views/highlighter.cpp | KingCakeTheFruity/mipt | e32cfe5e53236cdd2933d8b666ca995508300f0f | [
"MIT"
] | null | null | null | sem_4/ded/sorting/src/collections/views/highlighter.cpp | KingCakeTheFruity/mipt | e32cfe5e53236cdd2933d8b666ca995508300f0f | [
"MIT"
] | null | null | null | #include "highlighter.h"
const double HIGHLIGHTER_ON_COEF = 0.0;
v_Highlighter::v_Highlighter(const ViewBody &body, SmartColor *color, AbstractView *parent, double highlight_coef, bool to_block_covered):
AbstractLabledView(body, parent, to_block_covered),
highlight_coef(highlight_coef),
color(color)
{
e_mouse_press.add(new HighlighterPressAcceptor(this));
e_mouse_move.add(new HighlighterMoveAcceptor(this));
e_toggle_activity.add(new HighlighterDeactivateVisualy(this));
}
v_Highlighter::v_Highlighter(const ViewBody &body, AbstractView *parent, bool to_block_covered):
AbstractLabledView(body, parent, to_block_covered),
highlight_coef(0),
color(nullptr)
{
e_mouse_press.add(new HighlighterPressAcceptor(this));
e_mouse_move.add(new HighlighterMoveAcceptor(this));
e_toggle_activity.add(new HighlighterDeactivateVisualy(this));
}
v_Highlighter::~v_Highlighter() {}
void v_Highlighter::render(Renderer *renderer) {
if (appearence) {
appearence->fit_for_size(body.size);
renderer->set_appearence(appearence);
renderer->apr_draw_rectangle(body.position, body.size);
} else if (color) {
RGBA cur_color = color->rgb();
renderer->draw_rectangle(body.position, body.size, cur_color);
}
subrender(renderer);
AbstractLabledView::render(renderer);
if (to_draw_selected_bounds && is_selected() && tab_selected) {
renderer->draw_rectangle(body.position, body.size, {0, 0, 0, 0}, {255, 0, 0, 255});
}
}
HighlighterPressAcceptor::HighlighterPressAcceptor(v_Highlighter *highlighter) : EventAcceptor(highlighter) {}
EventAccResult HighlighterPressAcceptor::operator()(const Event::MousePress &event, const EventAccResult *) {
v_Highlighter *hl = acceptor;
if (hl->is_inside(event.position)) {
hl->cursor_inside = true;
return EventAccResult::cont;
} else {
hl->cursor_inside = false;
return EventAccResult::none;
}
}
HighlighterMoveAcceptor::HighlighterMoveAcceptor(v_Highlighter *highlighter) : EventAcceptor(highlighter) {}
EventAccResult HighlighterMoveAcceptor::operator()(const Event::MouseMove &event, const EventAccResult *) {
v_Highlighter *hl = acceptor;
if (hl->is_inside(event.to, event.from)) {
hl->cursor_inside = hl->is_inside(event.to);
return EventAccResult::cont;
} else {
return EventAccResult::none;
}
}
HighlighterDeactivateVisualy::HighlighterDeactivateVisualy(v_Highlighter *highlighter) : EventAcceptor(highlighter) {}
EventAccResult HighlighterDeactivateVisualy::operator()(const Event::ActivityToggle &event, const EventAccResult *) {
v_Highlighter *hl = acceptor;
if ((event.mode & Event::ActivityToggle::State::visualy) && (event.mode & Event::ActivityToggle::State::off)) {
hl->cursor_inside = false;
}
return EventAccResult::none;
}
| 33.523256 | 138 | 0.730489 | [
"render"
] |
d211fa4762e5bc65900b959304dfc375561bf172 | 668 | hpp | C++ | src/Hangman.hpp | ClemThierry/POO_S4 | 9628fe68417b21fdcbea7870a5b300c7780d929b | [
"MIT"
] | null | null | null | src/Hangman.hpp | ClemThierry/POO_S4 | 9628fe68417b21fdcbea7870a5b300c7780d929b | [
"MIT"
] | 2 | 2022-03-22T19:29:33.000Z | 2022-03-23T13:21:39.000Z | src/Hangman.hpp | ClemThierry/POO_S4 | 9628fe68417b21fdcbea7870a5b300c7780d929b | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
void hangmanGame();
std::string chooseRandomWord();
char askLetterToThePlayer();
bool isWordFound(const std::string& playerWord);
bool isPlayerAlive(const int livesOfPlayer);
bool isTheLetterInTheWord(char letterChooseByPlayer, const std::string& wordToGuess);
void findAllOccurances(std::vector<size_t>& vec, const char letterChooseByPlayer, const std::string wordToGuess);
std::string updateGuessedWord(const char letterChooseByPlayer, const std::string& wordToGuess, std::string& wordGuessed);
void endGameAnnounce(const int livesOfPlayer); | 47.714286 | 121 | 0.751497 | [
"vector"
] |
d21538308f42b2ce8b53117292bad31bb7e88e6d | 1,579 | cpp | C++ | aws-cpp-sdk-iotevents-data/source/model/SystemEvent.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-iotevents-data/source/model/SystemEvent.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-iotevents-data/source/model/SystemEvent.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotevents-data/model/SystemEvent.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace IoTEventsData
{
namespace Model
{
SystemEvent::SystemEvent() :
m_eventType(EventType::NOT_SET),
m_eventTypeHasBeenSet(false),
m_stateChangeConfigurationHasBeenSet(false)
{
}
SystemEvent::SystemEvent(JsonView jsonValue) :
m_eventType(EventType::NOT_SET),
m_eventTypeHasBeenSet(false),
m_stateChangeConfigurationHasBeenSet(false)
{
*this = jsonValue;
}
SystemEvent& SystemEvent::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("eventType"))
{
m_eventType = EventTypeMapper::GetEventTypeForName(jsonValue.GetString("eventType"));
m_eventTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("stateChangeConfiguration"))
{
m_stateChangeConfiguration = jsonValue.GetObject("stateChangeConfiguration");
m_stateChangeConfigurationHasBeenSet = true;
}
return *this;
}
JsonValue SystemEvent::Jsonize() const
{
JsonValue payload;
if(m_eventTypeHasBeenSet)
{
payload.WithString("eventType", EventTypeMapper::GetNameForEventType(m_eventType));
}
if(m_stateChangeConfigurationHasBeenSet)
{
payload.WithObject("stateChangeConfiguration", m_stateChangeConfiguration.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace IoTEventsData
} // namespace Aws
| 20.776316 | 89 | 0.751108 | [
"model"
] |
d21e9b20d910a8c459c31c98617a919ec5700fbd | 78,733 | cxx | C++ | main/vcl/source/gdi/outdev.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/vcl/source/gdi/outdev.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/vcl/source/gdi/outdev.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <tools/ref.hxx>
#include <tools/debug.hxx>
#include <tools/poly.hxx>
#include <vcl/svapp.hxx>
#include <vcl/ctrl.hxx>
#include <vcl/region.hxx>
#include <vcl/virdev.hxx>
#include <vcl/window.hxx>
#include <vcl/metaact.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/print.hxx>
#include <vcl/outdev.hxx>
#include <vcl/unowrap.hxx>
// declare system types in sysdata.hxx
#include <svsys.h>
#include <vcl/sysdata.hxx>
#include <salgdi.hxx>
#include <sallayout.hxx>
#include <salframe.hxx>
#include <salvd.hxx>
#include <salprn.hxx>
#include <svdata.hxx>
#include <window.h>
#include <outdev.h>
#include <outdata.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dlinegeometry.hxx>
#include <com/sun/star/awt/XGraphics.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <vcl/unohelp.hxx>
#include <numeric>
using namespace ::com::sun::star;
DBG_NAME( OutputDevice )
DBG_NAME( Polygon )
DBG_NAME( PolyPolygon )
DBG_NAMEEX( Region )
// -----------------------------------------------------------------------
#ifdef DBG_UTIL
const char* ImplDbgCheckOutputDevice( const void* pObj )
{
DBG_TESTSOLARMUTEX();
const OutputDevice* pOutDev = (OutputDevice*)pObj;
if ( (pOutDev->GetOutDevType() != OUTDEV_DONTKNOW) &&
(pOutDev->GetOutDevType() != OUTDEV_WINDOW) &&
(pOutDev->GetOutDevType() != OUTDEV_PRINTER) &&
(pOutDev->GetOutDevType() != OUTDEV_VIRDEV) )
return "OutputDevice data overwrite";
return NULL;
}
#endif
// =======================================================================
#define OUTDEV_POLYPOLY_STACKBUF 32
// =======================================================================
struct ImplObjStack
{
ImplObjStack* mpPrev;
MapMode* mpMapMode;
bool mbMapActive;
Region* mpClipRegion;
Color* mpLineColor;
Color* mpFillColor;
Font* mpFont;
Color* mpTextColor;
Color* mpTextFillColor;
Color* mpTextLineColor;
Color* mpOverlineColor;
Point* mpRefPoint;
TextAlign meTextAlign;
RasterOp meRasterOp;
sal_uLong mnTextLayoutMode;
LanguageType meTextLanguage;
sal_uInt16 mnFlags;
};
// -----------------------------------------------------------------------
static void ImplDeleteObjStack( ImplObjStack* pObjStack )
{
if ( pObjStack->mnFlags & PUSH_LINECOLOR )
{
if ( pObjStack->mpLineColor )
delete pObjStack->mpLineColor;
}
if ( pObjStack->mnFlags & PUSH_FILLCOLOR )
{
if ( pObjStack->mpFillColor )
delete pObjStack->mpFillColor;
}
if ( pObjStack->mnFlags & PUSH_FONT )
delete pObjStack->mpFont;
if ( pObjStack->mnFlags & PUSH_TEXTCOLOR )
delete pObjStack->mpTextColor;
if ( pObjStack->mnFlags & PUSH_TEXTFILLCOLOR )
{
if ( pObjStack->mpTextFillColor )
delete pObjStack->mpTextFillColor;
}
if ( pObjStack->mnFlags & PUSH_TEXTLINECOLOR )
{
if ( pObjStack->mpTextLineColor )
delete pObjStack->mpTextLineColor;
}
if ( pObjStack->mnFlags & PUSH_OVERLINECOLOR )
{
if ( pObjStack->mpOverlineColor )
delete pObjStack->mpOverlineColor;
}
if ( pObjStack->mnFlags & PUSH_MAPMODE )
{
if ( pObjStack->mpMapMode )
delete pObjStack->mpMapMode;
}
if ( pObjStack->mnFlags & PUSH_CLIPREGION )
{
if ( pObjStack->mpClipRegion )
delete pObjStack->mpClipRegion;
}
if ( pObjStack->mnFlags & PUSH_REFPOINT )
{
if ( pObjStack->mpRefPoint )
delete pObjStack->mpRefPoint;
}
delete pObjStack;
}
// -----------------------------------------------------------------------
bool OutputDevice::ImplIsAntiparallel() const
{
bool bRet = false;
if( ImplGetGraphics() )
{
if( ( (mpGraphics->GetLayout() & SAL_LAYOUT_BIDI_RTL) && ! IsRTLEnabled() ) ||
( ! (mpGraphics->GetLayout() & SAL_LAYOUT_BIDI_RTL) && IsRTLEnabled() ) )
{
bRet = true;
}
}
return bRet;
}
// -----------------------------------------------------------------------
bool OutputDevice::ImplSelectClipRegion( const Region& rRegion, SalGraphics* pGraphics )
{
DBG_TESTSOLARMUTEX();
if( !pGraphics )
{
if( !mpGraphics )
if( !ImplGetGraphics() )
return false;
pGraphics = mpGraphics;
}
bool bClipRegion = pGraphics->SetClipRegion( rRegion, this );
OSL_ENSURE( bClipRegion, "OutputDevice::ImplSelectClipRegion() - can't cerate region" );
return bClipRegion;
}
// =======================================================================
Polygon ImplSubdivideBezier( const Polygon& rPoly )
{
Polygon aPoly;
// #100127# Use adaptive subdivide instead of fixed 25 segments
rPoly.AdaptiveSubdivide( aPoly );
return aPoly;
}
// =======================================================================
PolyPolygon ImplSubdivideBezier( const PolyPolygon& rPolyPoly )
{
sal_uInt16 i, nPolys = rPolyPoly.Count();
PolyPolygon aPolyPoly( nPolys );
for( i=0; i<nPolys; ++i )
aPolyPoly.Insert( ImplSubdivideBezier( rPolyPoly.GetObject(i) ) );
return aPolyPoly;
}
// =======================================================================
// #100127# Extracted from OutputDevice::DrawPolyPolygon()
void OutputDevice::ImplDrawPolyPolygon( sal_uInt16 nPoly, const PolyPolygon& rPolyPoly )
{
// AW: This crashes on empty PolyPolygons, avoid that
if(!nPoly)
return;
sal_uInt32 aStackAry1[OUTDEV_POLYPOLY_STACKBUF];
PCONSTSALPOINT aStackAry2[OUTDEV_POLYPOLY_STACKBUF];
sal_uInt8* aStackAry3[OUTDEV_POLYPOLY_STACKBUF];
sal_uInt32* pPointAry;
PCONSTSALPOINT* pPointAryAry;
const sal_uInt8** pFlagAryAry;
sal_uInt16 i = 0, j = 0, last = 0;
sal_Bool bHaveBezier = sal_False;
if ( nPoly > OUTDEV_POLYPOLY_STACKBUF )
{
pPointAry = new sal_uInt32[nPoly];
pPointAryAry = new PCONSTSALPOINT[nPoly];
pFlagAryAry = new const sal_uInt8*[nPoly];
}
else
{
pPointAry = aStackAry1;
pPointAryAry = aStackAry2;
pFlagAryAry = (const sal_uInt8**)aStackAry3;
}
do
{
const Polygon& rPoly = rPolyPoly.GetObject( i );
sal_uInt16 nSize = rPoly.GetSize();
if ( nSize )
{
pPointAry[j] = nSize;
pPointAryAry[j] = (PCONSTSALPOINT)rPoly.GetConstPointAry();
pFlagAryAry[j] = rPoly.GetConstFlagAry();
last = i;
if( pFlagAryAry[j] )
bHaveBezier = sal_True;
++j;
}
++i;
}
while ( i < nPoly );
if ( j == 1 )
{
// #100127# Forward beziers to sal, if any
if( bHaveBezier )
{
if( !mpGraphics->DrawPolygonBezier( *pPointAry, *pPointAryAry, *pFlagAryAry, this ) )
{
Polygon aPoly = ImplSubdivideBezier( rPolyPoly.GetObject( last ) );
mpGraphics->DrawPolygon( aPoly.GetSize(), (const SalPoint*)aPoly.GetConstPointAry(), this );
}
}
else
{
mpGraphics->DrawPolygon( *pPointAry, *pPointAryAry, this );
}
}
else
{
// #100127# Forward beziers to sal, if any
if( bHaveBezier )
{
if( !mpGraphics->DrawPolyPolygonBezier( j, pPointAry, pPointAryAry, pFlagAryAry, this ) )
{
PolyPolygon aPolyPoly = ImplSubdivideBezier( rPolyPoly );
ImplDrawPolyPolygon( aPolyPoly.Count(), aPolyPoly );
}
}
else
{
mpGraphics->DrawPolyPolygon( j, pPointAry, pPointAryAry, this );
}
}
if ( pPointAry != aStackAry1 )
{
delete[] pPointAry;
delete[] pPointAryAry;
delete[] pFlagAryAry;
}
}
// =======================================================================
OutputDevice::OutputDevice() :
maRegion(true),
maFillColor( COL_WHITE ),
maTextLineColor( COL_TRANSPARENT ),
maSettings( Application::GetSettings() )
{
DBG_CTOR( OutputDevice, ImplDbgCheckOutputDevice );
mpGraphics = NULL;
mpUnoGraphicsList = NULL;
mpPrevGraphics = NULL;
mpNextGraphics = NULL;
mpMetaFile = NULL;
mpFontEntry = NULL;
mpFontCache = NULL;
mpFontList = NULL;
mpGetDevFontList = NULL;
mpGetDevSizeList = NULL;
mpObjStack = NULL;
mpOutDevData = NULL;
mpPDFWriter = NULL;
mpAlphaVDev = NULL;
mpExtOutDevData = NULL;
mnOutOffX = 0;
mnOutOffY = 0;
mnOutWidth = 0;
mnOutHeight = 0;
mnDPIX = 0;
mnDPIY = 0;
mnTextOffX = 0;
mnTextOffY = 0;
mnOutOffOrigX = 0;
mnOutOffLogicX = 0;
mnOutOffOrigY = 0;
mnOutOffLogicY = 0;
mnEmphasisAscent = 0;
mnEmphasisDescent = 0;
mnDrawMode = 0;
mnTextLayoutMode = TEXT_LAYOUT_DEFAULT;
if( Application::GetSettings().GetLayoutRTL() ) //#i84553# tip BiDi preference to RTL
mnTextLayoutMode = TEXT_LAYOUT_BIDI_RTL | TEXT_LAYOUT_TEXTORIGIN_LEFT;
meOutDevType = OUTDEV_DONTKNOW;
meOutDevViewType = OUTDEV_VIEWTYPE_DONTKNOW;
mbMap = sal_False;
mbMapIsDefault = sal_True;
mbClipRegion = sal_False;
mbBackground = sal_False;
mbOutput = sal_True;
mbDevOutput = sal_False;
mbOutputClipped = sal_False;
maTextColor = Color( COL_BLACK );
maOverlineColor = Color( COL_TRANSPARENT );
meTextAlign = maFont.GetAlign();
meRasterOp = ROP_OVERPAINT;
mnAntialiasing = 0;
meTextLanguage = 0; // TODO: get default from configuration?
mbLineColor = sal_True;
mbFillColor = sal_True;
mbInitLineColor = sal_True;
mbInitFillColor = sal_True;
mbInitFont = sal_True;
mbInitTextColor = sal_True;
mbInitClipRegion = sal_True;
mbClipRegionSet = sal_False;
mbKerning = sal_False;
mbNewFont = sal_True;
mbTextLines = sal_False;
mbTextSpecial = sal_False;
mbRefPoint = sal_False;
mbEnableRTL = sal_False; // mirroring must be explicitly allowed (typically for windows only)
// struct ImplMapRes
maMapRes.mnMapOfsX = 0;
maMapRes.mnMapOfsY = 0;
maMapRes.mnMapScNumX = 1;
maMapRes.mnMapScNumY = 1;
maMapRes.mnMapScDenomX = 1;
maMapRes.mnMapScDenomY = 1;
// struct ImplThresholdRes
maThresRes.mnThresLogToPixX = 0;
maThresRes.mnThresLogToPixY = 0;
maThresRes.mnThresPixToLogX = 0;
maThresRes.mnThresPixToLogY = 0;
}
// -----------------------------------------------------------------------
OutputDevice::~OutputDevice()
{
DBG_DTOR( OutputDevice, ImplDbgCheckOutputDevice );
if ( GetUnoGraphicsList() )
{
UnoWrapperBase* pWrapper = Application::GetUnoWrapper( sal_False );
if ( pWrapper )
pWrapper->ReleaseAllGraphics( this );
delete mpUnoGraphicsList;
mpUnoGraphicsList = NULL;
}
if ( mpOutDevData )
ImplDeInitOutDevData();
ImplObjStack* pData = mpObjStack;
if ( pData )
{
DBG_ERRORFILE( "OutputDevice::~OutputDevice(): OutputDevice::Push() calls != OutputDevice::Pop() calls" );
while ( pData )
{
ImplObjStack* pTemp = pData;
pData = pData->mpPrev;
ImplDeleteObjStack( pTemp );
}
}
// release the active font instance
if( mpFontEntry )
mpFontCache->Release( mpFontEntry );
// remove cached results of GetDevFontList/GetDevSizeList
// TODO: use smart pointers for them
if( mpGetDevFontList )
delete mpGetDevFontList;
if( mpGetDevSizeList )
delete mpGetDevSizeList;
// release ImplFontCache specific to this OutputDevice
// TODO: refcount ImplFontCache
if( mpFontCache
&& (mpFontCache != ImplGetSVData()->maGDIData.mpScreenFontCache)
&& (ImplGetSVData()->maGDIData.mpScreenFontCache != NULL) )
{
delete mpFontCache;
mpFontCache = NULL;
}
// release ImplFontList specific to this OutputDevice
// TODO: refcount ImplFontList
if( mpFontList
&& (mpFontList != ImplGetSVData()->maGDIData.mpScreenFontList)
&& (ImplGetSVData()->maGDIData.mpScreenFontList != NULL) )
{
mpFontList->Clear();
delete mpFontList;
mpFontList = NULL;
}
delete mpAlphaVDev;
}
bool OutputDevice::supportsOperation( OutDevSupportType eType ) const
{
if( !mpGraphics )
if( !ImplGetGraphics() )
return false;
const bool bHasSupport = mpGraphics->supportsOperation( eType );
return bHasSupport;
}
// -----------------------------------------------------------------------
void OutputDevice::EnableRTL( sal_Bool bEnable )
{
mbEnableRTL = (bEnable != 0);
if( meOutDevType == OUTDEV_VIRDEV )
{
// virdevs default to not mirroring, they will only be set to mirroring
// under rare circumstances in the UI, eg the valueset control
// because each virdev has its own SalGraphics we can safely switch the SalGraphics here
// ...hopefully
if( ImplGetGraphics() )
mpGraphics->SetLayout( mbEnableRTL ? SAL_LAYOUT_BIDI_RTL : 0 );
}
// convenience: for controls also switch layout mode
if( dynamic_cast<Control*>(this) != 0 )
SetLayoutMode( bEnable ? TEXT_LAYOUT_BIDI_RTL | TEXT_LAYOUT_TEXTORIGIN_LEFT : TEXT_LAYOUT_BIDI_LTR | TEXT_LAYOUT_TEXTORIGIN_LEFT);
Window* pWin = dynamic_cast<Window*>(this);
if( pWin )
pWin->StateChanged( STATE_CHANGE_MIRRORING );
if( mpAlphaVDev )
mpAlphaVDev->EnableRTL( bEnable );
}
sal_Bool OutputDevice::ImplHasMirroredGraphics()
{
// HOTFIX for #i55719#
if( meOutDevType == OUTDEV_PRINTER )
return sal_False;
return ( ImplGetGraphics() && (mpGraphics->GetLayout() & SAL_LAYOUT_BIDI_RTL) );
}
// note: the coordiantes to be remirrored are in frame coordiantes !
void OutputDevice::ImplReMirror( Point &rPoint ) const
{
rPoint.X() = mnOutOffX + mnOutWidth - 1 - rPoint.X() + mnOutOffX;
}
void OutputDevice::ImplReMirror( Rectangle &rRect ) const
{
long nWidth = rRect.nRight - rRect.nLeft;
//long lc_x = rRect.nLeft - mnOutOffX; // normalize
//lc_x = mnOutWidth - nWidth - 1 - lc_x; // mirror
//rRect.nLeft = lc_x + mnOutOffX; // re-normalize
rRect.nLeft = mnOutOffX + mnOutWidth - nWidth - 1 - rRect.nLeft + mnOutOffX;
rRect.nRight = rRect.nLeft + nWidth;
}
void OutputDevice::ImplReMirror( Region &rRegion ) const
{
RectangleVector aRectangles;
rRegion.GetRegionRectangles(aRectangles);
Region aMirroredRegion;
for(RectangleVector::iterator aRectIter(aRectangles.begin()); aRectIter != aRectangles.end(); aRectIter++)
{
ImplReMirror(*aRectIter);
aMirroredRegion.Union(*aRectIter);
}
rRegion = aMirroredRegion;
// long nX;
// long nY;
// long nWidth;
// long nHeight;
// ImplRegionInfo aInfo;
// sal_Bool bRegionRect;
// Region aMirroredRegion;
//
// bRegionRect = rRegion.ImplGetFirstRect( aInfo, nX, nY, nWidth, nHeight );
// while ( bRegionRect )
// {
// Rectangle aRect( Point(nX, nY), Size(nWidth, nHeight) );
// ImplReMirror( aRect );
// aMirroredRegion.Union( aRect );
// bRegionRect = rRegion.ImplGetNextRect( aInfo, nX, nY, nWidth, nHeight );
// }
// rRegion = aMirroredRegion;
}
// -----------------------------------------------------------------------
int OutputDevice::ImplGetGraphics() const
{
DBG_TESTSOLARMUTEX();
if ( mpGraphics )
return sal_True;
mbInitLineColor = sal_True;
mbInitFillColor = sal_True;
mbInitFont = sal_True;
mbInitTextColor = sal_True;
mbInitClipRegion = sal_True;
ImplSVData* pSVData = ImplGetSVData();
if ( meOutDevType == OUTDEV_WINDOW )
{
Window* pWindow = (Window*)this;
mpGraphics = pWindow->mpWindowImpl->mpFrame->GetGraphics();
// try harder if no wingraphics was available directly
if ( !mpGraphics )
{
// find another output device in the same frame
OutputDevice* pReleaseOutDev = pSVData->maGDIData.mpLastWinGraphics;
while ( pReleaseOutDev )
{
if ( ((Window*)pReleaseOutDev)->mpWindowImpl->mpFrame == pWindow->mpWindowImpl->mpFrame )
break;
pReleaseOutDev = pReleaseOutDev->mpPrevGraphics;
}
if ( pReleaseOutDev )
{
// steal the wingraphics from the other outdev
mpGraphics = pReleaseOutDev->mpGraphics;
pReleaseOutDev->ImplReleaseGraphics( sal_False );
}
else
{
// if needed retry after releasing least recently used wingraphics
while ( !mpGraphics )
{
if ( !pSVData->maGDIData.mpLastWinGraphics )
break;
pSVData->maGDIData.mpLastWinGraphics->ImplReleaseGraphics();
mpGraphics = pWindow->mpWindowImpl->mpFrame->GetGraphics();
}
}
}
// update global LRU list of wingraphics
if ( mpGraphics )
{
mpNextGraphics = pSVData->maGDIData.mpFirstWinGraphics;
pSVData->maGDIData.mpFirstWinGraphics = const_cast<OutputDevice*>(this);
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = const_cast<OutputDevice*>(this);
if ( !pSVData->maGDIData.mpLastWinGraphics )
pSVData->maGDIData.mpLastWinGraphics = const_cast<OutputDevice*>(this);
}
}
else if ( meOutDevType == OUTDEV_VIRDEV )
{
const VirtualDevice* pVirDev = (const VirtualDevice*)this;
if ( pVirDev->mpVirDev )
{
mpGraphics = pVirDev->mpVirDev->GetGraphics();
// if needed retry after releasing least recently used virtual device graphics
while ( !mpGraphics )
{
if ( !pSVData->maGDIData.mpLastVirGraphics )
break;
pSVData->maGDIData.mpLastVirGraphics->ImplReleaseGraphics();
mpGraphics = pVirDev->mpVirDev->GetGraphics();
}
// update global LRU list of virtual device graphics
if ( mpGraphics )
{
mpNextGraphics = pSVData->maGDIData.mpFirstVirGraphics;
pSVData->maGDIData.mpFirstVirGraphics = const_cast<OutputDevice*>(this);
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = const_cast<OutputDevice*>(this);
if ( !pSVData->maGDIData.mpLastVirGraphics )
pSVData->maGDIData.mpLastVirGraphics = const_cast<OutputDevice*>(this);
}
}
}
else if ( meOutDevType == OUTDEV_PRINTER )
{
const Printer* pPrinter = (const Printer*)this;
if ( pPrinter->mpJobGraphics )
mpGraphics = pPrinter->mpJobGraphics;
else if ( pPrinter->mpDisplayDev )
{
const VirtualDevice* pVirDev = pPrinter->mpDisplayDev;
mpGraphics = pVirDev->mpVirDev->GetGraphics();
// if needed retry after releasing least recently used virtual device graphics
while ( !mpGraphics )
{
if ( !pSVData->maGDIData.mpLastVirGraphics )
break;
pSVData->maGDIData.mpLastVirGraphics->ImplReleaseGraphics();
mpGraphics = pVirDev->mpVirDev->GetGraphics();
}
// update global LRU list of virtual device graphics
if ( mpGraphics )
{
mpNextGraphics = pSVData->maGDIData.mpFirstVirGraphics;
pSVData->maGDIData.mpFirstVirGraphics = const_cast<OutputDevice*>(this);
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = const_cast<OutputDevice*>(this);
if ( !pSVData->maGDIData.mpLastVirGraphics )
pSVData->maGDIData.mpLastVirGraphics = const_cast<OutputDevice*>(this);
}
}
else
{
mpGraphics = pPrinter->mpInfoPrinter->GetGraphics();
// if needed retry after releasing least recently used printer graphics
while ( !mpGraphics )
{
if ( !pSVData->maGDIData.mpLastPrnGraphics )
break;
pSVData->maGDIData.mpLastPrnGraphics->ImplReleaseGraphics();
mpGraphics = pPrinter->mpInfoPrinter->GetGraphics();
}
// update global LRU list of printer graphics
if ( mpGraphics )
{
mpNextGraphics = pSVData->maGDIData.mpFirstPrnGraphics;
pSVData->maGDIData.mpFirstPrnGraphics = const_cast<OutputDevice*>(this);
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = const_cast<OutputDevice*>(this);
if ( !pSVData->maGDIData.mpLastPrnGraphics )
pSVData->maGDIData.mpLastPrnGraphics = const_cast<OutputDevice*>(this);
}
}
}
if ( mpGraphics )
{
mpGraphics->SetXORMode( (ROP_INVERT == meRasterOp) || (ROP_XOR == meRasterOp), ROP_INVERT == meRasterOp );
mpGraphics->setAntiAliasB2DDraw(mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW);
return sal_True;
}
return sal_False;
}
// -----------------------------------------------------------------------
void OutputDevice::ImplReleaseGraphics( sal_Bool bRelease )
{
DBG_TESTSOLARMUTEX();
if ( !mpGraphics )
return;
// release the fonts of the physically released graphics device
if( bRelease )
{
#ifndef UNX
// HACK to fix an urgent P1 printing issue fast
// WinSalPrinter does not respect GetGraphics/ReleaseGraphics conventions
// so Printer::mpGraphics often points to a dead WinSalGraphics
// TODO: fix WinSalPrinter's GetGraphics/ReleaseGraphics handling
if( meOutDevType != OUTDEV_PRINTER )
#endif
mpGraphics->ReleaseFonts();
mbNewFont = true;
mbInitFont = true;
if ( mpFontEntry )
{
mpFontCache->Release( mpFontEntry );
mpFontEntry = NULL;
}
if ( mpGetDevFontList )
{
delete mpGetDevFontList;
mpGetDevFontList = NULL;
}
if ( mpGetDevSizeList )
{
delete mpGetDevSizeList;
mpGetDevSizeList = NULL;
}
}
ImplSVData* pSVData = ImplGetSVData();
if ( meOutDevType == OUTDEV_WINDOW )
{
Window* pWindow = (Window*)this;
if ( bRelease )
pWindow->mpWindowImpl->mpFrame->ReleaseGraphics( mpGraphics );
// remove from global LRU list of window graphics
if ( mpPrevGraphics )
mpPrevGraphics->mpNextGraphics = mpNextGraphics;
else
pSVData->maGDIData.mpFirstWinGraphics = mpNextGraphics;
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = mpPrevGraphics;
else
pSVData->maGDIData.mpLastWinGraphics = mpPrevGraphics;
}
else if ( meOutDevType == OUTDEV_VIRDEV )
{
VirtualDevice* pVirDev = (VirtualDevice*)this;
if ( bRelease )
pVirDev->mpVirDev->ReleaseGraphics( mpGraphics );
// remove from global LRU list of virtual device graphics
if ( mpPrevGraphics )
mpPrevGraphics->mpNextGraphics = mpNextGraphics;
else
pSVData->maGDIData.mpFirstVirGraphics = mpNextGraphics;
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = mpPrevGraphics;
else
pSVData->maGDIData.mpLastVirGraphics = mpPrevGraphics;
}
else if ( meOutDevType == OUTDEV_PRINTER )
{
Printer* pPrinter = (Printer*)this;
if ( !pPrinter->mpJobGraphics )
{
if ( pPrinter->mpDisplayDev )
{
VirtualDevice* pVirDev = pPrinter->mpDisplayDev;
if ( bRelease )
pVirDev->mpVirDev->ReleaseGraphics( mpGraphics );
// remove from global LRU list of virtual device graphics
if ( mpPrevGraphics )
mpPrevGraphics->mpNextGraphics = mpNextGraphics;
else
pSVData->maGDIData.mpFirstVirGraphics = mpNextGraphics;
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = mpPrevGraphics;
else
pSVData->maGDIData.mpLastVirGraphics = mpPrevGraphics;
}
else
{
if ( bRelease )
pPrinter->mpInfoPrinter->ReleaseGraphics( mpGraphics );
// remove from global LRU list of printer graphics
if ( mpPrevGraphics )
mpPrevGraphics->mpNextGraphics = mpNextGraphics;
else
pSVData->maGDIData.mpFirstPrnGraphics = mpNextGraphics;
if ( mpNextGraphics )
mpNextGraphics->mpPrevGraphics = mpPrevGraphics;
else
pSVData->maGDIData.mpLastPrnGraphics = mpPrevGraphics;
}
}
}
mpGraphics = NULL;
mpPrevGraphics = NULL;
mpNextGraphics = NULL;
}
// -----------------------------------------------------------------------
void OutputDevice::ImplInitOutDevData()
{
if ( !mpOutDevData )
{
mpOutDevData = new ImplOutDevData;
mpOutDevData->mpRotateDev = NULL;
mpOutDevData->mpRecordLayout = NULL;
// #i75163#
mpOutDevData->mpViewTransform = NULL;
mpOutDevData->mpInverseViewTransform = NULL;
}
}
// -----------------------------------------------------------------------
// #i75163#
void OutputDevice::ImplInvalidateViewTransform()
{
if(mpOutDevData)
{
if(mpOutDevData->mpViewTransform)
{
delete mpOutDevData->mpViewTransform;
mpOutDevData->mpViewTransform = NULL;
}
if(mpOutDevData->mpInverseViewTransform)
{
delete mpOutDevData->mpInverseViewTransform;
mpOutDevData->mpInverseViewTransform = NULL;
}
}
}
// -----------------------------------------------------------------------
sal_Bool OutputDevice::ImplIsRecordLayout() const
{
return mpOutDevData && mpOutDevData->mpRecordLayout;
}
// -----------------------------------------------------------------------
void OutputDevice::ImplDeInitOutDevData()
{
if ( mpOutDevData )
{
if ( mpOutDevData->mpRotateDev )
delete mpOutDevData->mpRotateDev;
// #i75163#
ImplInvalidateViewTransform();
delete mpOutDevData;
}
}
// -----------------------------------------------------------------------
void OutputDevice::ImplInitLineColor()
{
DBG_TESTSOLARMUTEX();
if( mbLineColor )
{
if( ROP_0 == meRasterOp )
mpGraphics->SetROPLineColor( SAL_ROP_0 );
else if( ROP_1 == meRasterOp )
mpGraphics->SetROPLineColor( SAL_ROP_1 );
else if( ROP_INVERT == meRasterOp )
mpGraphics->SetROPLineColor( SAL_ROP_INVERT );
else
mpGraphics->SetLineColor( ImplColorToSal( maLineColor ) );
}
else
mpGraphics->SetLineColor();
mbInitLineColor = sal_False;
}
// -----------------------------------------------------------------------
void OutputDevice::ImplInitFillColor()
{
DBG_TESTSOLARMUTEX();
if( mbFillColor )
{
if( ROP_0 == meRasterOp )
mpGraphics->SetROPFillColor( SAL_ROP_0 );
else if( ROP_1 == meRasterOp )
mpGraphics->SetROPFillColor( SAL_ROP_1 );
else if( ROP_INVERT == meRasterOp )
mpGraphics->SetROPFillColor( SAL_ROP_INVERT );
else
mpGraphics->SetFillColor( ImplColorToSal( maFillColor ) );
}
else
mpGraphics->SetFillColor();
mbInitFillColor = sal_False;
}
// -----------------------------------------------------------------------
void OutputDevice::ImplInitClipRegion()
{
DBG_TESTSOLARMUTEX();
if ( GetOutDevType() == OUTDEV_WINDOW )
{
Window* pWindow = (Window*)this;
Region aRegion;
// Hintergrund-Sicherung zuruecksetzen
if ( pWindow->mpWindowImpl->mpFrameData->mpFirstBackWin )
pWindow->ImplInvalidateAllOverlapBackgrounds();
if ( pWindow->mpWindowImpl->mbInPaint )
aRegion = *(pWindow->mpWindowImpl->mpPaintRegion);
else
{
aRegion = *(pWindow->ImplGetWinChildClipRegion());
// --- RTL -- only this region is in frame coordinates, so re-mirror it
// the mpWindowImpl->mpPaintRegion above is already correct (see ImplCallPaint()) !
if( ImplIsAntiparallel() )
ImplReMirror ( aRegion );
}
if ( mbClipRegion )
aRegion.Intersect( ImplPixelToDevicePixel( maRegion ) );
if ( aRegion.IsEmpty() )
mbOutputClipped = sal_True;
else
{
mbOutputClipped = sal_False;
ImplSelectClipRegion( aRegion );
}
mbClipRegionSet = sal_True;
}
else
{
if ( mbClipRegion )
{
if ( maRegion.IsEmpty() )
mbOutputClipped = sal_True;
else
{
mbOutputClipped = sal_False;
// #102532# Respect output offset also for clip region
Region aRegion( ImplPixelToDevicePixel( maRegion ) );
const bool bClipDeviceBounds( ! GetPDFWriter()
&& GetOutDevType() != OUTDEV_PRINTER );
if( bClipDeviceBounds )
{
// #b6520266# Perform actual rect clip against outdev
// dimensions, to generate empty clips whenever one of the
// values is completely off the device.
Rectangle aDeviceBounds( mnOutOffX, mnOutOffY,
mnOutOffX+GetOutputWidthPixel()-1,
mnOutOffY+GetOutputHeightPixel()-1 );
aRegion.Intersect( aDeviceBounds );
}
if ( aRegion.IsEmpty() )
{
mbOutputClipped = sal_True;
}
else
{
mbOutputClipped = sal_False;
ImplSelectClipRegion( aRegion );
}
}
mbClipRegionSet = sal_True;
}
else
{
if ( mbClipRegionSet )
{
mpGraphics->ResetClipRegion();
mbClipRegionSet = sal_False;
}
mbOutputClipped = sal_False;
}
}
mbInitClipRegion = sal_False;
}
// -----------------------------------------------------------------------
void OutputDevice::ImplSetClipRegion( const Region* pRegion )
{
DBG_TESTSOLARMUTEX();
if ( !pRegion )
{
if ( mbClipRegion )
{
maRegion = Region(true);
mbClipRegion = sal_False;
mbInitClipRegion = sal_True;
}
}
else
{
maRegion = *pRegion;
mbClipRegion = sal_True;
mbInitClipRegion = sal_True;
}
}
// -----------------------------------------------------------------------
void OutputDevice::SetClipRegion()
{
DBG_TRACE( "OutputDevice::SetClipRegion()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaClipRegionAction( Region(), sal_False ) );
ImplSetClipRegion( NULL );
if( mpAlphaVDev )
mpAlphaVDev->SetClipRegion();
}
// -----------------------------------------------------------------------
void OutputDevice::SetClipRegion( const Region& rRegion )
{
DBG_TRACE( "OutputDevice::SetClipRegion( rRegion )" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaClipRegionAction( rRegion, sal_True ) );
if ( rRegion.IsNull() )
{
ImplSetClipRegion( NULL );
}
else
{
Region aRegion = LogicToPixel( rRegion );
ImplSetClipRegion( &aRegion );
}
if( mpAlphaVDev )
mpAlphaVDev->SetClipRegion( rRegion );
}
// -----------------------------------------------------------------------
Region OutputDevice::GetClipRegion() const
{
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
return PixelToLogic( maRegion );
}
// -----------------------------------------------------------------------
Region OutputDevice::GetActiveClipRegion() const
{
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( GetOutDevType() == OUTDEV_WINDOW )
{
Region aRegion(true);
Window* pWindow = (Window*)this;
if ( pWindow->mpWindowImpl->mbInPaint )
{
aRegion = *(pWindow->mpWindowImpl->mpPaintRegion);
aRegion.Move( -mnOutOffX, -mnOutOffY );
}
if ( mbClipRegion )
aRegion.Intersect( maRegion );
return PixelToLogic( aRegion );
}
else
return GetClipRegion();
}
// -----------------------------------------------------------------------
void OutputDevice::MoveClipRegion( long nHorzMove, long nVertMove )
{
DBG_TRACE( "OutputDevice::MoveClipRegion()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mbClipRegion )
{
if( mpMetaFile )
mpMetaFile->AddAction( new MetaMoveClipRegionAction( nHorzMove, nVertMove ) );
maRegion.Move( ImplLogicWidthToDevicePixel( nHorzMove ),
ImplLogicHeightToDevicePixel( nVertMove ) );
mbInitClipRegion = sal_True;
}
if( mpAlphaVDev )
mpAlphaVDev->MoveClipRegion( nHorzMove, nVertMove );
}
// -----------------------------------------------------------------------
void OutputDevice::IntersectClipRegion( const Rectangle& rRect )
{
DBG_TRACE( "OutputDevice::IntersectClipRegion( rRect )" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaISectRectClipRegionAction( rRect ) );
Rectangle aRect = LogicToPixel( rRect );
maRegion.Intersect( aRect );
mbClipRegion = sal_True;
mbInitClipRegion = sal_True;
if( mpAlphaVDev )
mpAlphaVDev->IntersectClipRegion( rRect );
}
// -----------------------------------------------------------------------
void OutputDevice::IntersectClipRegion( const Region& rRegion )
{
DBG_TRACE( "OutputDevice::IntersectClipRegion( rRegion )" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if(!rRegion.IsNull())
{
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaISectRegionClipRegionAction( rRegion ) );
Region aRegion = LogicToPixel( rRegion );
maRegion.Intersect( aRegion );
mbClipRegion = sal_True;
mbInitClipRegion = sal_True;
}
if( mpAlphaVDev )
mpAlphaVDev->IntersectClipRegion( rRegion );
}
// -----------------------------------------------------------------------
void OutputDevice::SetDrawMode( sal_uLong nDrawMode )
{
DBG_TRACE1( "OutputDevice::SetDrawMode( %lx )", nDrawMode );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
mnDrawMode = nDrawMode;
if( mpAlphaVDev )
mpAlphaVDev->SetDrawMode( nDrawMode );
}
// -----------------------------------------------------------------------
void OutputDevice::SetRasterOp( RasterOp eRasterOp )
{
DBG_TRACE1( "OutputDevice::SetRasterOp( %d )", (int)eRasterOp );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaRasterOpAction( eRasterOp ) );
if ( meRasterOp != eRasterOp )
{
meRasterOp = eRasterOp;
mbInitLineColor = mbInitFillColor = sal_True;
if( mpGraphics || ImplGetGraphics() )
mpGraphics->SetXORMode( (ROP_INVERT == meRasterOp) || (ROP_XOR == meRasterOp), ROP_INVERT == meRasterOp );
}
if( mpAlphaVDev )
mpAlphaVDev->SetRasterOp( eRasterOp );
}
// -----------------------------------------------------------------------
void OutputDevice::SetLineColor()
{
DBG_TRACE( "OutputDevice::SetLineColor()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaLineColorAction( Color(), sal_False ) );
if ( mbLineColor )
{
mbInitLineColor = sal_True;
mbLineColor = sal_False;
maLineColor = Color( COL_TRANSPARENT );
}
if( mpAlphaVDev )
mpAlphaVDev->SetLineColor();
}
// -----------------------------------------------------------------------
void OutputDevice::SetLineColor( const Color& rColor )
{
DBG_TRACE1( "OutputDevice::SetLineColor( %lx )", rColor.GetColor() );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
Color aColor( rColor );
if( mnDrawMode & ( DRAWMODE_BLACKLINE | DRAWMODE_WHITELINE |
DRAWMODE_GRAYLINE | DRAWMODE_GHOSTEDLINE |
DRAWMODE_SETTINGSLINE ) )
{
if( !ImplIsColorTransparent( aColor ) )
{
if( mnDrawMode & DRAWMODE_BLACKLINE )
{
aColor = Color( COL_BLACK );
}
else if( mnDrawMode & DRAWMODE_WHITELINE )
{
aColor = Color( COL_WHITE );
}
else if( mnDrawMode & DRAWMODE_GRAYLINE )
{
const sal_uInt8 cLum = aColor.GetLuminance();
aColor = Color( cLum, cLum, cLum );
}
else if( mnDrawMode & DRAWMODE_SETTINGSLINE )
{
aColor = GetSettings().GetStyleSettings().GetFontColor();
}
if( mnDrawMode & DRAWMODE_GHOSTEDLINE )
{
aColor = Color( ( aColor.GetRed() >> 1 ) | 0x80,
( aColor.GetGreen() >> 1 ) | 0x80,
( aColor.GetBlue() >> 1 ) | 0x80);
}
}
}
if( mpMetaFile )
mpMetaFile->AddAction( new MetaLineColorAction( aColor, sal_True ) );
if( ImplIsColorTransparent( aColor ) )
{
if ( mbLineColor )
{
mbInitLineColor = sal_True;
mbLineColor = sal_False;
maLineColor = Color( COL_TRANSPARENT );
}
}
else
{
if( maLineColor != aColor )
{
mbInitLineColor = sal_True;
mbLineColor = sal_True;
maLineColor = aColor;
}
}
if( mpAlphaVDev )
mpAlphaVDev->SetLineColor( COL_BLACK );
}
// -----------------------------------------------------------------------
void OutputDevice::SetFillColor()
{
DBG_TRACE( "OutputDevice::SetFillColor()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaFillColorAction( Color(), sal_False ) );
if ( mbFillColor )
{
mbInitFillColor = sal_True;
mbFillColor = sal_False;
maFillColor = Color( COL_TRANSPARENT );
}
if( mpAlphaVDev )
mpAlphaVDev->SetFillColor();
}
// -----------------------------------------------------------------------
void OutputDevice::SetFillColor( const Color& rColor )
{
DBG_TRACE1( "OutputDevice::SetFillColor( %lx )", rColor.GetColor() );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
Color aColor( rColor );
if( mnDrawMode & ( DRAWMODE_BLACKFILL | DRAWMODE_WHITEFILL |
DRAWMODE_GRAYFILL | DRAWMODE_NOFILL |
DRAWMODE_GHOSTEDFILL | DRAWMODE_SETTINGSFILL ) )
{
if( !ImplIsColorTransparent( aColor ) )
{
if( mnDrawMode & DRAWMODE_BLACKFILL )
{
aColor = Color( COL_BLACK );
}
else if( mnDrawMode & DRAWMODE_WHITEFILL )
{
aColor = Color( COL_WHITE );
}
else if( mnDrawMode & DRAWMODE_GRAYFILL )
{
const sal_uInt8 cLum = aColor.GetLuminance();
aColor = Color( cLum, cLum, cLum );
}
else if( mnDrawMode & DRAWMODE_NOFILL )
{
aColor = Color( COL_TRANSPARENT );
}
else if( mnDrawMode & DRAWMODE_SETTINGSFILL )
{
aColor = GetSettings().GetStyleSettings().GetWindowColor();
}
if( mnDrawMode & DRAWMODE_GHOSTEDFILL )
{
aColor = Color( (aColor.GetRed() >> 1) | 0x80,
(aColor.GetGreen() >> 1) | 0x80,
(aColor.GetBlue() >> 1) | 0x80);
}
}
}
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaFillColorAction( aColor, sal_True ) );
if ( ImplIsColorTransparent( aColor ) )
{
if ( mbFillColor )
{
mbInitFillColor = sal_True;
mbFillColor = sal_False;
maFillColor = Color( COL_TRANSPARENT );
}
}
else
{
if ( maFillColor != aColor )
{
mbInitFillColor = sal_True;
mbFillColor = sal_True;
maFillColor = aColor;
}
}
if( mpAlphaVDev )
mpAlphaVDev->SetFillColor( COL_BLACK );
}
// -----------------------------------------------------------------------
void OutputDevice::SetBackground()
{
DBG_TRACE( "OutputDevice::SetBackground()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
maBackground = Wallpaper();
mbBackground = sal_False;
if( mpAlphaVDev )
mpAlphaVDev->SetBackground();
}
// -----------------------------------------------------------------------
void OutputDevice::SetBackground( const Wallpaper& rBackground )
{
DBG_TRACE( "OutputDevice::SetBackground( rBackground )" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
maBackground = rBackground;
if( rBackground.GetStyle() == WALLPAPER_NULL )
mbBackground = sal_False;
else
mbBackground = sal_True;
if( mpAlphaVDev )
mpAlphaVDev->SetBackground( rBackground );
}
// -----------------------------------------------------------------------
void OutputDevice::SetRefPoint()
{
DBG_TRACE( "OutputDevice::SetRefPoint()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaRefPointAction( Point(), sal_False ) );
mbRefPoint = sal_False;
maRefPoint.X() = maRefPoint.Y() = 0L;
if( mpAlphaVDev )
mpAlphaVDev->SetRefPoint();
}
// -----------------------------------------------------------------------
void OutputDevice::SetRefPoint( const Point& rRefPoint )
{
DBG_TRACE( "OutputDevice::SetRefPoint( rRefPoint )" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaRefPointAction( rRefPoint, sal_True ) );
mbRefPoint = sal_True;
maRefPoint = rRefPoint;
if( mpAlphaVDev )
mpAlphaVDev->SetRefPoint( rRefPoint );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawLine( const Point& rStartPt, const Point& rEndPt )
{
DBG_TRACE( "OutputDevice::DrawLine()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaLineAction( rStartPt, rEndPt ) );
if ( !IsDeviceOutputNecessary() || !mbLineColor || ImplIsRecordLayout() )
return;
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return;
}
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
if ( mbInitLineColor )
ImplInitLineColor();
// #i101598# support AA and snap for lines, too
if((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& IsLineColor())
{
// at least transform with double precision to device coordinates; this will
// avoid pixel snap of single, appended lines
const basegfx::B2DHomMatrix aTransform(ImplGetDeviceTransformation());
const basegfx::B2DVector aB2DLineWidth( 1.0, 1.0 );
basegfx::B2DPolygon aB2DPolyLine;
aB2DPolyLine.append(basegfx::B2DPoint(rStartPt.X(), rStartPt.Y()));
aB2DPolyLine.append(basegfx::B2DPoint(rEndPt.X(), rEndPt.Y()));
aB2DPolyLine.transform( aTransform );
if(mnAntialiasing & ANTIALIASING_PIXELSNAPHAIRLINE)
{
aB2DPolyLine = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aB2DPolyLine);
}
if( mpGraphics->DrawPolyLine( aB2DPolyLine, 0.0, aB2DLineWidth, basegfx::B2DLINEJOIN_NONE, com::sun::star::drawing::LineCap_BUTT, this))
{
return;
}
}
const Point aStartPt(ImplLogicToDevicePixel(rStartPt));
const Point aEndPt(ImplLogicToDevicePixel(rEndPt));
mpGraphics->DrawLine( aStartPt.X(), aStartPt.Y(), aEndPt.X(), aEndPt.Y(), this );
if( mpAlphaVDev )
mpAlphaVDev->DrawLine( rStartPt, rEndPt );
}
// -----------------------------------------------------------------------
void OutputDevice::impPaintLineGeometryWithEvtlExpand(
const LineInfo& rInfo,
basegfx::B2DPolyPolygon aLinePolyPolygon)
{
const bool bTryAA((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& IsLineColor());
basegfx::B2DPolyPolygon aFillPolyPolygon;
const bool bDashUsed(LINE_DASH == rInfo.GetStyle());
const bool bLineWidthUsed(rInfo.GetWidth() > 1);
if(bDashUsed && aLinePolyPolygon.count())
{
::std::vector< double > fDotDashArray;
const double fDashLen(rInfo.GetDashLen());
const double fDotLen(rInfo.GetDotLen());
const double fDistance(rInfo.GetDistance());
for(sal_uInt16 a(0); a < rInfo.GetDashCount(); a++)
{
fDotDashArray.push_back(fDashLen);
fDotDashArray.push_back(fDistance);
}
for(sal_uInt16 b(0); b < rInfo.GetDotCount(); b++)
{
fDotDashArray.push_back(fDotLen);
fDotDashArray.push_back(fDistance);
}
const double fAccumulated(::std::accumulate(fDotDashArray.begin(), fDotDashArray.end(), 0.0));
if(fAccumulated > 0.0)
{
basegfx::B2DPolyPolygon aResult;
for(sal_uInt32 c(0); c < aLinePolyPolygon.count(); c++)
{
basegfx::B2DPolyPolygon aLineTraget;
basegfx::tools::applyLineDashing(
aLinePolyPolygon.getB2DPolygon(c),
fDotDashArray,
&aLineTraget);
aResult.append(aLineTraget);
}
aLinePolyPolygon = aResult;
}
}
if(bLineWidthUsed && aLinePolyPolygon.count())
{
const double fHalfLineWidth((rInfo.GetWidth() * 0.5) + 0.5);
if(aLinePolyPolygon.areControlPointsUsed())
{
// #i110768# When area geometry has to be created, do not
// use the fallback bezier decomposition inside createAreaGeometry,
// but one that is at least as good as ImplSubdivideBezier was.
// There, Polygon::AdaptiveSubdivide was used with default parameter
// 1.0 as quality index.
aLinePolyPolygon = basegfx::tools::adaptiveSubdivideByDistance(aLinePolyPolygon, 1.0);
}
for(sal_uInt32 a(0); a < aLinePolyPolygon.count(); a++)
{
aFillPolyPolygon.append(basegfx::tools::createAreaGeometry(
aLinePolyPolygon.getB2DPolygon(a),
fHalfLineWidth,
rInfo.GetLineJoin(),
rInfo.GetLineCap()));
}
aLinePolyPolygon.clear();
}
GDIMetaFile* pOldMetaFile = mpMetaFile;
mpMetaFile = NULL;
if(aLinePolyPolygon.count())
{
for(sal_uInt32 a(0); a < aLinePolyPolygon.count(); a++)
{
const basegfx::B2DPolygon aCandidate(aLinePolyPolygon.getB2DPolygon(a));
bool bDone(false);
if(bTryAA)
{
bDone = mpGraphics->DrawPolyLine( aCandidate, 0.0, basegfx::B2DVector(1.0,1.0), basegfx::B2DLINEJOIN_NONE, com::sun::star::drawing::LineCap_BUTT, this);
}
if(!bDone)
{
const Polygon aPolygon(aCandidate);
mpGraphics->DrawPolyLine(aPolygon.GetSize(), (const SalPoint*)aPolygon.GetConstPointAry(), this);
}
}
}
if(aFillPolyPolygon.count())
{
const Color aOldLineColor( maLineColor );
const Color aOldFillColor( maFillColor );
SetLineColor();
ImplInitLineColor();
SetFillColor( aOldLineColor );
ImplInitFillColor();
bool bDone(false);
if(bTryAA)
{
bDone = mpGraphics->DrawPolyPolygon(aFillPolyPolygon, 0.0, this);
}
if(!bDone)
{
for(sal_uInt32 a(0); a < aFillPolyPolygon.count(); a++)
{
Polygon aPolygon(aFillPolyPolygon.getB2DPolygon(a));
// need to subdivide, mpGraphics->DrawPolygon ignores curves
aPolygon.AdaptiveSubdivide(aPolygon);
mpGraphics->DrawPolygon(aPolygon.GetSize(), (const SalPoint*)aPolygon.GetConstPointAry(), this);
}
}
SetFillColor( aOldFillColor );
SetLineColor( aOldLineColor );
}
mpMetaFile = pOldMetaFile;
}
// -----------------------------------------------------------------------
void OutputDevice::DrawLine( const Point& rStartPt, const Point& rEndPt,
const LineInfo& rLineInfo )
{
DBG_TRACE( "OutputDevice::DrawLine()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( rLineInfo.IsDefault() )
{
DrawLine( rStartPt, rEndPt );
return;
}
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaLineAction( rStartPt, rEndPt, rLineInfo ) );
if ( !IsDeviceOutputNecessary() || !mbLineColor || ( LINE_NONE == rLineInfo.GetStyle() ) || ImplIsRecordLayout() )
return;
if( !mpGraphics && !ImplGetGraphics() )
return;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
const Point aStartPt( ImplLogicToDevicePixel( rStartPt ) );
const Point aEndPt( ImplLogicToDevicePixel( rEndPt ) );
const LineInfo aInfo( ImplLogicToDevicePixel( rLineInfo ) );
const bool bDashUsed(LINE_DASH == aInfo.GetStyle());
const bool bLineWidthUsed(aInfo.GetWidth() > 1);
if ( mbInitLineColor )
ImplInitLineColor();
if(bDashUsed || bLineWidthUsed)
{
basegfx::B2DPolygon aLinePolygon;
aLinePolygon.append(basegfx::B2DPoint(aStartPt.X(), aStartPt.Y()));
aLinePolygon.append(basegfx::B2DPoint(aEndPt.X(), aEndPt.Y()));
impPaintLineGeometryWithEvtlExpand(aInfo, basegfx::B2DPolyPolygon(aLinePolygon));
}
else
{
mpGraphics->DrawLine( aStartPt.X(), aStartPt.Y(), aEndPt.X(), aEndPt.Y(), this );
}
if( mpAlphaVDev )
mpAlphaVDev->DrawLine( rStartPt, rEndPt, rLineInfo );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawRect( const Rectangle& rRect )
{
DBG_TRACE( "OutputDevice::DrawRect()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaRectAction( rRect ) );
if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() )
return;
Rectangle aRect( ImplLogicToDevicePixel( rRect ) );
if ( aRect.IsEmpty() )
return;
aRect.Justify();
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return;
}
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
mpGraphics->DrawRect( aRect.Left(), aRect.Top(), aRect.GetWidth(), aRect.GetHeight(), this );
if( mpAlphaVDev )
mpAlphaVDev->DrawRect( rRect );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawPolyLine( const Polygon& rPoly )
{
DBG_TRACE( "OutputDevice::DrawPolyLine()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
DBG_CHKOBJ( &rPoly, Polygon, NULL );
if( mpMetaFile )
mpMetaFile->AddAction( new MetaPolyLineAction( rPoly ) );
sal_uInt16 nPoints = rPoly.GetSize();
if ( !IsDeviceOutputNecessary() || !mbLineColor || (nPoints < 2) || ImplIsRecordLayout() )
return;
// we need a graphics
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
if ( mbInitLineColor )
ImplInitLineColor();
const bool bTryAA((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& IsLineColor());
// use b2dpolygon drawing if possible
if(bTryAA && ImpTryDrawPolyLineDirect(rPoly.getB2DPolygon()))
{
basegfx::B2DPolygon aB2DPolyLine(rPoly.getB2DPolygon());
const ::basegfx::B2DHomMatrix aTransform = ImplGetDeviceTransformation();
const ::basegfx::B2DVector aB2DLineWidth( 1.0, 1.0 );
// transform the polygon
aB2DPolyLine.transform( aTransform );
if(mnAntialiasing & ANTIALIASING_PIXELSNAPHAIRLINE)
{
aB2DPolyLine = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aB2DPolyLine);
}
if(mpGraphics->DrawPolyLine( aB2DPolyLine, 0.0, aB2DLineWidth, basegfx::B2DLINEJOIN_NONE, com::sun::star::drawing::LineCap_BUTT, this))
{
return;
}
}
Polygon aPoly = ImplLogicToDevicePixel( rPoly );
const SalPoint* pPtAry = (const SalPoint*)aPoly.GetConstPointAry();
// #100127# Forward beziers to sal, if any
if( aPoly.HasFlags() )
{
const sal_uInt8* pFlgAry = aPoly.GetConstFlagAry();
if( !mpGraphics->DrawPolyLineBezier( nPoints, pPtAry, pFlgAry, this ) )
{
aPoly = ImplSubdivideBezier(aPoly);
pPtAry = (const SalPoint*)aPoly.GetConstPointAry();
mpGraphics->DrawPolyLine( aPoly.GetSize(), pPtAry, this );
}
}
else
{
mpGraphics->DrawPolyLine( nPoints, pPtAry, this );
}
if( mpAlphaVDev )
mpAlphaVDev->DrawPolyLine( rPoly );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawPolyLine( const Polygon& rPoly, const LineInfo& rLineInfo )
{
DBG_TRACE( "OutputDevice::DrawPolyLine()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
DBG_CHKOBJ( &rPoly, Polygon, NULL );
if ( rLineInfo.IsDefault() )
{
DrawPolyLine( rPoly );
return;
}
// #i101491#
// Try direct Fallback to B2D-Version of DrawPolyLine
if((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& LINE_SOLID == rLineInfo.GetStyle())
{
DrawPolyLine( rPoly.getB2DPolygon(), (double)rLineInfo.GetWidth(), rLineInfo.GetLineJoin(), rLineInfo.GetLineCap());
return;
}
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaPolyLineAction( rPoly, rLineInfo ) );
ImpDrawPolyLineWithLineInfo(rPoly, rLineInfo);
}
void OutputDevice::ImpDrawPolyLineWithLineInfo(const Polygon& rPoly, const LineInfo& rLineInfo)
{
sal_uInt16 nPoints(rPoly.GetSize());
if ( !IsDeviceOutputNecessary() || !mbLineColor || ( nPoints < 2 ) || ( LINE_NONE == rLineInfo.GetStyle() ) || ImplIsRecordLayout() )
return;
Polygon aPoly = ImplLogicToDevicePixel( rPoly );
// #100127# LineInfo is not curve-safe, subdivide always
//
// What shall this mean? It's wrong to subdivide here when the
// polygon is a fat line. In that case, the painted geometry
// WILL be much different.
// I also have no idea how this could be related to the given ID
// which reads 'consolidate boost versions' in the task description.
// Removing.
//
//if( aPoly.HasFlags() )
//{
// aPoly = ImplSubdivideBezier( aPoly );
// nPoints = aPoly.GetSize();
//}
// we need a graphics
if ( !mpGraphics && !ImplGetGraphics() )
return;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
if ( mbInitLineColor )
ImplInitLineColor();
const LineInfo aInfo( ImplLogicToDevicePixel( rLineInfo ) );
const bool bDashUsed(LINE_DASH == aInfo.GetStyle());
const bool bLineWidthUsed(aInfo.GetWidth() > 1);
if(bDashUsed || bLineWidthUsed)
{
impPaintLineGeometryWithEvtlExpand(aInfo, basegfx::B2DPolyPolygon(aPoly.getB2DPolygon()));
}
else
{
// #100127# the subdivision HAS to be done here since only a pointer
// to an array of points is given to the DrawPolyLine method, there is
// NO way to find out there that it's a curve.
if( aPoly.HasFlags() )
{
aPoly = ImplSubdivideBezier( aPoly );
nPoints = aPoly.GetSize();
}
mpGraphics->DrawPolyLine(nPoints, (const SalPoint*)aPoly.GetConstPointAry(), this);
}
if( mpAlphaVDev )
mpAlphaVDev->DrawPolyLine( rPoly, rLineInfo );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawPolygon( const Polygon& rPoly )
{
DBG_TRACE( "OutputDevice::DrawPolygon()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
DBG_CHKOBJ( &rPoly, Polygon, NULL );
if( mpMetaFile )
mpMetaFile->AddAction( new MetaPolygonAction( rPoly ) );
sal_uInt16 nPoints = rPoly.GetSize();
if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || (nPoints < 2) || ImplIsRecordLayout() )
return;
// we need a graphics
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
// use b2dpolygon drawing if possible
if((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& (IsLineColor() || IsFillColor()))
{
const ::basegfx::B2DHomMatrix aTransform = ImplGetDeviceTransformation();
basegfx::B2DPolygon aB2DPolygon(rPoly.getB2DPolygon());
bool bSuccess(true);
// transform the polygon and ensure closed
aB2DPolygon.transform(aTransform);
aB2DPolygon.setClosed(true);
if(IsFillColor())
{
bSuccess = mpGraphics->DrawPolyPolygon(basegfx::B2DPolyPolygon(aB2DPolygon), 0.0, this);
}
if(bSuccess && IsLineColor())
{
const ::basegfx::B2DVector aB2DLineWidth( 1.0, 1.0 );
if(mnAntialiasing & ANTIALIASING_PIXELSNAPHAIRLINE)
{
aB2DPolygon = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aB2DPolygon);
}
bSuccess = mpGraphics->DrawPolyLine(
aB2DPolygon,
0.0,
aB2DLineWidth,
basegfx::B2DLINEJOIN_NONE,
com::sun::star::drawing::LineCap_BUTT,
this);
}
if(bSuccess)
{
return;
}
}
Polygon aPoly = ImplLogicToDevicePixel( rPoly );
const SalPoint* pPtAry = (const SalPoint*)aPoly.GetConstPointAry();
// #100127# Forward beziers to sal, if any
if( aPoly.HasFlags() )
{
const sal_uInt8* pFlgAry = aPoly.GetConstFlagAry();
if( !mpGraphics->DrawPolygonBezier( nPoints, pPtAry, pFlgAry, this ) )
{
aPoly = ImplSubdivideBezier(aPoly);
pPtAry = (const SalPoint*)aPoly.GetConstPointAry();
mpGraphics->DrawPolygon( aPoly.GetSize(), pPtAry, this );
}
}
else
{
mpGraphics->DrawPolygon( nPoints, pPtAry, this );
}
if( mpAlphaVDev )
mpAlphaVDev->DrawPolygon( rPoly );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawPolyPolygon( const PolyPolygon& rPolyPoly )
{
DBG_TRACE( "OutputDevice::DrawPolyPolygon()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
DBG_CHKOBJ( &rPolyPoly, PolyPolygon, NULL );
if( mpMetaFile )
mpMetaFile->AddAction( new MetaPolyPolygonAction( rPolyPoly ) );
sal_uInt16 nPoly = rPolyPoly.Count();
if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || !nPoly || ImplIsRecordLayout() )
return;
// we need a graphics
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
// use b2dpolygon drawing if possible
if((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& (IsLineColor() || IsFillColor()))
{
const ::basegfx::B2DHomMatrix aTransform = ImplGetDeviceTransformation();
basegfx::B2DPolyPolygon aB2DPolyPolygon(rPolyPoly.getB2DPolyPolygon());
bool bSuccess(true);
// transform the polygon and ensure closed
aB2DPolyPolygon.transform(aTransform);
aB2DPolyPolygon.setClosed(true);
if(IsFillColor())
{
bSuccess = mpGraphics->DrawPolyPolygon(aB2DPolyPolygon, 0.0, this);
}
if(bSuccess && IsLineColor())
{
const ::basegfx::B2DVector aB2DLineWidth( 1.0, 1.0 );
if(mnAntialiasing & ANTIALIASING_PIXELSNAPHAIRLINE)
{
aB2DPolyPolygon = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aB2DPolyPolygon);
}
for(sal_uInt32 a(0); bSuccess && a < aB2DPolyPolygon.count(); a++)
{
bSuccess = mpGraphics->DrawPolyLine(
aB2DPolyPolygon.getB2DPolygon(a),
0.0,
aB2DLineWidth,
basegfx::B2DLINEJOIN_NONE,
com::sun::star::drawing::LineCap_BUTT,
this);
}
}
if(bSuccess)
{
return;
}
}
if ( nPoly == 1 )
{
// #100127# Map to DrawPolygon
Polygon aPoly = rPolyPoly.GetObject( 0 );
if( aPoly.GetSize() >= 2 )
{
GDIMetaFile* pOldMF = mpMetaFile;
mpMetaFile = NULL;
DrawPolygon( aPoly );
mpMetaFile = pOldMF;
}
}
else
{
// #100127# moved real PolyPolygon draw to separate method,
// have to call recursively, avoiding duplicate
// ImplLogicToDevicePixel calls
ImplDrawPolyPolygon( nPoly, ImplLogicToDevicePixel( rPolyPoly ) );
}
if( mpAlphaVDev )
mpAlphaVDev->DrawPolyPolygon( rPolyPoly );
}
// -----------------------------------------------------------------------
void OutputDevice::DrawPolygon( const ::basegfx::B2DPolygon& rB2DPolygon)
{
// AW: Do NOT paint empty polygons
if(rB2DPolygon.count())
{
::basegfx::B2DPolyPolygon aPP( rB2DPolygon );
DrawPolyPolygon( aPP );
}
}
// -----------------------------------------------------------------------
// Caution: This method is nearly the same as
// OutputDevice::DrawTransparent( const basegfx::B2DPolyPolygon& rB2DPolyPoly, double fTransparency),
// so when changes are made here do not forget to make change sthere, too
void OutputDevice::DrawPolyPolygon( const basegfx::B2DPolyPolygon& rB2DPolyPoly )
{
DBG_TRACE( "OutputDevice::DrawPolyPolygon(B2D&)" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
#if 0
// MetaB2DPolyPolygonAction is not implemented yet:
// according to AW adding it is very dangerous since there is a lot
// of code that uses the metafile actions directly and unless every
// place that does this knows about the new action we need to fallback
if( mpMetaFile )
mpMetaFile->AddAction( new MetaB2DPolyPolygonAction( rB2DPolyPoly ) );
#else
if( mpMetaFile )
mpMetaFile->AddAction( new MetaPolyPolygonAction( PolyPolygon( rB2DPolyPoly ) ) );
#endif
// call helper
ImpDrawPolyPolygonWithB2DPolyPolygon(rB2DPolyPoly);
}
void OutputDevice::ImpDrawPolyPolygonWithB2DPolyPolygon(const basegfx::B2DPolyPolygon& rB2DPolyPoly)
{
// AW: Do NOT paint empty PolyPolygons
if(!rB2DPolyPoly.count())
return;
// we need a graphics
if( !mpGraphics )
if( !ImplGetGraphics() )
return;
if( mbInitClipRegion )
ImplInitClipRegion();
if( mbOutputClipped )
return;
if( mbInitLineColor )
ImplInitLineColor();
if( mbInitFillColor )
ImplInitFillColor();
if((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& (IsLineColor() || IsFillColor()))
{
const basegfx::B2DHomMatrix aTransform(ImplGetDeviceTransformation());
basegfx::B2DPolyPolygon aB2DPolyPolygon(rB2DPolyPoly);
bool bSuccess(true);
// transform the polygon and ensure closed
aB2DPolyPolygon.transform(aTransform);
aB2DPolyPolygon.setClosed(true);
if(IsFillColor())
{
bSuccess = mpGraphics->DrawPolyPolygon(aB2DPolyPolygon, 0.0, this);
}
if(bSuccess && IsLineColor())
{
const ::basegfx::B2DVector aB2DLineWidth( 1.0, 1.0 );
if(mnAntialiasing & ANTIALIASING_PIXELSNAPHAIRLINE)
{
aB2DPolyPolygon = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aB2DPolyPolygon);
}
for(sal_uInt32 a(0);bSuccess && a < aB2DPolyPolygon.count(); a++)
{
bSuccess = mpGraphics->DrawPolyLine(
aB2DPolyPolygon.getB2DPolygon(a),
0.0,
aB2DLineWidth,
basegfx::B2DLINEJOIN_NONE,
com::sun::star::drawing::LineCap_BUTT,
this);
}
}
if(bSuccess)
{
return;
}
}
// fallback to old polygon drawing if needed
const PolyPolygon aToolsPolyPolygon( rB2DPolyPoly );
const PolyPolygon aPixelPolyPolygon = ImplLogicToDevicePixel( aToolsPolyPolygon );
ImplDrawPolyPolygon( aPixelPolyPolygon.Count(), aPixelPolyPolygon );
}
// -----------------------------------------------------------------------
bool OutputDevice::ImpTryDrawPolyLineDirect(
const basegfx::B2DPolygon& rB2DPolygon,
double fLineWidth,
double fTransparency,
basegfx::B2DLineJoin eLineJoin,
com::sun::star::drawing::LineCap eLineCap)
{
const basegfx::B2DHomMatrix aTransform = ImplGetDeviceTransformation();
basegfx::B2DVector aB2DLineWidth(1.0, 1.0);
// transform the line width if used
if( fLineWidth != 0.0 )
{
aB2DLineWidth = aTransform * ::basegfx::B2DVector( fLineWidth, fLineWidth );
}
// transform the polygon
basegfx::B2DPolygon aB2DPolygon(rB2DPolygon);
aB2DPolygon.transform(aTransform);
if((mnAntialiasing & ANTIALIASING_PIXELSNAPHAIRLINE)
&& aB2DPolygon.count() < 1000)
{
// #i98289#, #i101491#
// better to remove doubles on device coordinates. Also assume from a given amount
// of points that the single edges are not long enough to smooth
aB2DPolygon.removeDoublePoints();
aB2DPolygon = basegfx::tools::snapPointsOfHorizontalOrVerticalEdges(aB2DPolygon);
}
// draw the polyline
return mpGraphics->DrawPolyLine(
aB2DPolygon,
fTransparency,
aB2DLineWidth,
eLineJoin,
eLineCap,
this);
}
bool OutputDevice::TryDrawPolyLineDirect(
const basegfx::B2DPolygon& rB2DPolygon,
double fLineWidth,
double fTransparency,
basegfx::B2DLineJoin eLineJoin,
com::sun::star::drawing::LineCap eLineCap)
{
// AW: Do NOT paint empty PolyPolygons
if(!rB2DPolygon.count())
return true;
// we need a graphics
if( !mpGraphics )
if( !ImplGetGraphics() )
return false;
if( mbInitClipRegion )
ImplInitClipRegion();
if( mbOutputClipped )
return true;
if( mbInitLineColor )
ImplInitLineColor();
const bool bTryAA((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& IsLineColor());
if(bTryAA)
{
if(ImpTryDrawPolyLineDirect(rB2DPolygon, fLineWidth, fTransparency, eLineJoin, eLineCap))
{
// worked, add metafile action (if recorded) and return true
if( mpMetaFile )
{
LineInfo aLineInfo;
if( fLineWidth != 0.0 )
aLineInfo.SetWidth( static_cast<long>(fLineWidth+0.5) );
const Polygon aToolsPolygon( rB2DPolygon );
mpMetaFile->AddAction( new MetaPolyLineAction( aToolsPolygon, aLineInfo ) );
}
return true;
}
}
return false;
}
void OutputDevice::DrawPolyLine(
const basegfx::B2DPolygon& rB2DPolygon,
double fLineWidth,
basegfx::B2DLineJoin eLineJoin,
com::sun::star::drawing::LineCap eLineCap)
{
DBG_TRACE( "OutputDevice::DrawPolyLine(B2D&)" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
#if 0 // MetaB2DPolyLineAction is not implemented yet:
// according to AW adding it is very dangerous since there is a lot
// of code that uses the metafile actions directly and unless every
// place that does this knows about the new action we need to fallback
if( mpMetaFile )
mpMetaFile->AddAction( new MetaB2DPolyLineAction( rB2DPolygon ) );
#else
if( mpMetaFile )
{
LineInfo aLineInfo;
if( fLineWidth != 0.0 )
aLineInfo.SetWidth( static_cast<long>(fLineWidth+0.5) );
const Polygon aToolsPolygon( rB2DPolygon );
mpMetaFile->AddAction( new MetaPolyLineAction( aToolsPolygon, aLineInfo ) );
}
#endif
// AW: Do NOT paint empty PolyPolygons
if(!rB2DPolygon.count())
return;
// we need a graphics
if( !mpGraphics )
if( !ImplGetGraphics() )
return;
if( mbInitClipRegion )
ImplInitClipRegion();
if( mbOutputClipped )
return;
if( mbInitLineColor )
ImplInitLineColor();
const bool bTryAA((mnAntialiasing & ANTIALIASING_ENABLE_B2DDRAW)
&& mpGraphics->supportsOperation(OutDevSupport_B2DDraw)
&& ROP_OVERPAINT == GetRasterOp()
&& IsLineColor());
// use b2dpolygon drawing if possible
if(bTryAA && ImpTryDrawPolyLineDirect(rB2DPolygon, fLineWidth, 0.0, eLineJoin, eLineCap))
{
return;
}
// #i101491#
// no output yet; fallback to geometry decomposition and use filled polygon paint
// when line is fat and not too complex. ImpDrawPolyPolygonWithB2DPolyPolygon
// will do internal needed AA checks etc.
if(fLineWidth >= 2.5
&& rB2DPolygon.count()
&& rB2DPolygon.count() <= 1000)
{
const double fHalfLineWidth((fLineWidth * 0.5) + 0.5);
const basegfx::B2DPolyPolygon aAreaPolyPolygon(
basegfx::tools::createAreaGeometry(
rB2DPolygon,
fHalfLineWidth,
eLineJoin,
eLineCap));
const Color aOldLineColor(maLineColor);
const Color aOldFillColor(maFillColor);
SetLineColor();
ImplInitLineColor();
SetFillColor(aOldLineColor);
ImplInitFillColor();
// draw usig a loop; else the topology will paint a PolyPolygon
for(sal_uInt32 a(0); a < aAreaPolyPolygon.count(); a++)
{
ImpDrawPolyPolygonWithB2DPolyPolygon(
basegfx::B2DPolyPolygon(aAreaPolyPolygon.getB2DPolygon(a)));
}
SetLineColor(aOldLineColor);
ImplInitLineColor();
SetFillColor(aOldFillColor);
ImplInitFillColor();
if(bTryAA)
{
// when AA it is necessary to also paint the filled polygon's outline
// to avoid optical gaps
for(sal_uInt32 a(0); a < aAreaPolyPolygon.count(); a++)
{
ImpTryDrawPolyLineDirect(aAreaPolyPolygon.getB2DPolygon(a));
}
}
}
else
{
// fallback to old polygon drawing if needed
const Polygon aToolsPolygon( rB2DPolygon );
LineInfo aLineInfo;
if( fLineWidth != 0.0 )
aLineInfo.SetWidth( static_cast<long>(fLineWidth+0.5) );
ImpDrawPolyLineWithLineInfo( aToolsPolygon, aLineInfo );
}
}
// -----------------------------------------------------------------------
sal_uInt32 OutputDevice::GetGCStackDepth() const
{
const ImplObjStack* pData = mpObjStack;
sal_uInt32 nDepth = 0;
while( pData )
{
nDepth++;
pData = pData->mpPrev;
}
return nDepth;
}
// -----------------------------------------------------------------------
void OutputDevice::Push( sal_uInt16 nFlags )
{
DBG_TRACE( "OutputDevice::Push()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( mpMetaFile )
mpMetaFile->AddAction( new MetaPushAction( nFlags ) );
ImplObjStack* pData = new ImplObjStack;
pData->mpPrev = mpObjStack;
mpObjStack = pData;
pData->mnFlags = nFlags;
if ( nFlags & PUSH_LINECOLOR )
{
if ( mbLineColor )
pData->mpLineColor = new Color( maLineColor );
else
pData->mpLineColor = NULL;
}
if ( nFlags & PUSH_FILLCOLOR )
{
if ( mbFillColor )
pData->mpFillColor = new Color( maFillColor );
else
pData->mpFillColor = NULL;
}
if ( nFlags & PUSH_FONT )
pData->mpFont = new Font( maFont );
if ( nFlags & PUSH_TEXTCOLOR )
pData->mpTextColor = new Color( GetTextColor() );
if ( nFlags & PUSH_TEXTFILLCOLOR )
{
if ( IsTextFillColor() )
pData->mpTextFillColor = new Color( GetTextFillColor() );
else
pData->mpTextFillColor = NULL;
}
if ( nFlags & PUSH_TEXTLINECOLOR )
{
if ( IsTextLineColor() )
pData->mpTextLineColor = new Color( GetTextLineColor() );
else
pData->mpTextLineColor = NULL;
}
if ( nFlags & PUSH_OVERLINECOLOR )
{
if ( IsOverlineColor() )
pData->mpOverlineColor = new Color( GetOverlineColor() );
else
pData->mpOverlineColor = NULL;
}
if ( nFlags & PUSH_TEXTALIGN )
pData->meTextAlign = GetTextAlign();
if( nFlags & PUSH_TEXTLAYOUTMODE )
pData->mnTextLayoutMode = GetLayoutMode();
if( nFlags & PUSH_TEXTLANGUAGE )
pData->meTextLanguage = GetDigitLanguage();
if ( nFlags & PUSH_RASTEROP )
pData->meRasterOp = GetRasterOp();
if ( nFlags & PUSH_MAPMODE )
{
pData->mpMapMode = new MapMode( maMapMode );
pData->mbMapActive = mbMap;
}
if ( nFlags & PUSH_CLIPREGION )
{
if ( mbClipRegion )
pData->mpClipRegion = new Region( maRegion );
else
pData->mpClipRegion = NULL;
}
if ( nFlags & PUSH_REFPOINT )
{
if ( mbRefPoint )
pData->mpRefPoint = new Point( maRefPoint );
else
pData->mpRefPoint = NULL;
}
if( mpAlphaVDev )
mpAlphaVDev->Push();
}
// -----------------------------------------------------------------------
void OutputDevice::Pop()
{
DBG_TRACE( "OutputDevice::Pop()" );
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if( mpMetaFile )
mpMetaFile->AddAction( new MetaPopAction() );
GDIMetaFile* pOldMetaFile = mpMetaFile;
ImplObjStack* pData = mpObjStack;
mpMetaFile = NULL;
if ( !pData )
{
DBG_ERRORFILE( "OutputDevice::Pop() without OutputDevice::Push()" );
return;
}
if( mpAlphaVDev )
mpAlphaVDev->Pop();
mpObjStack = pData->mpPrev;
if ( pData->mnFlags & PUSH_LINECOLOR )
{
if ( pData->mpLineColor )
SetLineColor( *pData->mpLineColor );
else
SetLineColor();
}
if ( pData->mnFlags & PUSH_FILLCOLOR )
{
if ( pData->mpFillColor )
SetFillColor( *pData->mpFillColor );
else
SetFillColor();
}
if ( pData->mnFlags & PUSH_FONT )
SetFont( *pData->mpFont );
if ( pData->mnFlags & PUSH_TEXTCOLOR )
SetTextColor( *pData->mpTextColor );
if ( pData->mnFlags & PUSH_TEXTFILLCOLOR )
{
if ( pData->mpTextFillColor )
SetTextFillColor( *pData->mpTextFillColor );
else
SetTextFillColor();
}
if ( pData->mnFlags & PUSH_TEXTLINECOLOR )
{
if ( pData->mpTextLineColor )
SetTextLineColor( *pData->mpTextLineColor );
else
SetTextLineColor();
}
if ( pData->mnFlags & PUSH_OVERLINECOLOR )
{
if ( pData->mpOverlineColor )
SetOverlineColor( *pData->mpOverlineColor );
else
SetOverlineColor();
}
if ( pData->mnFlags & PUSH_TEXTALIGN )
SetTextAlign( pData->meTextAlign );
if( pData->mnFlags & PUSH_TEXTLAYOUTMODE )
SetLayoutMode( pData->mnTextLayoutMode );
if( pData->mnFlags & PUSH_TEXTLANGUAGE )
SetDigitLanguage( pData->meTextLanguage );
if ( pData->mnFlags & PUSH_RASTEROP )
SetRasterOp( pData->meRasterOp );
if ( pData->mnFlags & PUSH_MAPMODE )
{
if ( pData->mpMapMode )
SetMapMode( *pData->mpMapMode );
else
SetMapMode();
mbMap = pData->mbMapActive;
}
if ( pData->mnFlags & PUSH_CLIPREGION )
ImplSetClipRegion( pData->mpClipRegion );
if ( pData->mnFlags & PUSH_REFPOINT )
{
if ( pData->mpRefPoint )
SetRefPoint( *pData->mpRefPoint );
else
SetRefPoint();
}
ImplDeleteObjStack( pData );
mpMetaFile = pOldMetaFile;
}
// -----------------------------------------------------------------------
void OutputDevice::SetConnectMetaFile( GDIMetaFile* pMtf )
{
mpMetaFile = pMtf;
}
// -----------------------------------------------------------------------
void OutputDevice::EnableOutput( sal_Bool bEnable )
{
mbOutput = (bEnable != 0);
if( mpAlphaVDev )
mpAlphaVDev->EnableOutput( bEnable );
}
// -----------------------------------------------------------------------
void OutputDevice::SetSettings( const AllSettings& rSettings )
{
maSettings = rSettings;
if( mpAlphaVDev )
mpAlphaVDev->SetSettings( rSettings );
}
// -----------------------------------------------------------------------
sal_uInt16 OutputDevice::GetBitCount() const
{
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( meOutDevType == OUTDEV_VIRDEV )
return ((VirtualDevice*)this)->mnBitCount;
// we need a graphics
if ( !mpGraphics )
{
if ( !((OutputDevice*)this)->ImplGetGraphics() )
return 0;
}
return (sal_uInt16)mpGraphics->GetBitCount();
}
// -----------------------------------------------------------------------
sal_uInt16 OutputDevice::GetAlphaBitCount() const
{
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
if ( meOutDevType == OUTDEV_VIRDEV &&
mpAlphaVDev != NULL )
{
return mpAlphaVDev->GetBitCount();
}
return 0;
}
// -----------------------------------------------------------------------
sal_uLong OutputDevice::GetColorCount() const
{
DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice );
const sal_uInt16 nBitCount = GetBitCount();
return( ( nBitCount > 31 ) ? ULONG_MAX : ( ( (sal_uLong) 1 ) << nBitCount) );
}
// -----------------------------------------------------------------------
sal_Bool OutputDevice::HasAlpha()
{
return mpAlphaVDev != NULL;
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics > OutputDevice::CreateUnoGraphics()
{
UnoWrapperBase* pWrapper = Application::GetUnoWrapper();
return pWrapper ? pWrapper->CreateGraphics( this ) : ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >();
}
// -----------------------------------------------------------------------
SystemGraphicsData OutputDevice::GetSystemGfxData() const
{
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return SystemGraphicsData();
}
return mpGraphics->GetGraphicsData();
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Any OutputDevice::GetSystemGfxDataAny() const
{
::com::sun::star::uno::Any aRet;
const SystemGraphicsData aSysData = GetSystemGfxData();
::com::sun::star::uno::Sequence< sal_Int8 > aSeq( (sal_Int8*)&aSysData,
aSysData.nSize );
return uno::makeAny(aSeq);
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > OutputDevice::GetCanvas() const
{
uno::Sequence< uno::Any > aArg(6);
aArg[ 0 ] = uno::makeAny( reinterpret_cast<sal_Int64>(this) );
aArg[ 2 ] = uno::makeAny( ::com::sun::star::awt::Rectangle( mnOutOffX, mnOutOffY, mnOutWidth, mnOutHeight ) );
aArg[ 3 ] = uno::makeAny( sal_False );
aArg[ 5 ] = GetSystemGfxDataAny();
uno::Reference<lang::XMultiServiceFactory> xFactory = vcl::unohelper::GetMultiServiceFactory();
uno::Reference<rendering::XCanvas> xCanvas;
// Create canvas instance with window handle
// =========================================
if ( xFactory.is() )
{
static uno::Reference<lang::XMultiServiceFactory> xCanvasFactory(
xFactory->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star."
"rendering.CanvasFactory") ) ),
uno::UNO_QUERY );
if(xCanvasFactory.is())
{
xCanvas.set(
xCanvasFactory->createInstanceWithArguments(
OUString( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.rendering.Canvas" )),
aArg ),
uno::UNO_QUERY );
}
}
return xCanvas;
}
// -----------------------------------------------------------------------
| 28.038818 | 168 | 0.623868 | [
"geometry",
"vector",
"transform"
] |
d22236250dfbfa40ecb87468012e0edcd5b4b605 | 2,322 | hpp | C++ | src/libpanacea/distribution/distributions/distribution.hpp | lanl/PANACEA | 9779bdb6dcc3be41ea7b286ae55a21bb269e0339 | [
"BSD-3-Clause"
] | null | null | null | src/libpanacea/distribution/distributions/distribution.hpp | lanl/PANACEA | 9779bdb6dcc3be41ea7b286ae55a21bb269e0339 | [
"BSD-3-Clause"
] | null | null | null | src/libpanacea/distribution/distributions/distribution.hpp | lanl/PANACEA | 9779bdb6dcc3be41ea7b286ae55a21bb269e0339 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PANACEA_PRIVATE_BASEDISTRIBUTION_H
#define PANACEA_PRIVATE_BASEDISTRIBUTION_H
#pragma once
// Local private PANACEA includes
#include "private_settings.hpp"
// Public PANACEA includes
#include "panacea/file_io_types.hpp"
// Standard includes
#include <any>
#include <iostream>
#include <vector>
namespace panacea {
class BaseDescriptorWrapper;
class Dimensions;
class DistributionSettings;
class Distribution;
class Distribution {
public:
typedef io::ReadInstantiateVector (*ReadFunction)(
const settings::FileType file_type, std::istream &, Distribution &);
typedef std::vector<std::any> (*WriteFunction)(
const settings::FileType file_type, std::ostream &, const Distribution &);
private:
virtual Distribution::ReadFunction getReadFunction_() = 0;
virtual Distribution::WriteFunction getWriteFunction_() const = 0;
public:
virtual settings::DistributionType type() const noexcept = 0;
virtual double compute(const BaseDescriptorWrapper &descriptor_wrapper,
const int desc_ind,
const DistributionSettings &distribution_settings) = 0;
virtual std::vector<double>
compute_grad(const BaseDescriptorWrapper &descriptor_wrapper,
const int desc_ind,
const int grad_ind, // The index associated with whatever we are
// taking the gradiant with respect to
const DistributionSettings &distribution_settings,
std::any extra_options = settings::None::None) = 0;
/**
* Get the actual dimensions used in the distribution
**/
virtual const Dimensions &getDimensions() const noexcept = 0;
virtual const int getMaximumNumberOfDimensions() const noexcept = 0;
virtual void update(const BaseDescriptorWrapper &descriptor_wrapper) = 0;
virtual void initialize(const BaseDescriptorWrapper &descriptor_wrapper) = 0;
virtual ~Distribution() = 0;
static std::vector<std::any> write(const settings::FileType file_type,
std::ostream &, std::any dist_instance);
static io::ReadInstantiateVector read(const settings::FileType file_type,
std::istream &, std::any dist_instance);
};
} // namespace panacea
#endif // PANACEA_PRIVATE_BASEDISTRIBUTION_H
| 32.25 | 80 | 0.703704 | [
"vector"
] |
d230561c740cf40af6b74505f121d50b001cef1b | 1,182 | cpp | C++ | book/CH01/S14_Selecting_index_of_a_queue_family_with_desired_capabilities.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 5 | 2019-03-02T16:29:15.000Z | 2021-11-07T11:07:53.000Z | book/CH01/S14_Selecting_index_of_a_queue_family_with_desired_capabilities.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | null | null | null | book/CH01/S14_Selecting_index_of_a_queue_family_with_desired_capabilities.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 2 | 2018-07-10T18:15:40.000Z | 2020-01-03T04:02:32.000Z | //
// Created by aicdg on 2017/6/17.
//
//
// Chapter: 01 Instance and Devices
// Recipe: 14 Selecting index of a queue family with desired capabilities
#include "S13_Checking_available_queue_families_and_their_properties.h"
#include "S14_Selecting_index_of_a_queue_family_with_desired_capabilities.h"
namespace VKCookbook {
bool SelectIndexOfQueueFamilyWithDesiredCapabilities( VkPhysicalDevice physical_device,
VkQueueFlags desired_capabilities,
uint32_t & queue_family_index ) {
std::vector<VkQueueFamilyProperties> queue_families;
if( !CheckAvailableQueueFamiliesAndTheirProperties( physical_device, queue_families ) ) {
return false;
}
for ( uint32_t index = 0; index < static_cast<uint32_t>(queue_families.size()); ++index) {
if( (queue_families[index].queueCount > 0) &&
(queue_families[index].queueFlags & desired_capabilities) ) {
queue_family_index = index;
return true;
}
}
return false;
}
} | 35.818182 | 99 | 0.615059 | [
"vector"
] |
d230c698d97bf2b5c07514066c326b13d9e5a62c | 832 | hpp | C++ | src/vbk/test/util/tx.hpp | xagau/vbk-ri-btc | 9907b6ec54894c01e1f6dcfd80764f08ac84743a | [
"MIT"
] | 1 | 2020-04-20T15:20:23.000Z | 2020-04-20T15:20:23.000Z | src/vbk/test/util/tx.hpp | xagau/vbk-ri-btc | 9907b6ec54894c01e1f6dcfd80764f08ac84743a | [
"MIT"
] | null | null | null | src/vbk/test/util/tx.hpp | xagau/vbk-ri-btc | 9907b6ec54894c01e1f6dcfd80764f08ac84743a | [
"MIT"
] | null | null | null | #ifndef BITCOIN_SRC_VBK_TEST_UTIL_TX_HPP
#define BITCOIN_SRC_VBK_TEST_UTIL_TX_HPP
#include <primitives/transaction.h>
#include <vbk/util.hpp>
namespace VeriBlockTest {
// creates valid pop transaction given atv & vtbs
inline CMutableTransaction makePopTx(const std::vector<uint8_t>& atv, const std::vector<std::vector<uint8_t>>& vtbs)
{
CMutableTransaction tx;
tx.vin.resize(1);
VeriBlock::setVBKNoInput(tx.vin[0].prevout);
tx.vin[0].scriptSig << atv << OP_CHECKATV;
for (const auto& vtb : vtbs) {
tx.vin[0].scriptSig << vtb << OP_CHECKVTB;
}
tx.vin[0].scriptSig << OP_CHECKPOP;
// set output: OP_RETURN
tx.vout.resize(1);
tx.vout[0].scriptPubKey << OP_RETURN;
tx.vout[0].nValue = 0;
return tx;
}
} // namespace VeriBlockTest
#endif //BITCOIN_SRC_VBK_TEST_UTIL_TX_HPP
| 25.212121 | 116 | 0.703125 | [
"vector"
] |
d237557df6b001856573319634453cd49eecb129 | 3,932 | cpp | C++ | build/qCC/CloudCompare_autogen/include_Debug/MR6MLFC4MR/moc_matrixDisplayDlg.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | build/qCC/CloudCompare_autogen/include_Debug/MR6MLFC4MR/moc_matrixDisplayDlg.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | null | null | null | build/qCC/CloudCompare_autogen/include_Debug/MR6MLFC4MR/moc_matrixDisplayDlg.cpp | ohanlonl/qCMAT | f6ca04fa7c171629f094ee886364c46ff8b27c0b | [
"BSD-Source-Code"
] | 1 | 2019-02-03T12:19:42.000Z | 2019-02-03T12:19:42.000Z | /****************************************************************************
** Meta object code from reading C++ file 'matrixDisplayDlg.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../../../qCC/db_tree/matrixDisplayDlg.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'matrixDisplayDlg.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MatrixDisplayDlg_t {
QByteArrayData data[4];
char stringdata0[50];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MatrixDisplayDlg_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MatrixDisplayDlg_t qt_meta_stringdata_MatrixDisplayDlg = {
{
QT_MOC_LITERAL(0, 0, 16), // "MatrixDisplayDlg"
QT_MOC_LITERAL(1, 17, 13), // "exportToASCII"
QT_MOC_LITERAL(2, 31, 0), // ""
QT_MOC_LITERAL(3, 32, 17) // "exportToClipboard"
},
"MatrixDisplayDlg\0exportToASCII\0\0"
"exportToClipboard"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MatrixDisplayDlg[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 24, 2, 0x0a /* Public */,
3, 0, 25, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void MatrixDisplayDlg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MatrixDisplayDlg *_t = static_cast<MatrixDisplayDlg *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->exportToASCII(); break;
case 1: _t->exportToClipboard(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MatrixDisplayDlg::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_MatrixDisplayDlg.data,
qt_meta_data_MatrixDisplayDlg, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MatrixDisplayDlg::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MatrixDisplayDlg::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MatrixDisplayDlg.stringdata0))
return static_cast<void*>(this);
if (!strcmp(_clname, "Ui::MatrixDisplayDlg"))
return static_cast< Ui::MatrixDisplayDlg*>(this);
return QWidget::qt_metacast(_clname);
}
int MatrixDisplayDlg::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 32.229508 | 97 | 0.614191 | [
"object"
] |
d240e65e332d34317ba25b03523e19dedbf6f1da | 2,155 | hpp | C++ | src/core/stream_utility.hpp | mnewhouse/izieditor | 0a7f300737de9ab5a2a9a02c1a8c786083e71054 | [
"MIT"
] | null | null | null | src/core/stream_utility.hpp | mnewhouse/izieditor | 0a7f300737de9ab5a2a9a02c1a8c786083e71054 | [
"MIT"
] | null | null | null | src/core/stream_utility.hpp | mnewhouse/izieditor | 0a7f300737de9ab5a2a9a02c1a8c786083e71054 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* IziEditor
* Copyright (c) 2015 Martin Newhouse
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef STREAM_UTILITY_HPP
#define STREAM_UTILITY_HPP
#include <istream>
#include <vector>
namespace core
{
template <typename CharType>
std::vector<CharType> read_stream_contents(std::basic_istream<CharType>& stream);
template <typename CharType = unsigned char>
std::vector<CharType> read_file_contents(const std::string& file_name);
}
template <typename CharType>
std::vector<CharType> core::read_stream_contents(std::basic_istream<CharType>& stream)
{
auto current_pos = stream.tellg();
stream.seekg(0, std::istream::end);
auto num_bytes = static_cast<std::size_t>(stream.tellg() - current_pos);
stream.seekg(current_pos);
std::vector<CharType> result(num_bytes);
stream.read(result.data(), num_bytes);
return result;
}
template <typename CharType>
std::vector<CharType> core::read_file_contents(const std::string& file_name)
{
std::ifstream stream(file_name, std::istream::in | std::istream::binary);
return read_stream_contents(stream);
}
#endif | 33.671875 | 86 | 0.75406 | [
"vector"
] |
d242ec8470c0284eb6db0ad0eae84cbf0a57da60 | 3,177 | hpp | C++ | test/unit/module/real/core/hypot/regular/hypot.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/core/hypot/regular/hypot.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/core/hypot/regular/hypot.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/function/hypot.hpp>
#include <eve/constant/valmax.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <eve/constant/sqrt_2.hpp>
#include <eve/platform.hpp>
#include <cmath>
TTS_CASE_TPL("Check hypot return type", EVE_TYPE)
{
using v_t = eve::element_type_t<T>;
TTS_EXPR_IS(eve::hypot( T(0), T(0)), T);
TTS_EXPR_IS(eve::hypot( v_t(0), T(0)), T);
TTS_EXPR_IS(eve::hypot( T(0), v_t(0)), T);
TTS_EXPR_IS(eve::hypot( T(0), T(0), T(0)), T);
TTS_EXPR_IS(eve::hypot( T(0), T(0), v_t(0)), T);
TTS_EXPR_IS(eve::hypot( T(0), v_t(0), T(0)), T);
TTS_EXPR_IS(eve::hypot( T(0), v_t(0), v_t(0)), T);
TTS_EXPR_IS(eve::hypot( v_t(0), T(0), T(0)), T);
TTS_EXPR_IS(eve::hypot( v_t(0), T(0), v_t(0)), T);
TTS_EXPR_IS(eve::hypot( v_t(0), v_t(0), T(0)), T);
}
TTS_CASE_TPL("Check eve::hypot behavior", EVE_TYPE)
{
// non conforming to standard
if constexpr(eve::platform::supports_invalids)
{
TTS_IEEE_EQUAL(eve::hypot(eve::nan(eve::as<T>()), eve::inf(eve::as<T>())), eve::nan(eve::as<T>()));
TTS_IEEE_EQUAL(eve::hypot(eve::inf(eve::as<T>()), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()));
}
TTS_IEEE_EQUAL(eve::hypot(eve::valmax(eve::as<T>()) , T(0) ) , eve::inf(eve::as<T>()));
TTS_IEEE_EQUAL(eve::hypot(T(0) , eve::valmax(eve::as<T>())) , eve::inf(eve::as<T>()));
TTS_ULP_EQUAL(eve::hypot(T(-1), T(-1)) , eve::sqrt_2(eve::as<T>()), 0.5);
TTS_ULP_EQUAL(eve::hypot(T( 1), T( 1)) , eve::sqrt_2(eve::as<T>()), 0.5);
TTS_ULP_EQUAL(eve::hypot(T( 0), T( 0)) , T(0) , 0.5);
TTS_ULP_EQUAL(eve::hypot(eve::sqrt_2(eve::as<T>()), eve::sqrt_2(eve::as<T>())), T(2) , 0.5);
}
TTS_CASE_TPL("Check 3 params eve::hypot behavior", EVE_TYPE)
{
using v_t = eve::element_type_t<T>;
// non conforming to standard
if constexpr(eve::platform::supports_invalids)
{
TTS_IEEE_EQUAL(eve::hypot(eve::nan(eve::as<T>()), eve::inf(eve::as<T>()), eve::inf(eve::as<T>())), eve::nan(eve::as<T>()));
TTS_IEEE_EQUAL(eve::hypot(eve::inf(eve::as<T>()), eve::nan(eve::as<T>()), eve::inf(eve::as<T>())), eve::nan(eve::as<T>()));
}
TTS_IEEE_EQUAL(eve::hypot(eve::valmax(eve::as<T>()) , T(0) , T(0)) , eve::inf(eve::as<T>()));
TTS_IEEE_EQUAL(eve::hypot(T(0) , eve::valmax(eve::as<T>()), T(0)) , eve::inf(eve::as<T>()));
TTS_ULP_EQUAL(eve::hypot(T(-1), T(-1), eve::sqrt_2(eve::as<T>()) ) , T(2) , 0.5);
TTS_ULP_EQUAL(eve::hypot(T( 1), T( 1), eve::sqrt_2(eve::as<T>()) ) , T(2) , 0.5);
TTS_ULP_EQUAL(eve::hypot(T( 0), T( 0), T( 0) ) , T(0) , 0.5);
TTS_ULP_EQUAL(eve::hypot(T( 1), T( 1), T( 1) ) , T(std::sqrt(v_t(3))), 0.5);
}
| 44.125 | 127 | 0.517155 | [
"vector"
] |
d244c29db356d48aac6798309120e3a31b0e39ff | 5,189 | cpp | C++ | flatland_plugins/src/world_random_wall.cpp | schmiddey/flatland | 7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb | [
"BSD-3-Clause"
] | null | null | null | flatland_plugins/src/world_random_wall.cpp | schmiddey/flatland | 7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb | [
"BSD-3-Clause"
] | null | null | null | flatland_plugins/src/world_random_wall.cpp | schmiddey/flatland | 7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb | [
"BSD-3-Clause"
] | null | null | null | /*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name world_random_wall.h
* @brief a simple plugin that add random walls on the field
* @author Yi Ren
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Avidbots Corp. 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 <Box2D/Box2D.h>
#include <flatland_plugins/world_modifier.h>
#include <flatland_plugins/world_random_wall.h>
#include <flatland_server/types.h>
#include <flatland_server/world_plugin.h>
#include <pluginlib/class_list_macros.hpp>
#include <rclcpp/rclcpp.hpp>
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <iostream>
#include <string>
using namespace flatland_server;
using std::cout;
using std::endl;
namespace flatland_plugins {
void RandomWall::OnInitialize(const YAML::Node &config, YamlReader &world_config) {
// read in the plugin config
YamlReader plugin_reader(node_, config);
std::string layer_name = plugin_reader.Get<std::string>("layer", "");
unsigned int num_of_walls =
plugin_reader.Get<unsigned int>("num_of_walls", 0);
double wall_wall_dist = plugin_reader.Get<double>("wall_wall_dist", 1);
bool double_wall = plugin_reader.Get<bool>("double_wall", false);
std::string robot_name = plugin_reader.Get<std::string>("robot_name", "");
Layer *layer = NULL;
for (auto &it : world_->layers_name_map_) {
for (auto &v_it : it.first) {
if (v_it == layer_name) {
layer = it.second;
break;
}
}
}
if (layer == NULL) {
throw("no such layer name!");
}
// read in the robot location from the world.yaml
Pose robot_ini_pose;
YamlReader models_reader =
world_config.SubnodeOpt("models", YamlReader::LIST);
if (models_reader.IsNodeNull()) {
throw("no robot specified!");
}
for (int i = 0; i < models_reader.NodeSize(); i++) {
YamlReader reader = models_reader.Subnode(i, YamlReader::MAP);
if (i + 1 >= models_reader.NodeSize() &&
reader.Get<std::string>("name") != robot_name) {
throw("cannot find specified robot name of " + robot_name);
}
if (reader.Get<std::string>("name") == robot_name) {
robot_ini_pose = reader.Get("pose", Pose(0, 0, 0));
b2Transform tran = layer->body_->physics_body_->GetTransform();
b2Vec2 ini_pose =
b2MulT(tran, b2Vec2(robot_ini_pose.x, robot_ini_pose.y));
robot_ini_pose.x = ini_pose.x;
robot_ini_pose.y = ini_pose.y;
break;
}
}
// create the world modifiyer
cout << "robot location read" << endl;
WorldModifier modifier(world_, layer_name, wall_wall_dist, double_wall,
robot_ini_pose);
// get all walls
std::vector<b2EdgeShape *> Wall_List;
for (b2Fixture *f = layer->body_->physics_body_->GetFixtureList(); f;
f = f->GetNext()) {
Wall_List.push_back(static_cast<b2EdgeShape *>(f->GetShape()));
}
std::srand(std::time(0));
std::random_shuffle(Wall_List.begin(), Wall_List.end());
try {
for (unsigned int i = 0; i < num_of_walls; i++) {
modifier.AddFullWall(Wall_List[i]);
}
} catch (std::string e) {
throw e;
}
}
}; // namespace
PLUGINLIB_EXPORT_CLASS(flatland_plugins::RandomWall,
flatland_server::WorldPlugin) | 39.310606 | 83 | 0.656967 | [
"vector"
] |
d24a7c2fd468e9ca1df0349d885b732cbd4315bc | 3,626 | cpp | C++ | dbms/src/Access/AccessControlManager.cpp | s5-stratos/ClickHouse | f0657fbac428e326a1c60114328b4c7e8a67073d | [
"Apache-2.0"
] | 1 | 2020-02-14T11:38:11.000Z | 2020-02-14T11:38:11.000Z | dbms/src/Access/AccessControlManager.cpp | s5-stratos/ClickHouse | f0657fbac428e326a1c60114328b4c7e8a67073d | [
"Apache-2.0"
] | null | null | null | dbms/src/Access/AccessControlManager.cpp | s5-stratos/ClickHouse | f0657fbac428e326a1c60114328b4c7e8a67073d | [
"Apache-2.0"
] | null | null | null | #include <Access/AccessControlManager.h>
#include <Access/MultipleAccessStorage.h>
#include <Access/MemoryAccessStorage.h>
#include <Access/UsersConfigAccessStorage.h>
#include <Access/User.h>
#include <Access/QuotaContextFactory.h>
#include <Access/RowPolicyContextFactory.h>
#include <Access/AccessRightsContext.h>
namespace DB
{
namespace
{
std::vector<std::unique_ptr<IAccessStorage>> createStorages()
{
std::vector<std::unique_ptr<IAccessStorage>> list;
list.emplace_back(std::make_unique<MemoryAccessStorage>());
list.emplace_back(std::make_unique<UsersConfigAccessStorage>());
return list;
}
}
AccessControlManager::AccessControlManager()
: MultipleAccessStorage(createStorages()),
quota_context_factory(std::make_unique<QuotaContextFactory>(*this)),
row_policy_context_factory(std::make_unique<RowPolicyContextFactory>(*this))
{
}
AccessControlManager::~AccessControlManager()
{
}
UserPtr AccessControlManager::getUser(
const String & user_name, std::function<void(const UserPtr &)> on_change, ext::scope_guard * subscription) const
{
return getUser(getID<User>(user_name), std::move(on_change), subscription);
}
UserPtr AccessControlManager::getUser(
const UUID & user_id, std::function<void(const UserPtr &)> on_change, ext::scope_guard * subscription) const
{
if (on_change && subscription)
{
*subscription = subscribeForChanges(user_id, [on_change](const UUID &, const AccessEntityPtr & user)
{
if (user)
on_change(typeid_cast<UserPtr>(user));
});
}
return read<User>(user_id);
}
UserPtr AccessControlManager::authorizeAndGetUser(
const String & user_name,
const String & password,
const Poco::Net::IPAddress & address,
std::function<void(const UserPtr &)> on_change,
ext::scope_guard * subscription) const
{
return authorizeAndGetUser(getID<User>(user_name), password, address, std::move(on_change), subscription);
}
UserPtr AccessControlManager::authorizeAndGetUser(
const UUID & user_id,
const String & password,
const Poco::Net::IPAddress & address,
std::function<void(const UserPtr &)> on_change,
ext::scope_guard * subscription) const
{
auto user = getUser(user_id, on_change, subscription);
user->allowed_client_hosts.checkContains(address, user->getName());
user->authentication.checkPassword(password, user->getName());
return user;
}
void AccessControlManager::loadFromConfig(const Poco::Util::AbstractConfiguration & users_config)
{
auto & users_config_access_storage = dynamic_cast<UsersConfigAccessStorage &>(getStorageByIndex(1));
users_config_access_storage.loadFromConfig(users_config);
}
std::shared_ptr<const AccessRightsContext> AccessControlManager::getAccessRightsContext(const UserPtr & user, const ClientInfo & client_info, const Settings & settings, const String & current_database)
{
return std::make_shared<AccessRightsContext>(user, client_info, settings, current_database);
}
std::shared_ptr<QuotaContext> AccessControlManager::createQuotaContext(
const String & user_name, const Poco::Net::IPAddress & address, const String & custom_quota_key)
{
return quota_context_factory->createContext(user_name, address, custom_quota_key);
}
std::vector<QuotaUsageInfo> AccessControlManager::getQuotaUsageInfo() const
{
return quota_context_factory->getUsageInfo();
}
std::shared_ptr<RowPolicyContext> AccessControlManager::getRowPolicyContext(const String & user_name) const
{
return row_policy_context_factory->createContext(user_name);
}
}
| 30.991453 | 201 | 0.747932 | [
"vector"
] |
d2582d01f4843874b044b0e6882a15faf524c9f9 | 8,813 | cpp | C++ | src/MainWindow/main_window.cpp | MidsummerNight/FOEDAG | 4bab24b9a96f1a34ad3bb4a29796bfa3ccb771a6 | [
"MIT"
] | null | null | null | src/MainWindow/main_window.cpp | MidsummerNight/FOEDAG | 4bab24b9a96f1a34ad3bb4a29796bfa3ccb771a6 | [
"MIT"
] | null | null | null | src/MainWindow/main_window.cpp | MidsummerNight/FOEDAG | 4bab24b9a96f1a34ad3bb4a29796bfa3ccb771a6 | [
"MIT"
] | null | null | null | /*
Copyright 2021 The Foedag team
GPL License
Copyright (c) 2021 The Open-Source FPGA Foundation
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "main_window.h"
#include <QTextStream>
#include <QtWidgets>
#include <fstream>
#include "Compiler/TaskManager.h"
#include "Compiler/TaskModel.h"
#include "Compiler/TaskTableView.h"
#include "Console/DummyParser.h"
#include "Console/StreamBuffer.h"
#include "Console/TclConsole.h"
#include "Console/TclConsoleBuilder.h"
#include "Console/TclConsoleWidget.h"
#include "DesignRuns/runs_form.h"
#include "Main/CompilerNotifier.h"
#include "Main/Foedag.h"
#include "NewFile/new_file.h"
#include "NewProject/Main/registerNewProjectCommands.h"
#include "NewProject/new_project_dialog.h"
#include "ProjNavigator/sources_form.h"
#include "TextEditor/text_editor.h"
using namespace FOEDAG;
MainWindow::MainWindow(TclInterpreter* interp) : m_interpreter(interp) {
/* Window settings */
setWindowTitle(tr("FOEDAG"));
resize(350, 250);
QDesktopWidget dw;
setGeometry(dw.width() / 6, dw.height() / 6, dw.width() * 2 / 3,
dw.height() * 2 / 3);
setDockNestingEnabled(true);
setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North);
/* Create actions that can be added to menu/tool bars */
createActions();
/* Create menu bars */
createMenus();
/* Create tool bars */
createToolBars();
/* Create status bar */
statusBar();
// /* Add dummy text editors */
// QTextEdit* editor1 = new QTextEdit;
// QTextEdit* editor2 = new QTextEdit;
// QTextEdit* editor3 = new QTextEdit;
// /* Add widgets into floorplanning */
// QSplitter* leftSplitter = new QSplitter(Qt::Horizontal);
// leftSplitter->addWidget(editor1);
// leftSplitter->setStretchFactor(1, 1);
// QDockWidget* texteditorDockWidget = new QDockWidget(tr("Text Editor"));
// texteditorDockWidget->setObjectName("texteditorDockWidget");
// texteditorDockWidget->setWidget(editor2);
// texteditorDockWidget->setAllowedAreas(Qt::LeftDockWidgetArea |
// Qt::RightDockWidgetArea);
// addDockWidget(Qt::RightDockWidgetArea, texteditorDockWidget);
// QSplitter* mainSplitter = new QSplitter(Qt::Vertical);
// mainSplitter->addWidget(leftSplitter);
// mainSplitter->addWidget(editor3);
// mainSplitter->setStretchFactor(1, 1);
// setCentralWidget(mainSplitter);
statusBar()->showMessage("Ready");
}
void MainWindow::Tcl_NewProject(int argc, const char* argv[]) {
ProjectManager* projectManager = new ProjectManager(this);
projectManager->Tcl_CreateProject(argc, argv);
}
void MainWindow::newFile() {
// QTextStream out(stdout);
// out << "New file is requested\n";
NewFile* newfile = new NewFile(this);
newfile->StartNewFile();
}
void MainWindow::newProjectDlg() {
int ret = newProjdialog->exec();
newProjdialog->close();
if (ret) {
QString strproject = newProjdialog->getProject();
newProjectAction->setEnabled(false);
ReShowWindow(strproject);
}
}
void MainWindow::openProject() {
QString fileName = "";
fileName = QFileDialog::getOpenFileName(this, tr("Open Project"), "",
"FOEDAG Project File(*.ospr)");
if ("" != fileName) {
ReShowWindow(fileName);
}
}
void MainWindow::openFileSlot() {
const QString file = QFileDialog::getOpenFileName(this, tr("Open file"));
auto editor = findChild<TextEditor*>("textEditor");
if (editor) editor->SlotOpenFile(file);
}
void MainWindow::createMenus() {
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(newAction);
fileMenu->addAction(openFile);
fileMenu->addSeparator();
fileMenu->addAction(newProjectAction);
fileMenu->addAction(openProjectAction);
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
}
void MainWindow::createToolBars() {
fileToolBar = addToolBar(tr("&File"));
fileToolBar->addAction(newAction);
}
void MainWindow::createActions() {
newAction = new QAction(tr("&New"), this);
newAction->setIcon(QIcon(":/images/icon_newfile.png"));
newAction->setShortcut(QKeySequence::New);
newAction->setStatusTip(tr("Create a new source file"));
connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
openProjectAction = new QAction(tr("&Open Project"), this);
openProjectAction->setStatusTip(tr("Open a new project"));
connect(openProjectAction, SIGNAL(triggered()), this, SLOT(openProject()));
newProjdialog = new newProjectDialog(this);
newProjectAction = new QAction(tr("&New Project"), this);
newProjectAction->setStatusTip(tr("Create a new project"));
connect(newProjectAction, SIGNAL(triggered()), this, SLOT(newProjectDlg()));
openFile = new QAction(tr("&Open File"), this);
openFile->setStatusTip(tr("Open file"));
openFile->setIcon(QIcon(":/images/open-file.png"));
connect(openFile, SIGNAL(triggered()), this, SLOT(openFileSlot()));
exitAction = new QAction(tr("E&xit"), this);
exitAction->setShortcut(tr("Ctrl+Q"));
exitAction->setStatusTip(tr("Exit the application"));
connect(exitAction, &QAction::triggered, qApp, [this]() {
Command cmd("gui_stop; exit");
GlobalSession->CmdStack()->push_and_exec(&cmd);
});
}
void MainWindow::gui_start() { ReShowWindow(""); }
void MainWindow::ReShowWindow(QString strProject) {
clearDockWidgets();
takeCentralWidget();
setWindowTitle(tr(mainWindowName.c_str()) + " - " + strProject);
QDockWidget* sourceDockWidget = new QDockWidget(tr("Source"), this);
sourceDockWidget->setObjectName("sourcedockwidget");
SourcesForm* sourForm = new SourcesForm(strProject, this);
sourceDockWidget->setWidget(sourForm);
addDockWidget(Qt::LeftDockWidgetArea, sourceDockWidget);
QDockWidget* runDockWidget = new QDockWidget(tr("Design Runs"), this);
runDockWidget->setObjectName("sourcedockwidget");
RunsForm* runForm = new RunsForm(strProject, this);
runDockWidget->setWidget(runForm);
TextEditor* textEditor = new TextEditor(this);
textEditor->RegisterCommands(GlobalSession);
textEditor->setObjectName("textEditor");
connect(sourForm, SIGNAL(OpenFile(QString)), textEditor,
SLOT(SlotOpenFile(QString)));
connect(textEditor, SIGNAL(CurrentFileChanged(QString)), sourForm,
SLOT(SetCurrentFileItem(QString)));
QWidget* centralWidget = new QWidget(this);
QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(textEditor->GetTextEditor());
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
// console
QDockWidget* consoleDocWidget = new QDockWidget(tr("Console"), this);
consoleDocWidget->setObjectName("consoledocwidget");
StreamBuffer* buffer = new StreamBuffer;
auto tclConsole = std::make_unique<FOEDAG::TclConsole>(
m_interpreter->getInterp(), buffer->getStream());
FOEDAG::TclConsole* c = tclConsole.get();
TclConsoleWidget* console{nullptr};
QWidget* w =
FOEDAG::createConsole(m_interpreter->getInterp(), std::move(tclConsole),
buffer, nullptr, &console);
consoleDocWidget->setWidget(w);
connect(console, &TclConsoleWidget::linkActivated, textEditor,
&TextEditor::SlotOpenFile);
console->addParser(new DummyParser{});
// Register fake compiler until openFPGA gets available
std::string design("Some cool design");
FOEDAG::Compiler* com = new FOEDAG::Compiler{
m_interpreter, new FOEDAG::Design(design), buffer->getStream(),
new FOEDAG::CompilerNotifier{c}};
com->RegisterCommands(m_interpreter, false);
addDockWidget(Qt::BottomDockWidgetArea, consoleDocWidget);
tabifyDockWidget(consoleDocWidget, runDockWidget);
TaskManager* taskManager = new TaskManager;
TaskModel* model = new TaskModel{taskManager};
TaskTableView* view = new TaskTableView;
view->setModel(model);
QDockWidget* taskDocWidget = new QDockWidget(tr("Task"), this);
taskDocWidget->setWidget(view);
tabifyDockWidget(sourceDockWidget, taskDocWidget);
com->setTaskManager(taskManager);
}
void MainWindow::clearDockWidgets() {
auto docks = findChildren<QDockWidget*>();
for (auto dock : docks) {
removeDockWidget(dock);
}
}
| 33.509506 | 78 | 0.719846 | [
"model"
] |
d25f851b8570941200a8c309df7b639287da3199 | 29,404 | cpp | C++ | Modules/DiffusionCmdApps/Tractography/StreamlineTractography.cpp | MIC-DKFZ/MITK-Diffusion | 58b42eb2204e9f127900ff7890314307d26e9921 | [
"BSD-3-Clause"
] | 37 | 2019-07-05T10:55:06.000Z | 2022-03-21T12:09:35.000Z | Modules/DiffusionCmdApps/Tractography/StreamlineTractography.cpp | MIC-DKFZ/MITK-Diffusion | 58b42eb2204e9f127900ff7890314307d26e9921 | [
"BSD-3-Clause"
] | 6 | 2019-11-04T16:05:47.000Z | 2022-03-22T15:53:31.000Z | Modules/DiffusionCmdApps/Tractography/StreamlineTractography.cpp | MIC-DKFZ/MITK-Diffusion | 58b42eb2204e9f127900ff7890314307d26e9921 | [
"BSD-3-Clause"
] | 10 | 2019-10-15T14:37:26.000Z | 2022-02-18T03:22:01.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkBaseData.h>
#include <mitkImageCast.h>
#include <mitkImageToItk.h>
#include <metaCommand.h>
#include <mitkDiffusionCommandLineParser.h>
#include <mitkLog.h>
#include <usAny.h>
#include <mitkIOUtil.h>
#include <iostream>
#include <fstream>
#include <itksys/SystemTools.hxx>
#include <mitkCoreObjectFactory.h>
#include <itksys/SystemTools.hxx>
#include <mitkFiberBundle.h>
#include <itkStreamlineTrackingFilter.h>
#include <Algorithms/TrackingHandlers/mitkTrackingDataHandler.h>
#include <Algorithms/TrackingHandlers/mitkTrackingHandlerRandomForest.h>
#include <Algorithms/TrackingHandlers/mitkTrackingHandlerPeaks.h>
#include <Algorithms/TrackingHandlers/mitkTrackingHandlerTensor.h>
#include <Algorithms/TrackingHandlers/mitkTrackingHandlerOdf.h>
#include <itkTensorImageToOdfImageFilter.h>
#include <mitkTractographyForest.h>
#include <mitkPreferenceListReaderOptionsFunctor.h>
#include <mitkStreamlineTractographyParameters.h>
#define _USE_MATH_DEFINES
#include <math.h>
const int numOdfSamples = 200;
typedef itk::Image< itk::Vector< float, numOdfSamples > , 3 > SampledShImageType;
/*!
\brief
*/
int main(int argc, char* argv[])
{
mitkDiffusionCommandLineParser parser;
parser.setTitle("Streamline Tractography");
parser.setCategory("Fiber Tracking and Processing Methods");
parser.setDescription("Perform streamline tractography");
parser.setContributor("MIC");
// parameters fo all methods
parser.setArgumentPrefix("--", "-");
parser.beginGroup("1. Mandatory arguments:");
parser.addArgument("", "i", mitkDiffusionCommandLineParser::StringList, "Input:", "input image (multiple possible for 'DetTensor' algorithm)", us::Any(), false, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("", "o", mitkDiffusionCommandLineParser::String, "Output:", "output fiberbundle/probability map", us::Any(), false, false, false, mitkDiffusionCommandLineParser::Output);
parser.addArgument("type", "", mitkDiffusionCommandLineParser::String, "Type:", "which tracker to use (Peaks; Tensor; ODF; ODF-DIPY/FSL; RF)", us::Any(), false);
parser.addArgument("probabilistic", "", mitkDiffusionCommandLineParser::Bool, "Probabilistic:", "Probabilistic tractography", us::Any(false));
parser.endGroup();
parser.beginGroup("2. Seeding:");
parser.addArgument("seeds", "", mitkDiffusionCommandLineParser::Int, "Seeds per voxel:", "number of seed points per voxel", 1);
parser.addArgument("seed_image", "", mitkDiffusionCommandLineParser::String, "Seed image:", "mask image defining seed voxels", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("trials_per_seed", "", mitkDiffusionCommandLineParser::Int, "Max. trials per seed:", "try each seed N times until a valid streamline is obtained (only for probabilistic tractography)", 10);
parser.addArgument("max_tracts", "", mitkDiffusionCommandLineParser::Int, "Max. number of tracts:", "tractography is stopped if the reconstructed number of tracts is exceeded", -1);
parser.endGroup();
parser.beginGroup("3. Tractography constraints:");
parser.addArgument("tracking_mask", "", mitkDiffusionCommandLineParser::String, "Mask image:", "streamlines leaving the mask will stop immediately", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("stop_image", "", mitkDiffusionCommandLineParser::String, "Stop ROI image:", "streamlines entering the mask will stop immediately", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("exclusion_image", "", mitkDiffusionCommandLineParser::String, "Exclusion ROI image:", "streamlines entering the mask will be discarded", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("ep_constraint", "", mitkDiffusionCommandLineParser::String, "Endpoint constraint:", "determines which fibers are accepted based on their endpoint location - options are NONE, EPS_IN_TARGET, EPS_IN_TARGET_LABELDIFF, EPS_IN_SEED_AND_TARGET, MIN_ONE_EP_IN_TARGET, ONE_EP_IN_TARGET and NO_EP_IN_TARGET", us::Any());
parser.addArgument("target_image", "", mitkDiffusionCommandLineParser::String, "Target ROI image:", "effact depends on the chosen endpoint constraint (option ep_constraint)", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.endGroup();
parser.beginGroup("4. Streamline integration parameters:");
parser.addArgument("sharpen_odfs", "", mitkDiffusionCommandLineParser::Bool, "SHarpen ODFs:", "if you are using dODF images as input, it is advisable to sharpen the ODFs (min-max normalize and raise to the power of 4). this is not necessary for CSD fODFs, since they are narurally much sharper.");
parser.addArgument("cutoff", "", mitkDiffusionCommandLineParser::Float, "Cutoff:", "set the FA, GFA or Peak amplitude cutoff for terminating tracks", 0.1);
parser.addArgument("odf_cutoff", "", mitkDiffusionCommandLineParser::Float, "ODF Cutoff:", "threshold on the ODF magnitude. this is useful in case of CSD fODF tractography.", 0.0);
parser.addArgument("step_size", "", mitkDiffusionCommandLineParser::Float, "Step size:", "step size (in voxels)", 0.5);
parser.addArgument("min_tract_length", "", mitkDiffusionCommandLineParser::Float, "Min. tract length:", "minimum fiber length (in mm)", 20);
parser.addArgument("angular_threshold", "", mitkDiffusionCommandLineParser::Float, "Angular threshold:", "angular threshold between two successive steps, (default: 90° * step_size, minimum 15°)");
parser.addArgument("loop_check", "", mitkDiffusionCommandLineParser::Float, "Check for loops:", "threshold on angular stdev over the last 4 voxel lengths");
parser.addArgument("peak_jitter", "", mitkDiffusionCommandLineParser::Float, "Peak jitter:", "important for probabilistic peak tractography and peak prior. actual jitter is drawn from a normal distribution with peak_jitter*fabs(direction_value) as standard deviation.", 0.01);
parser.endGroup();
parser.beginGroup("5. Tractography prior:");
parser.addArgument("prior_image", "", mitkDiffusionCommandLineParser::String, "Peak prior:", "tractography prior in thr for of a peak image", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("prior_weight", "", mitkDiffusionCommandLineParser::Float, "Prior weight", "weighting factor between prior and data.", 0.5);
parser.addArgument("dont_restrict_to_prior", "", mitkDiffusionCommandLineParser::Bool, "Don't restrict to prior:", "don't restrict tractography to regions where the prior is valid.", us::Any(false));
parser.addArgument("no_new_directions_from_prior", "", mitkDiffusionCommandLineParser::Bool, "No new directios from prior:", "the prior cannot create directions where there are none in the data.", us::Any(false));
parser.addArgument("prior_flip_x", "", mitkDiffusionCommandLineParser::Bool, "Prior Flip X:", "multiply x-coordinate of prior direction by -1");
parser.addArgument("prior_flip_y", "", mitkDiffusionCommandLineParser::Bool, "Prior Flip Y:", "multiply y-coordinate of prior direction by -1");
parser.addArgument("prior_flip_z", "", mitkDiffusionCommandLineParser::Bool, "Prior Flip Z:", "multiply z-coordinate of prior direction by -1");
parser.endGroup();
parser.beginGroup("6. Neighborhood sampling:");
parser.addArgument("num_samples", "", mitkDiffusionCommandLineParser::Int, "Num. neighborhood samples:", "number of neighborhood samples that are use to determine the next progression direction", 0);
parser.addArgument("sampling_distance", "", mitkDiffusionCommandLineParser::Float, "Sampling distance:", "distance of neighborhood sampling points (in voxels)", 0.25);
parser.addArgument("use_stop_votes", "", mitkDiffusionCommandLineParser::Bool, "Use stop votes:", "use stop votes");
parser.addArgument("use_only_forward_samples", "", mitkDiffusionCommandLineParser::Bool, "Use only forward samples:", "use only forward samples");
parser.endGroup();
parser.beginGroup("7. Tensor tractography specific:");
parser.addArgument("tend_f", "", mitkDiffusionCommandLineParser::Float, "Weight f", "weighting factor between first eigenvector (f=1 equals FACT tracking) and input vector dependent direction (f=0).", 1.0);
parser.addArgument("tend_g", "", mitkDiffusionCommandLineParser::Float, "Weight g", "weighting factor between input vector (g=0) and tensor deflection (g=1 equals TEND tracking)", 0.0);
parser.endGroup();
parser.beginGroup("8. Random forest tractography specific:");
parser.addArgument("forest", "", mitkDiffusionCommandLineParser::String, "Forest:", "input random forest (HDF5 file)", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.addArgument("use_sh_features", "", mitkDiffusionCommandLineParser::Bool, "Use SH features:", "use SH features");
parser.endGroup();
parser.beginGroup("9. Additional input:");
parser.addArgument("additional_images", "", mitkDiffusionCommandLineParser::StringList, "Additional images:", "specify a list of float images that hold additional information (FA, GFA, additional features for RF tractography)", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.endGroup();
parser.beginGroup("10. Misc:");
parser.addArgument("flip_x", "", mitkDiffusionCommandLineParser::Bool, "Flip X:", "multiply x-coordinate of direction proposal by -1");
parser.addArgument("flip_y", "", mitkDiffusionCommandLineParser::Bool, "Flip Y:", "multiply y-coordinate of direction proposal by -1");
parser.addArgument("flip_z", "", mitkDiffusionCommandLineParser::Bool, "Flip Z:", "multiply z-coordinate of direction proposal by -1");
parser.addArgument("no_data_interpolation", "", mitkDiffusionCommandLineParser::Bool, "Don't interpolate input data:", "don't interpolate input image values");
parser.addArgument("no_mask_interpolation", "", mitkDiffusionCommandLineParser::Bool, "Don't interpolate masks:", "don't interpolate mask image values");
parser.addArgument("compress", "", mitkDiffusionCommandLineParser::Bool, "Compress:", "compress output fibers (lossy)");
parser.addArgument("fix_seed", "", mitkDiffusionCommandLineParser::Bool, "Fix Random Seed:", "always use the same random numbers");
parser.addArgument("parameter_file", "", mitkDiffusionCommandLineParser::String, "Parameter File:", "load parameters from json file (svae using MITK Diffusion GUI). the parameters loaded form this file are overwritten by the manually set parameters.", us::Any(), true, false, false, mitkDiffusionCommandLineParser::Input);
parser.endGroup();
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
mitkDiffusionCommandLineParser::StringContainerType input_files = us::any_cast<mitkDiffusionCommandLineParser::StringContainerType>(parsedArgs["i"]);
std::string outFile = us::any_cast<std::string>(parsedArgs["o"]);
std::string type = us::any_cast<std::string>(parsedArgs["type"]);
std::shared_ptr< mitk::StreamlineTractographyParameters > params = std::make_shared<mitk::StreamlineTractographyParameters>();
if (parsedArgs.count("parameter_file"))
{
auto parameter_file = us::any_cast<std::string>(parsedArgs["parameter_file"]);
params->LoadParameters(parameter_file);
}
if (parsedArgs.count("probabilistic"))
params->m_Mode = mitk::StreamlineTractographyParameters::MODE::PROBABILISTIC;
else {
params->m_Mode = mitk::StreamlineTractographyParameters::MODE::DETERMINISTIC;
}
std::string prior_image = "";
if (parsedArgs.count("prior_image"))
prior_image = us::any_cast<std::string>(parsedArgs["prior_image"]);
if (parsedArgs.count("prior_weight"))
params->m_Weight = us::any_cast<float>(parsedArgs["prior_weight"]);
if (parsedArgs.count("fix_seed"))
params->m_FixRandomSeed = us::any_cast<bool>(parsedArgs["fix_seed"]);
if (parsedArgs.count("dont_restrict_to_prior"))
params->m_RestrictToPrior = !us::any_cast<bool>(parsedArgs["dont_restrict_to_prior"]);
if (parsedArgs.count("no_new_directions_from_prior"))
params->m_NewDirectionsFromPrior = !us::any_cast<bool>(parsedArgs["no_new_directions_from_prior"]);
if (parsedArgs.count("sharpen_odfs"))
params->m_SharpenOdfs = us::any_cast<bool>(parsedArgs["sharpen_odfs"]);
if (parsedArgs.count("no_data_interpolation"))
params->m_InterpolateTractographyData = !us::any_cast<bool>(parsedArgs["no_data_interpolation"]);
params->m_InterpolateRoiImages = true;
if (parsedArgs.count("no_mask_interpolation"))
params->m_InterpolateRoiImages = !us::any_cast<bool>(parsedArgs["no_mask_interpolation"]);
bool use_sh_features = false;
if (parsedArgs.count("use_sh_features"))
use_sh_features = us::any_cast<bool>(parsedArgs["use_sh_features"]);
if (parsedArgs.count("use_stop_votes"))
params->m_StopVotes = us::any_cast<bool>(parsedArgs["use_stop_votes"]);
if (parsedArgs.count("use_only_forward_samples"))
params->m_OnlyForwardSamples = us::any_cast<bool>(parsedArgs["use_only_forward_samples"]);
if (parsedArgs.count("flip_x"))
params->m_FlipX = us::any_cast<bool>(parsedArgs["flip_x"]);
if (parsedArgs.count("flip_y"))
params->m_FlipY = us::any_cast<bool>(parsedArgs["flip_y"]);
if (parsedArgs.count("flip_z"))
params->m_FlipZ = us::any_cast<bool>(parsedArgs["flip_z"]);
if (parsedArgs.count("prior_flip_x"))
params->m_PriorFlipX = us::any_cast<bool>(parsedArgs["prior_flip_x"]);
if (parsedArgs.count("prior_flip_y"))
params->m_PriorFlipY = us::any_cast<bool>(parsedArgs["prior_flip_y"]);
if (parsedArgs.count("prior_flip_z"))
params->m_PriorFlipZ = us::any_cast<bool>(parsedArgs["prior_flip_z"]);
if (parsedArgs.count("apply_image_rotation"))
params->m_ApplyDirectionMatrix = us::any_cast<bool>(parsedArgs["apply_image_rotation"]);
if (parsedArgs.count("compress"))
params->m_CompressFibers = us::any_cast<bool>(parsedArgs["compress"]);
if (parsedArgs.count("min_tract_length"))
params->m_MinTractLengthMm = us::any_cast<float>(parsedArgs["min_tract_length"]);
if (parsedArgs.count("loop_check"))
params->SetLoopCheckDeg(us::any_cast<float>(parsedArgs["loop_check"]));
std::string forestFile;
if (parsedArgs.count("forest"))
forestFile = us::any_cast<std::string>(parsedArgs["forest"]);
std::string maskFile = "";
if (parsedArgs.count("tracking_mask"))
maskFile = us::any_cast<std::string>(parsedArgs["tracking_mask"]);
std::string seedFile = "";
if (parsedArgs.count("seed_image"))
seedFile = us::any_cast<std::string>(parsedArgs["seed_image"]);
std::string targetFile = "";
if (parsedArgs.count("target_image"))
targetFile = us::any_cast<std::string>(parsedArgs["target_image"]);
std::string exclusionFile = "";
if (parsedArgs.count("exclusion_image"))
exclusionFile = us::any_cast<std::string>(parsedArgs["exclusion_image"]);
std::string stopFile = "";
if (parsedArgs.count("stop_image"))
stopFile = us::any_cast<std::string>(parsedArgs["stop_image"]);
if (parsedArgs.count("ep_constraint"))
{
if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "NONE")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::NONE;
else if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "EPS_IN_TARGET")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::EPS_IN_TARGET;
else if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "EPS_IN_TARGET_LABELDIFF")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::EPS_IN_TARGET_LABELDIFF;
else if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "EPS_IN_SEED_AND_TARGET")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::EPS_IN_SEED_AND_TARGET;
else if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "MIN_ONE_EP_IN_TARGET")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::MIN_ONE_EP_IN_TARGET;
else if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "ONE_EP_IN_TARGET")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::ONE_EP_IN_TARGET;
else if (us::any_cast<std::string>(parsedArgs["ep_constraint"]) == "NO_EP_IN_TARGET")
params->m_EpConstraints = mitk::StreamlineTractographyParameters::EndpointConstraints::NO_EP_IN_TARGET;
}
if (parsedArgs.count("cutoff"))
params->m_Cutoff = us::any_cast<float>(parsedArgs["cutoff"]);
if (parsedArgs.count("odf_cutoff"))
params->m_OdfCutoff = us::any_cast<float>(parsedArgs["odf_cutoff"]);
if (parsedArgs.count("peak_jitter"))
params->m_PeakJitter = us::any_cast<float>(parsedArgs["peak_jitter"]);
if (parsedArgs.count("step_size"))
params->SetStepSizeVox(us::any_cast<float>(parsedArgs["step_size"]));
if (parsedArgs.count("sampling_distance"))
params->SetSamplingDistanceVox(us::any_cast<float>(parsedArgs["sampling_distance"]));
if (parsedArgs.count("num_samples"))
params->m_NumSamples = static_cast<unsigned int>(us::any_cast<int>(parsedArgs["num_samples"]));
if (parsedArgs.count("seeds"))
params->m_SeedsPerVoxel = us::any_cast<int>(parsedArgs["seeds"]);
if (parsedArgs.count("trials_per_seed"))
params->m_TrialsPerSeed = static_cast<unsigned int>(us::any_cast<int>(parsedArgs["trials_per_seed"]));
if (parsedArgs.count("tend_f"))
params->m_F = us::any_cast<float>(parsedArgs["tend_f"]);
if (parsedArgs.count("tend_g"))
params->m_G = us::any_cast<float>(parsedArgs["tend_g"]);
if (parsedArgs.count("angular_threshold"))
params->SetAngularThresholdDeg(us::any_cast<float>(parsedArgs["angular_threshold"]));
if (parsedArgs.count("max_tracts"))
params->m_MaxNumFibers = us::any_cast<int>(parsedArgs["max_tracts"]);
std::string ext = itksys::SystemTools::GetFilenameExtension(outFile);
if (ext != ".fib" && ext != ".trk")
{
MITK_INFO << "Output file format not supported. Use one of .fib, .trk, .nii, .nii.gz, .nrrd";
return EXIT_FAILURE;
}
// LOAD DATASETS
mitkDiffusionCommandLineParser::StringContainerType addFiles;
if (parsedArgs.count("additional_images"))
addFiles = us::any_cast<mitkDiffusionCommandLineParser::StringContainerType>(parsedArgs["additional_images"]);
typedef itk::Image<float, 3> ItkFloatImgType;
ItkFloatImgType::Pointer mask = nullptr;
if (!maskFile.empty())
{
MITK_INFO << "loading mask image";
mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(maskFile);
mask = ItkFloatImgType::New();
mitk::CastToItkImage(img, mask);
}
ItkFloatImgType::Pointer seed = nullptr;
if (!seedFile.empty())
{
MITK_INFO << "loading seed ROI image";
mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(seedFile);
seed = ItkFloatImgType::New();
mitk::CastToItkImage(img, seed);
}
ItkFloatImgType::Pointer stop = nullptr;
if (!stopFile.empty())
{
MITK_INFO << "loading stop ROI image";
mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(stopFile);
stop = ItkFloatImgType::New();
mitk::CastToItkImage(img, stop);
}
ItkFloatImgType::Pointer target = nullptr;
if (!targetFile.empty())
{
MITK_INFO << "loading target ROI image";
mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(targetFile);
target = ItkFloatImgType::New();
mitk::CastToItkImage(img, target);
}
ItkFloatImgType::Pointer exclusion = nullptr;
if (!exclusionFile.empty())
{
MITK_INFO << "loading exclusion ROI image";
mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(exclusionFile);
exclusion = ItkFloatImgType::New();
mitk::CastToItkImage(img, exclusion);
}
MITK_INFO << "loading additional images";
std::vector< std::vector< ItkFloatImgType::Pointer > > addImages;
addImages.push_back(std::vector< ItkFloatImgType::Pointer >());
for (auto file : addFiles)
{
mitk::Image::Pointer img = mitk::IOUtil::Load<mitk::Image>(file);
ItkFloatImgType::Pointer itkimg = ItkFloatImgType::New();
mitk::CastToItkImage(img, itkimg);
addImages.at(0).push_back(itkimg);
}
// //////////////////////////////////////////////////////////////////
// omp_set_num_threads(1);
typedef itk::StreamlineTrackingFilter TrackerType;
TrackerType::Pointer tracker = TrackerType::New();
if (!prior_image.empty())
{
mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor({"Peak Image"}, std::vector<std::string>());
mitk::PeakImage::Pointer priorImage = mitk::IOUtil::Load<mitk::PeakImage>(prior_image, &functor);
if (priorImage.IsNull())
{
MITK_INFO << "Only peak images are supported as prior at the moment!";
return EXIT_FAILURE;
}
mitk::TrackingDataHandler* priorhandler = new mitk::TrackingHandlerPeaks();
typedef mitk::ImageToItk< mitk::TrackingHandlerPeaks::PeakImgType > CasterType;
CasterType::Pointer caster = CasterType::New();
caster->SetInput(priorImage);
caster->Update();
mitk::TrackingHandlerPeaks::PeakImgType::Pointer itkImg = caster->GetOutput();
std::shared_ptr< mitk::StreamlineTractographyParameters > prior_params = std::make_shared< mitk::StreamlineTractographyParameters >(*params);
prior_params->m_FlipX = params->m_PriorFlipX;
prior_params->m_FlipY = params->m_PriorFlipY;
prior_params->m_FlipZ = params->m_PriorFlipZ;
prior_params->m_Cutoff = 0.0;
dynamic_cast<mitk::TrackingHandlerPeaks*>(priorhandler)->SetPeakImage(itkImg);
priorhandler->SetParameters(prior_params);
tracker->SetTrackingPriorHandler(priorhandler);
}
mitk::TrackingDataHandler* handler;
mitk::Image::Pointer reference_image;
if (type == "RF")
{
mitk::TractographyForest::Pointer forest = mitk::IOUtil::Load<mitk::TractographyForest>(forestFile);
if (forest.IsNull())
mitkThrow() << "Forest file " << forestFile << " could not be read.";
std::vector<std::string> include = {"Diffusion Weighted Images"};
std::vector<std::string> exclude = {};
mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(include, exclude);
auto input = mitk::IOUtil::Load<mitk::Image>(input_files.at(0), &functor);
reference_image = input;
if (use_sh_features)
{
handler = new mitk::TrackingHandlerRandomForest<6,28>();
dynamic_cast<mitk::TrackingHandlerRandomForest<6,28>*>(handler)->SetForest(forest);
dynamic_cast<mitk::TrackingHandlerRandomForest<6,28>*>(handler)->AddDwi(input);
dynamic_cast<mitk::TrackingHandlerRandomForest<6,28>*>(handler)->SetAdditionalFeatureImages(addImages);
}
else
{
handler = new mitk::TrackingHandlerRandomForest<6,100>();
dynamic_cast<mitk::TrackingHandlerRandomForest<6,100>*>(handler)->SetForest(forest);
dynamic_cast<mitk::TrackingHandlerRandomForest<6,100>*>(handler)->AddDwi(input);
dynamic_cast<mitk::TrackingHandlerRandomForest<6,100>*>(handler)->SetAdditionalFeatureImages(addImages);
}
}
else if (type == "Peaks")
{
handler = new mitk::TrackingHandlerPeaks();
MITK_INFO << "loading input peak image";
mitk::Image::Pointer mitkImage = mitk::IOUtil::Load<mitk::Image>(input_files.at(0));
reference_image = mitkImage;
mitk::TrackingHandlerPeaks::PeakImgType::Pointer itkImg = mitk::convert::GetItkPeakFromPeakImage(mitkImage);
dynamic_cast<mitk::TrackingHandlerPeaks*>(handler)->SetPeakImage(itkImg);
}
else if (type == "Tensor" && params->m_Mode == mitk::StreamlineTractographyParameters::MODE::DETERMINISTIC)
{
handler = new mitk::TrackingHandlerTensor();
MITK_INFO << "loading input tensor images";
std::vector< mitk::Image::Pointer > input_images;
for (unsigned int i=0; i<input_files.size(); i++)
{
mitk::Image::Pointer mitkImage = mitk::IOUtil::Load<mitk::Image>(input_files.at(i));
reference_image = mitkImage;
mitk::TensorImage::ItkTensorImageType::Pointer itkImg = mitk::convert::GetItkTensorFromTensorImage(mitkImage);
dynamic_cast<mitk::TrackingHandlerTensor*>(handler)->AddTensorImage(itkImg.GetPointer());
}
if (addImages.at(0).size()>0)
dynamic_cast<mitk::TrackingHandlerTensor*>(handler)->SetFaImage(addImages.at(0).at(0));
}
else if (type == "ODF" || type == "ODF-DIPY/FSL" || (type == "Tensor" && params->m_Mode == mitk::StreamlineTractographyParameters::MODE::PROBABILISTIC))
{
handler = new mitk::TrackingHandlerOdf();
mitk::OdfImage::ItkOdfImageType::Pointer itkImg = nullptr;
if (type == "Tensor")
{
MITK_INFO << "Converting Tensor to ODF image";
auto input = mitk::IOUtil::Load<mitk::Image>(input_files.at(0));
reference_image = input;
itkImg = mitk::convert::GetItkOdfFromTensorImage(input);
dynamic_cast<mitk::TrackingHandlerOdf*>(handler)->SetIsOdfFromTensor(true);
}
else
{
std::vector<std::string> include = {"SH Image", "ODF Image"};
std::vector<std::string> exclude = {};
mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(include, exclude);
auto input = mitk::IOUtil::Load(input_files.at(0), &functor)[0];
reference_image = dynamic_cast<mitk::Image*>(input.GetPointer());
if (dynamic_cast<mitk::ShImage*>(input.GetPointer()))
{
MITK_INFO << "Converting SH to ODF image";
mitk::ShImage::Pointer mitkShImage = dynamic_cast<mitk::ShImage*>(input.GetPointer());
if (type == "ODF-DIPY/FSL")
mitkShImage->SetShConvention(mitk::ShImage::SH_CONVENTION::FSL);
mitk::Image::Pointer mitkImg = dynamic_cast<mitk::Image*>(mitkShImage.GetPointer());
itkImg = mitk::convert::GetItkOdfFromShImage(mitkImg);
}
else if (dynamic_cast<mitk::OdfImage*>(input.GetPointer()))
{
mitk::Image::Pointer mitkImg = dynamic_cast<mitk::Image*>(input.GetPointer());
itkImg = mitk::convert::GetItkOdfFromOdfImage(mitkImg);
}
else
mitkThrow() << "";
}
dynamic_cast<mitk::TrackingHandlerOdf*>(handler)->SetOdfImage(itkImg);
if (addImages.at(0).size()>0)
dynamic_cast<mitk::TrackingHandlerOdf*>(handler)->SetGfaImage(addImages.at(0).at(0));
}
else
{
MITK_INFO << "Unknown tractography algorithm (" + type+"). Known types are Peaks, DetTensor, ProbTensor, DetODF, ProbODF, DetRF, ProbRF.";
return EXIT_FAILURE;
}
float max_size = 0;
for (int i=0; i<3; ++i)
if (reference_image->GetGeometry()->GetExtentInMM(i)>max_size)
max_size = reference_image->GetGeometry()->GetExtentInMM(i);
if (params->m_MinTractLengthMm >= max_size)
{
MITK_INFO << "Max. image size: " << max_size << "mm";
MITK_INFO << "Min. tract length: " << params->m_MinTractLengthMm << "mm";
MITK_ERROR << "Minimum tract length exceeds the maximum image extent! Recommended value is about 1/10 of the image extent.";
return EXIT_FAILURE;
}
else if (params->m_MinTractLengthMm > max_size/10)
{
MITK_INFO << "Max. image size: " << max_size << "mm";
MITK_INFO << "Min. tract length: " << params->m_MinTractLengthMm << "mm";
MITK_WARN << "Minimum tract length is larger than 1/10 the maximum image extent! Decrease recommended.";
}
MITK_INFO << "Tractography algorithm: " << type;
tracker->SetMaskImage(mask);
tracker->SetSeedImage(seed);
tracker->SetStoppingRegions(stop);
tracker->SetTargetRegions(target);
tracker->SetExclusionRegions(exclusion);
tracker->SetTrackingHandler(handler);
if (ext != ".fib" && ext != ".trk")
params->m_OutputProbMap = true;
tracker->SetParameters(params);
tracker->Update();
if (ext == ".fib" || ext == ".trk")
{
vtkSmartPointer< vtkPolyData > poly = tracker->GetFiberPolyData();
mitk::FiberBundle::Pointer outFib = mitk::FiberBundle::New(poly);
if (params->m_CompressFibers)
{
float min_sp = 999;
auto spacing = handler->GetSpacing();
if (spacing[0] < min_sp)
min_sp = spacing[0];
if (spacing[1] < min_sp)
min_sp = spacing[1];
if (spacing[2] < min_sp)
min_sp = spacing[2];
params->m_Compression = min_sp/10;
outFib->Compress(params->m_Compression);
}
outFib->SetTrackVisHeader(reference_image->GetGeometry());
mitk::IOUtil::Save(outFib, outFile);
}
else
{
TrackerType::ItkDoubleImgType::Pointer outImg = tracker->GetOutputProbabilityMap();
mitk::Image::Pointer img = mitk::Image::New();
img->InitializeByItk(outImg.GetPointer());
img->SetVolume(outImg->GetBufferPointer());
if (ext != ".nii" && ext != ".nii.gz" && ext != ".nrrd")
outFile += ".nii.gz";
mitk::IOUtil::Save(img, outFile);
}
delete handler;
return EXIT_SUCCESS;
}
| 50.435678 | 333 | 0.721637 | [
"vector"
] |
d92251efa2884bdf0113f96927290f41bc95a22d | 18,332 | cpp | C++ | chromosone.cpp | rcorbish/GenePool | a18b29689bae13e56abca6f03de9b6da22d62111 | [
"Unlicense"
] | null | null | null | chromosone.cpp | rcorbish/GenePool | a18b29689bae13e56abca6f03de9b6da22d62111 | [
"Unlicense"
] | null | null | null | chromosone.cpp | rcorbish/GenePool | a18b29689bae13e56abca6f03de9b6da22d62111 | [
"Unlicense"
] | null | null | null |
#include <Python.h>
#include <structmember.h>
#include <vector>
#include <cstring>
#include <stdlib.h> /* rand */
/********************************************************************
*
* C defintion for Python class
*
********************************************************************/
typedef struct {
PyObject_HEAD // no semicolon
size_t len;
size_t current;
u_int8_t *data;
} Chromosone ;
/*
* A helper method to turn the bits into an integer. This
* is not a public method
*/
uint64_t as_long( Chromosone *a ) {
uint64_t val = 0L ;
uint8_t *data = a->data + a->len - 1 ;
for( uint64_t mask = 1L ; data >= a->data ; mask<<=1, --data ) {
if( *data ) {
val += mask ;
}
}
return val ;
}
/*
* Given an instance of a Chromosone, set the data to the value
* of the given data.
*/
void set_long( Chromosone *self, uint64_t x, size_t len ) {
delete self->data ;
self->data = new uint8_t[len] ;
self->len = len ;
// self->current = 0 ;
uint64_t mask = 1L << (len - 1) ;
for( size_t i=0 ; i<len ; ++i, mask >>= 1 ) {
self->data[i] = ( x & mask ) ? 1 : 0 ;
}
}
/*
* Create a new instance of a Chromosone (or a subtype thereof) and
* initialize its data & size to the values given.
*/
Chromosone *from_long( PyTypeObject *type, uint64_t x, size_t len ) {
Chromosone *self = (Chromosone *)type->tp_alloc( type, 0 ) ;
set_long( self, x, len ) ;
return self ;
}
/********************************************************************
*
* Allocation/deallocation & __init__ definitions
*
********************************************************************/
static void Chromosone_dealloc(Chromosone *self) {
delete self->data ;
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *Chromosone_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
Chromosone *self;
self = (Chromosone *)type->tp_alloc(type, 0);
self->data = NULL ;
self->len = 0 ;
self->current = 0 ;
return (PyObject *)self;
}
static int Chromosone_init(Chromosone *self, PyObject *args, PyObject *kwds) {
int argc = PyTuple_GET_SIZE( args ) ;
if( argc > 1 ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_Exception, "Constructor accepts a single argument" ) ;
PyGILState_Release(gstate);
return 1 ;
}
PyObject *arg = PyTuple_GET_ITEM( args, 0 ) ;
if( PyLong_Check( arg ) ) {
long l = PyLong_AsLong( arg ) ;
set_long( self, l, CHAR_BIT*SIZEOF_LONG ) ;
} else if( PyUnicode_Check( arg ) ) {
long l = 0L ;
long mask = 1L ;
size_t len = PyUnicode_GET_SIZE( arg ) ;
Py_UNICODE *s = PyUnicode_AS_UNICODE( arg ) ;
for( int i=len - 1 ; i>=0 ; --i ) {
if( s[i] != '0' ) l+= mask ;
mask <<= 1 ;
}
set_long( self, l, len ) ;
} else if( PyBytes_Check( arg ) ) {
long l = 0L ;
long mask = 1L ;
size_t len = PyBytes_GET_SIZE( arg ) ;
char *s = PyBytes_AsString( arg ) ;
for( int i=len - 1 ; i>=0 ; --i ) {
if( s[i] != '0' ) l+= mask ;
mask <<= 1 ;
}
set_long( self, l, len ) ;
} else if( PyObject_TypeCheck( arg, Py_TYPE(self) ) ) {
Chromosone *other = (Chromosone*)arg ;
long l = as_long( other ) ;
set_long( self, l, other->len ) ;
} else {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_Exception, "Constructor has invalid argument type" ) ;
PyGILState_Release(gstate);
return 1 ;
}
return 0;
}
/********************************************************************
*
* Member attributes exposed from C definition
*
********************************************************************/
static PyMemberDef Chromosone_members[] = {
{ "capacity", T_PYSSIZET, offsetof(Chromosone, len) , READONLY, "The maximum capacity of the buffer" },
{NULL, 0, 0, 0, NULL}
};
/********************************************************************
*
* Printing type functions
*
********************************************************************/
static PyObject *Chromosone_repr( Chromosone *self ) {
uint64_t l = as_long( self ) ;
uint64_t mask = 1L << ( self->len - 1 ) ;
char rc[ self-> len + 1] ;
for( size_t i=0 ; i<self->len ; i++, mask >>= 1L ) {
rc[i] = ( l & mask ) ? '1' : '0' ;
}
rc[self->len] = 0 ;
return Py_BuildValue( "s", rc ) ;
};
/********************************************************************
*
* Mapping Methods
*
* Used to implement a dictionary
*
* __len__ len(a)
* __getitem__ a[x]
* __setitem__ a[x] = y
*
********************************************************************/
static int Chromosone_len(Chromosone *self) {
return self->len ;
}
static PyObject* Chromosone_getitem(Chromosone *self, PyObject *ix ) {
size_t index = PyLong_AsSize_t( ix ) ;
if( index >= self->len ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_IndexError, "Out of bounds!" ) ;
PyGILState_Release(gstate);
return 0 ;
}
uint64_t l = as_long( self ) ;
uint64_t mask = 1L << ( self->len - index - 1 ) ;
return PyLong_FromLong( ( l & mask ) ? 1 : 0 ) ;
}
static int Chromosone_setitem(Chromosone *self, PyObject *ix, PyObject *val ) {
size_t index = PyLong_AsSize_t( ix ) ;
if( index >= self->len ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_IndexError, "Out of bounds!" ) ;
PyGILState_Release(gstate);
return 0 ;
}
int v = PyLong_AsLong( val ) ;
// self->data[index] = v ;
uint64_t l = as_long( self ) ;
uint64_t mask = 1L << ( self->len - index - 1 ) ;
if( v == 0 ) {
l &= ~mask ;
} else {
l |= mask ;
}
set_long( self, l, self->len ) ;
return 0 ;
}
static PyMappingMethods Chromosone_mappings = {
(lenfunc)Chromosone_len,
(binaryfunc)Chromosone_getitem,
(objobjargproc)Chromosone_setitem
};
/********************************************************************
*
* Regular Methods
*
********************************************************************/
static PyObject *mutate( Chromosone *self, PyObject *args ) {
double probability ;
int argc = PyTuple_GET_SIZE( args ) ;
if( argc == 0 ) {
probability = 0.05 ;
} else if ( !PyArg_ParseTuple(args, "d", &probability)) {
Py_RETURN_NONE ;
}
if( probability > 0 ) {
u_int64_t mask = 0 ;
for( size_t i=0 ; i<self->len ; ++i ) {
double r = drand48() ;
if( r < probability ) {
mask |= 1 ;
}
mask <<= 1 ;
}
u_int64_t l = as_long( self ) ;
l ^= mask ;
set_long( self, l, self->len ) ;
}
Py_RETURN_NONE ;
}
static PyObject *countOnes( Chromosone *self ) {
u_int64_t l = as_long( self ) ;
long rc = 0 ;
for( rc = 0; l > 0; ++rc) {
l &= l - 1;
}
return PyLong_FromLong( rc ) ;
}
static PyObject *countZeros( Chromosone *self ) {
u_int64_t l = as_long( self ) ;
long rc = 0 ;
for( rc = 0; l > 0; ++rc) {
l &= l - 1;
}
return PyLong_FromLong( self->len - rc ) ;
}
static PyObject *new_random( PyTypeObject *type, PyObject *args, PyObject *kwds ) {
int length = -1 ;
// int argc = PyTuple_GET_SIZE( args ) ;
PyObject *arg = PyTuple_GET_ITEM( args, 0 ) ;
if( PyLong_Check( arg ) ) {
length = PyLong_AsLong( arg ) ;
} else {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_Exception, "Random needs 1 numeric argument." ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
uint64_t mask = ( 1L << length ) - 1L ;
uint64_t l = mask & random() ;
Chromosone *self = (Chromosone *)type->tp_alloc( type, 0 ) ;
set_long( self, l, length ) ;
return (PyObject*)self ;
}
static PyObject *from_parents( PyTypeObject *type, PyObject *args ) {
int argc = PyTuple_GET_SIZE( args ) ;
std::vector<bool> tmp_data ;
PyObject *arg1 = PyTuple_GET_ITEM( args, 0 ) ;
PyObject *arg2 = PyTuple_GET_ITEM( args, 1 ) ;
if( argc != 2 ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_Exception, "Require 2 arguments of Chromosone types." ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
if( !PyObject_TypeCheck( arg1, type ) || !PyObject_TypeCheck( arg2, type ) ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_Exception, "Require 2 arguments of Chromosone types." ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
Chromosone *p1 = (Chromosone*)arg1 ;
Chromosone *p2 = (Chromosone*)arg2 ;
if( p1->len != p2->len ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_Exception, "Require 2 arguments of Chromosone types, of the same size." ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
Chromosone *self = (Chromosone *)type->tp_alloc( type, 0 ) ;
u_int64_t l1 = as_long( p1 ) ;
u_int64_t l2 = as_long( p2 ) ;
u_int64_t mask = 1L ;
u_int64_t x = 0 ;
for( size_t i=0 ; i<p1->len ; ++i, mask <<= 1 ) {
x |= ( mask & ( drand48() < 0.5 ? l1 : l2) ) ;
}
set_long( self, x, p1->len ) ;
return (PyObject*)self ;
}
static PyMethodDef Chromosone_methods[] = {
{"mutate", (PyCFunction)mutate, METH_VARARGS, "Randomly change bits in the chromosone. Input is chance per bit mutation"},
{"countOnes", (PyCFunction)countOnes, METH_NOARGS, "Count number of ones in the data"},
{"countZeros", (PyCFunction)countZeros, METH_NOARGS, "Count number of zeros in the data"},
{"random", (PyCFunction)new_random, METH_CLASS | METH_VARARGS, "Create a new instance initialized at random of a given length"},
{"from_parents", (PyCFunction)from_parents, METH_CLASS | METH_VARARGS, "Create a new instance inherited from 2 parents' genes"},
{NULL, NULL, 0, NULL}
};
/********************************************************************
*
* Number Methods
*
********************************************************************/
static PyObject *nb_and( Chromosone *a, Chromosone *b ) {
if( a->len != b->len ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_IndexError, "Mismatched data length for bitwise operation" ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
uint64_t la = as_long( a ) ;
uint64_t lb = as_long( b ) ;
uint64_t res = lb & la ;
PyTypeObject *type = Py_TYPE( a ) ;
Chromosone *self = from_long( type, res, a->len ) ;
return (PyObject *)self ;
}
static PyObject *nb_or( Chromosone *a, Chromosone *b ) {
if( a->len != b->len ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_IndexError, "Mismatched data length for bitwise operation" ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
uint64_t la = as_long( a ) ;
uint64_t lb = as_long( b ) ;
uint64_t res = lb | la ;
PyTypeObject *type = Py_TYPE( a ) ;
Chromosone *self = from_long( type, res, a->len ) ;
return (PyObject *)self ;
}
static PyObject *nb_xor( Chromosone *a, Chromosone *b ) {
if( a->len != b->len ) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_IndexError, "Mismatched data length for bitwise operation" ) ;
PyGILState_Release(gstate);
Py_RETURN_NONE ;
}
uint64_t la = as_long( a ) ;
uint64_t lb = as_long( b ) ;
uint64_t res = lb ^ la ;
PyTypeObject *type = Py_TYPE( a ) ;
Chromosone *self = from_long( type, res, a->len ) ;
return (PyObject *)self ;
}
static PyObject *nb_inplace_and( Chromosone *a, Chromosone *b ) {
for( size_t i=0 ; i<a->len ; ++i ) {
a->data[i] &= b->data[i] ;
}
return (PyObject *)a ;
}
static PyObject *nb_inplace_or( Chromosone *a, Chromosone *b ) {
for( size_t i=0 ; i<a->len ; ++i ) {
a->data[i] |= b->data[i] ;
}
return (PyObject *)a ;
}
static PyObject *nb_inplace_xor( Chromosone *a, Chromosone *b ) {
for( size_t i=0 ; i<a->len ; ++i ) {
a->data[i] ^= b->data[i] ;
}
return (PyObject *)a ;
}
static int nb_bool( Chromosone *a ) {
uint64_t rc = as_long( a ) ;
return rc != 0L ;
}
static PyObject *nb_invert( Chromosone *a ) {
uint64_t la = as_long( a ) ;
uint64_t res = ~la ;
PyTypeObject *type = Py_TYPE( a ) ;
Chromosone *self = from_long( type, res, a->len ) ;
return (PyObject *)self ;
}
static PyObject *nb_long( Chromosone *a ) {
uint64_t rc = as_long( a ) ;
return PyLong_FromLong( rc ) ;
}
static PyObject *nb_float( Chromosone *a ) {
uint64_t val = as_long( a ) ;
if( a->len >= sizeof(double) * 8 ) {
return PyFloat_FromDouble( *(double*)&val ) ;
}
if( a->len >= sizeof(float) * 8 ) {
return PyFloat_FromDouble( *(float*)&val ) ;
}
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_SetString(PyExc_IndexError, "Not enough bits to hold a double or float!" ) ;
PyGILState_Release(gstate);
Py_RETURN_NAN ;
}
static PyNumberMethods Chromosone_numbers = {
0 , // binaryfunc nb_add;
0 , // binaryfunc nb_subtract;
0 , // binaryfunc nb_multiply;
0 , // binaryfunc nb_remainder;
0 , // binaryfunc nb_divmod;
0 , // ternaryfunc nb_power;
0 , // unaryfunc nb_negative;
0 , // unaryfunc nb_positive;
0 , // unaryfunc nb_absolute;
(inquiry)nb_bool , // inquiry nb_bool;
(unaryfunc)nb_invert , // unaryfunc nb_invert;
0 , // binaryfunc nb_lshift;
0 , // binaryfunc nb_rshift;
(binaryfunc)nb_and , // binaryfunc nb_and;
(binaryfunc)nb_xor , // binaryfunc nb_xor;
(binaryfunc)nb_or , // binaryfunc nb_or;
(unaryfunc)nb_long , // unaryfunc nb_int;
0 , // void *nb_reserved; /* the slot formerly known as nb_long */
(unaryfunc)nb_float , // unaryfunc nb_float;
0 , // binaryfunc nb_inplace_add;
0 , // binaryfunc nb_inplace_subtract;
0 , // binaryfunc nb_inplace_multiply;
0 , // binaryfunc nb_inplace_remainder;
0 , // ternaryfunc nb_inplace_power;
0 , // binaryfunc nb_inplace_lshift;
0 , // binaryfunc nb_inplace_rshift;
(binaryfunc)nb_inplace_and , // binaryfunc nb_inplace_and;
(binaryfunc)nb_inplace_xor , // binaryfunc nb_inplace_xor;
(binaryfunc)nb_inplace_or , // binaryfunc nb_inplace_or;
0 , // binaryfunc nb_floor_divide;
0 , // binaryfunc nb_true_divide;
0 , // binaryfunc nb_inplace_floor_divide;
0 , // binaryfunc nb_inplace_true_divide;
0 , // unaryfunc nb_index;
0 , // binaryfunc nb_matrix_multiply;
0 // binaryfunc nb_inplace_matrix_multiply;
} ;
/********************************************************************
*
* Iterator Methods
*
********************************************************************/
static PyObject *Chromosone_iternext( Chromosone *iter ) {
if ( iter->current < iter->len ) {
return PyLong_FromLong( iter->data[iter->current++] ) ;
}
return NULL ;
}
/********************************************************************
*
* Main Type Definition
*
********************************************************************/
static PyTypeObject ChromosoneType = {
PyVarObject_HEAD_INIT(NULL, 0)
"gene_pool.Chromosone", /* tp_name */
sizeof(Chromosone), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)Chromosone_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)Chromosone_repr, /* tp_repr */
&Chromosone_numbers, /* tp_as_number */
0, /* tp_as_sequence */
&Chromosone_mappings, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
"Chromosone objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
// (getiterfunc)Chromosone_getiter, /* tp_iter */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)Chromosone_iternext, /* tp_iternext */
Chromosone_methods, /* tp_methods */
Chromosone_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Chromosone_init, /* tp_init */
0, /* tp_alloc */
Chromosone_new /* tp_new */
};
/*****************************************************************
*
* Main Module Definition / Initialization
*
*****************************************************************/
static struct PyModuleDef gene_pool_definition = {
PyModuleDef_HEAD_INIT,
"gene_pool",
"example module containing Chromosone class",
-1,
NULL,
};
PyMODINIT_FUNC PyInit_gene_pool(void) {
srand48( getpid() ) ;
srand( getpid() ) ;
Py_Initialize();
PyObject *m = PyModule_Create(&gene_pool_definition);
if (PyType_Ready(&ChromosoneType) < 0)
return NULL;
Py_INCREF(&ChromosoneType); // class is in use
PyModule_AddObject(m, "Chromosone", (PyObject *)&ChromosoneType);
return m;
}
| 29.378205 | 130 | 0.532239 | [
"vector"
] |
d924d032f478bf9de4b3ffbe45c354a24cabf1e0 | 1,013 | cc | C++ | src/apc001/c.cc | nryotaro/at_c | 8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c | [
"MIT"
] | null | null | null | src/apc001/c.cc | nryotaro/at_c | 8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c | [
"MIT"
] | null | null | null | src/apc001/c.cc | nryotaro/at_c | 8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#ifndef _debug
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
cout << 0 << endl;
vector<string> fm(n, "");
cin >> fm[0];
if(fm[0] == "Vacant")
return 0;
cout << n - 1 << endl;
cin >> fm[n - 1];
if(fm[n - 1] == "Vacant")
return 0;
int l = -1, r = n;
while(r - l > 1) {
int mid = (l + r) / 2;
cout << mid << endl;
cin >> fm[mid];
if(fm[mid] == "Vacant")
return 0;
int c_l = max(0, l), c_r = min(n - 1, r);
if((mid - c_l + 1) % 2 == 0) {
if(fm[c_l] == fm[mid])
r = mid;
else
l = mid;
} else {
if(fm[c_l] == fm[mid])
l = mid;
else
r = mid;
}
}
if(fm[r] == "") {
cout << r;
} else {
cout << l;
}
return 0;
}
#endif
| 20.673469 | 49 | 0.372162 | [
"vector"
] |
d925eee144fa8e04927c0d1b3713b3f3714984a2 | 1,655 | cpp | C++ | passenger_car_kinematic_model/src/passenger_car_kinematic_model/EntryPoint.cpp | mjeronimo/carma-vehicle-model-framework | d330ed4eb316432e62ed48f5932be135d69688a4 | [
"Apache-2.0"
] | 3 | 2020-08-13T14:25:43.000Z | 2021-07-07T06:09:30.000Z | passenger_car_kinematic_model/src/passenger_car_kinematic_model/EntryPoint.cpp | mjeronimo/carma-vehicle-model-framework | d330ed4eb316432e62ed48f5932be135d69688a4 | [
"Apache-2.0"
] | 7 | 2020-08-18T21:24:51.000Z | 2022-02-03T21:55:28.000Z | passenger_car_kinematic_model/src/passenger_car_kinematic_model/EntryPoint.cpp | mjeronimo/carma-vehicle-model-framework | d330ed4eb316432e62ed48f5932be135d69688a4 | [
"Apache-2.0"
] | 1 | 2021-06-28T15:39:32.000Z | 2021-06-28T15:39:32.000Z | /*
* Copyright (C) 2018-2021 LEIDOS.
*
* 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 "passenger_car_kinematic_model/PassengerCarKinematicModel.h"
/**
* This Cpp file defines the two functions used as entry and exit points from the vehicle model shared library
* Define functions with C symbols (create/destroy PassengerCarKinematicModel instance).
*/
/**
* @brief Creates a new PassengerCarKinematicModel instance and returns a raw pointer to that instance
*
* This function is the access hook for getting a PassengerCarKinematicModel from this shared lib
*
* @return A raw pointer to a new PassengerCarKinematicModel instance
*/
extern "C" PassengerCarKinematicModel* create()
{
return new PassengerCarKinematicModel;
}
/**
* @brief Destroys the PassengerCarKinematicModel pointed at by the provided raw pointer and frees up its memory
*
* @param model_ptr A pointer to a valid instance of a PassengerCarKinematicModel
*
* This function is the access hook for getting a PassengerCarKinematicModel from this shared lib
*/
extern "C" void destroy(PassengerCarKinematicModel* model_ptr)
{
delete model_ptr;
}
| 35.978261 | 112 | 0.76858 | [
"model"
] |
d9303e2091c1366bba9c0d3e6e7cdfec6c1856df | 987 | cpp | C++ | leetcode-cpp/PartitionEqualSubsetSum_416.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/PartitionEqualSubsetSum_416.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/PartitionEqualSubsetSum_416.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <iostream>
#include <climits>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#define Max(a, b) a > b ? a : b
#define Min(a, b) a < b ? a : b
using namespace std;
class Solution {
public:
bool canPartition(vector<int>& nums) {
int m = nums.size();
int sum = 0;
for(int i=0;i<m;i++) {
sum += nums[i];
}
if(sum % 2 == 1) return false;
sum /= 2;
vector<vector<int>> dp(sum + 1, vector<int>(m + 1, 0));
for(int i = 1; i <= sum; i++) {
for(int j=0;j<nums.size();j++) {
if(nums[j] > sum) return false;
if (nums[j] <= i)
dp[i][j+1] = Max(dp[i][j], nums[j] + dp[i-nums[j]][j]);
}
}
return dp[sum][m] == sum;
}
};
int main() {
Solution s;
vector<int> c
{
1,2,3,5
};
bool result = s.canPartition(c);
cout<<result<<endl;
} | 19.352941 | 75 | 0.454914 | [
"vector"
] |
d9307ca2c4485a791d4e4f154e1cf740ca3d87f1 | 2,378 | cpp | C++ | test/signal_tests.cpp | JiveHelix/pex | d3cbe0e437e803fb4af6fe153de0cf3f61a3a6d6 | [
"MIT"
] | null | null | null | test/signal_tests.cpp | JiveHelix/pex | d3cbe0e437e803fb4af6fe153de0cf3f61a3a6d6 | [
"MIT"
] | null | null | null | test/signal_tests.cpp | JiveHelix/pex | d3cbe0e437e803fb4af6fe153de0cf3f61a3a6d6 | [
"MIT"
] | null | null | null | /**
* @author Jive Helix (jivehelix@gmail.com)
* @copyright 2020 Jive Helix
* Licensed under the MIT license. See LICENSE file.
*/
#include <catch2/catch.hpp>
#include "pex/signal.h"
template<typename Access = pex::GetAndSetTag>
class Observer
{
public:
Observer(pex::model::Signal &model)
:
control_(model),
observedCount{0}
{
if constexpr (pex::HasAccess<pex::GetTag, Access>)
{
this->control_.Connect(this, &Observer::Observe_);
}
}
void Trigger()
{
this->control_.Trigger();
}
private:
void Observe_()
{
++this->observedCount;
}
pex::control::Signal<Observer, Access> control_;
public:
int observedCount;
};
TEST_CASE("Signal propagation", "[signal]")
{
auto signalCount = GENERATE(take(10, random(1, 10000)));
auto expectedObservedCount = signalCount;
pex::model::Signal signal;
Observer observer(signal);
while (signalCount-- > 0)
{
signal.Trigger();
}
REQUIRE(observer.observedCount == expectedObservedCount);
}
TEST_CASE("Signal fan out", "[signal]")
{
auto signalCount = GENERATE(take(10, random(1, 10000)));
auto expectedObservedCount = signalCount;
pex::model::Signal signal;
Observer observer1(signal);
Observer observer2(signal);
Observer observer3(signal);
// Control signals echo back to us, and fan out to all other observers.
while (signalCount-- > 0)
{
observer1.Trigger();
}
REQUIRE(observer1.observedCount == expectedObservedCount);
REQUIRE(observer2.observedCount == expectedObservedCount);
REQUIRE(observer3.observedCount == expectedObservedCount);
}
TEST_CASE("Signal fan out from write-only control", "[signal]")
{
auto signalCount = GENERATE(take(10, random(1, 10000)));
auto expectedObservedCount = signalCount;
pex::model::Signal signal;
Observer<pex::SetTag> observer1(signal);
Observer<pex::GetTag> observer2(signal);
Observer<pex::GetTag> observer3(signal);
// Control signals echo back to us, and fan out to all other observers.
while (signalCount-- > 0)
{
observer1.Trigger();
}
REQUIRE(observer1.observedCount == 0);
REQUIRE(observer2.observedCount == expectedObservedCount);
REQUIRE(observer3.observedCount == expectedObservedCount);
}
| 23.544554 | 75 | 0.656854 | [
"model"
] |
d931de683d15f0ef8a2e6a859aa35c15828608df | 3,404 | cpp | C++ | ProjectEuler/euler033.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | ProjectEuler/euler033.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | ProjectEuler/euler033.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <unordered_set>
using namespace std;
//converts n to string and adds leading zeroes
string toString(unsigned int n, unsigned int digits) {
unsigned int digit;
string number = "";
while(digits--) {
digit = n % 10;
number += digit + '0';
n /= 10;
}
reverse(number.begin(),number.end());
return number;
}
//fill gaps in 'fill' with the numbers of 'digits'
unsigned int fillGaps(const string &fill, const string &digits) {
string::const_iterator it = fill.begin();
unsigned int result = 0;
for(int i=0; i<digits.size(); i++) {
result *= 10;
if(digits[i] == '.')
result += *it++ - '0';
else
result += digits[i] - '0';
}
return result;
}
int main() {
unsigned int n, k, num, den, insert, curNum, curDen, value;
cin >> n >> k;
const vector<unsigned int> powers = {1,10,100,1000,10000}; // 10^i
unsigned int sumNum = 0, sumDen = 0;
const unsigned int remaining = n - k;
string strNum, strDen, strIns, strInsNum, strInsDen;
bool ascending;
//helper to not count fractions twice
unordered_set<unsigned int> fractions;
for(den = 1; den < powers[remaining]; den++) {
for(num = 1; num < den; num++) {
strNum = toString(num,remaining);
strDen = toString(den,remaining);
//looü through all numbers that could be inserted
for(insert = powers[k-1]; insert < powers[k]; insert++) {
strIns = toString(insert,k);
//digits of strIns must be ascending, or all its permutations were already checked
ascending = true;
for(int i=1; i<strIns.size(); i++)
if(strIns[i-1] > strIns[i]) {
ascending = false;
break;
}
if(!ascending) continue;
strIns.insert(0, remaining, '.');
strInsNum = strIns;
strInsDen = strIns;
//loop through all permutations for numerator
do{
curNum = fillGaps(strNum,strInsNum);
if(curNum < powers[n-1])
continue;
//loop through all permutations for denominator
do {
curDen = fillGaps(strDen,strInsDen);
//fractions a/b and c/d are equal if a*d = b*c
if(curNum * den == curDen * num) {
value = curNum * 100000 + curDen;
//check if this fraction pair already occured
//if not: add to sums and insert into fractions
if(fractions.count(value) == 0) {
sumNum += curNum;
sumDen += curDen;
fractions.insert(value);
}
}
} while(next_permutation(strInsDen.begin(),strInsDen.end()));
} while(next_permutation(strInsNum.begin(),strInsNum.end()));
}
}
}
cout << sumNum << " " << sumDen << endl;
return 0;
}
| 33.70297 | 98 | 0.493243 | [
"vector"
] |
d93463925c3dad03cb87d75028db9dd79268f832 | 15,156 | cpp | C++ | stereo_sparse_depth_fusion/src/stereo_depth_fusion.cpp | huyaoyu/Tutorial2020_Stereo_ROS | 32f7427b597ac01674a36a19b8439844d1ea291b | [
"BSD-3-Clause"
] | 4 | 2020-10-27T03:12:39.000Z | 2022-02-01T07:04:34.000Z | stereo_sparse_depth_fusion/src/stereo_depth_fusion.cpp | huyaoyu/Tutorial2020_Stereo_ROS | 32f7427b597ac01674a36a19b8439844d1ea291b | [
"BSD-3-Clause"
] | null | null | null | stereo_sparse_depth_fusion/src/stereo_depth_fusion.cpp | huyaoyu/Tutorial2020_Stereo_ROS | 32f7427b597ac01674a36a19b8439844d1ea291b | [
"BSD-3-Clause"
] | 3 | 2021-08-14T23:05:10.000Z | 2022-02-02T11:31:22.000Z | #include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <dirent.h>
#include <iostream>
#include <sstream>
#include <string>
#include "stereo_sdf/SGMStereo.h"
#include "stereo_sdf/utils.h"
#include <Eigen/Dense>
// Headers from package stereo_utils.
#include <stereo_utils/stereo_utils.hpp>
#include <stereo_utils/Common.hpp>
using namespace std;
using JSON = nlohmann::json;
namespace su = stereo_utils;
/* -------------------------- SET THESE PARAMETERS --------------------------- */
/* stereo options */
#define STEREO_FULL_PIPELINE -1
#define STEREO_LEFT_ONLY 0
/* cost volume update options */
#define VOLUME_UPDATE_NAIVE 3
#define VOLUME_UPDATE_DIFFB 2
#define VOLUME_UPDATE_NEIGH 1
#define VOLUME_UPDATE_NONE -1
/* image save flag */
#define SAVE_IMAGES 1
/* ground truth sampling option */
double SAMPLING_FRACTION = 0.50;
/* disparity scaling factor (256 for KITTI) */
double SCALING_FACTOR = 256.0;
/* --------------------------------------------------------------------------- */
/* ------------ Type definition for interfacing the JSON file. --------------- */
struct CaseDescription {
std::string name = ""; // Name of the test case.
std::string fn0 = ""; // Filename of image Ref.
std::string fn1 = ""; // Filename of image Tst.
std::string fnD = ""; // Filename of the true disparity map.
std::string outDir = ""; // Output directory.
std::string fnQ = ""; // Filename of the Q matrix.
float qFactor = 1.0f; // Scale factor of Q.
float dOffs = 0.0f; // Disparity offset. Non-zero for Middlebury dataset. Zero for other datasets.
float distLimit = 20.f; // The distance limit for point cloud generation.
double gtSampleFrac = 0.5; // Ground truth sampling option.
SGMParams sgmParams = SGMParams();
};
/* --------------------------------------------------------------------------- */
void SemiGlobalMatching(const cv::Mat &leftImage,
const cv::Mat &rightImage,
cv::Mat &dispImage,
int STEREO_PIPELINE_MODE,
const std::string cameraParamFile,
cv::Mat depthImage,
cv::Mat weightImg,
int FUSE_FLAG,
const SGMParams &sgmParams)
{
png::image<png::rgb_pixel> leftImageSGM, rightImageSGM;
Utils utilities;
utilities.convertCVMatToPNG(leftImage, leftImageSGM);
utilities.convertCVMatToPNG(rightImage, rightImageSGM);
size_t width = leftImageSGM.get_width();
size_t height = leftImageSGM.get_height();
if (width != rightImageSGM.get_width() ||
height != rightImageSGM.get_height())
{
dispImage = cv::Mat1w();
return;
}
float* dispImageFloat = (float*)malloc(width*height*sizeof(float));
SGMStereo sgm;
// Configure the SGM method.
std::cout << "P1 = " << sgmParams.P1 << ", "
<< "P2 = " << sgmParams.P2 << ". \n";
sgm.setSmoothnessCostParameters( sgmParams.P1, sgmParams.P2 );
sgm.setDisparityTotal( sgmParams.total );
cv::Mat leftImageGray;
cv::cvtColor(leftImage, leftImageGray, CV_RGB2GRAY);
sgm.compute(leftImageSGM,
rightImageSGM,
dispImageFloat,
STEREO_PIPELINE_MODE,
cameraParamFile,
depthImage,
FUSE_FLAG,
leftImageGray,
weightImg);
dispImage = utilities.convertFloatToCVMat(width, height, dispImageFloat);
free(dispImageFloat);
}
void displayMinMax(cv::Mat array)
{
double min, max;
cv::minMaxLoc(array, &min, &max);
std::cout << "Minimum: " << min << " | Maximum: " << max << std::endl;
}
static void save_ply(
const std::string &fn,
const Eigen::MatrixXf &Q,
const cv::Mat &dispFloat,
const cv::Mat &color,
float distLimit=20.f,
float dOffs=0.f ) {
cv::Mat dispFloat32;
dispFloat.convertTo(dispFloat32, CV_32FC1);
const bool flagFlip = true; // Flip the point cloud so that the y-axis is upwards.
const bool flagBinary = true; // Write binary PLY files.
const float distanceLimit = 20.f; // All points with depth greater than this value will be ignored.
cv::Mat predDispOffs = dispFloat32 + dOffs; // This is required by Middlebury dataset. dOffs will be zero for other dataset.
su::write_ply_with_color(fn,
predDispOffs, color,
Q, flagFlip, distanceLimit, flagBinary);
}
static void process( const CaseDescription &cd ) {
/* input and output directories */
// std::string repo_dir = argv[1];
// std::string left_image_uri = repo_dir + "imgs/stereo_left.png";
// std::string right_image_uri = repo_dir + "imgs/stereo_right.png";
// std::string left_depth_uri = repo_dir + "imgs/gt_disparity.png";
// std::string save_dir = repo_dir + "results/";
std::string left_image_uri = cd.fn0;
std::string right_image_uri = cd.fn1;
std::string left_depth_uri = cd.fnD;
std::string save_dir = cd.outDir + "/";
su::test_directory(save_dir);
Eigen::MatrixXf Q;
if ( cd.fnQ != "" ) {
su::read_matrix(cd.fnQ, 4, 4, " ", Q);
// Update the Q matrix according to the scale factor.
Q(0, 3) *= cd.qFactor;
Q(1, 3) *= cd.qFactor;
Q(2, 3) *= cd.qFactor;
}
Utils utilities;
std::cout << "DATA DETAILS: " << std::endl;
std::cout << "--- Left Image: " << left_image_uri << std::endl;
std::cout << "--- Right Image: " << right_image_uri << std::endl;
std::cout << "--- Disparity: (GT) " << left_depth_uri << std::endl;
std::vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(0);
cv::Mat left_image_clr = cv::imread(left_image_uri);
cv::Mat right_image_clr = cv::imread(right_image_uri);
cv::Mat_<double> disp_image = cv::imread(left_depth_uri,
cv::IMREAD_ANYDEPTH);
disp_image = disp_image / SCALING_FACTOR;
std::cout << "{read status:} successfully read input images.." << std::endl;
/* EVALUATION A: SEMI GLOBAL MATCHING */
std::cout << "\n{EVALUATION A:} -- SEMI GLOBAL MATCHING -- " << std::endl;
cv::Mat disparity_image;
SemiGlobalMatching(left_image_clr,
right_image_clr,
disparity_image,
STEREO_LEFT_ONLY,
"no_params_needed",
cv::Mat(),
cv::Mat(),
VOLUME_UPDATE_NONE,
cd.sgmParams);
if (SAVE_IMAGES) {
std::string save_file_name = + "sgm_default.png";
std::string save_url = save_dir + save_file_name;
std::cout << "{SGM} saving image to: " << save_url << std::endl;
cv::imwrite(save_url, disparity_image, compression_params);
}
cv::Mat_<double> disp_SGM = disparity_image / SCALING_FACTOR;
/* evaluate SGM */
cv::Mat_<double> error_image_sgm;
double average_error_sgm;
cv::Mat sample_mask_sgm = cv::Mat::zeros(disp_SGM.rows,
disp_SGM.cols,
CV_32FC1);
utilities.calculateAccuracy(disp_SGM,
disp_image,
average_error_sgm,
error_image_sgm,
sample_mask_sgm);
std::cout << "{SGM} avg error: " << average_error_sgm << std::endl;
cv::Mat sample_mask;
// utilities.generateRandomSamplingMask(disp_image,
// sample_mask,
// SAMPLING_FRACTION);
utilities.generateRandomSamplingMask(disp_image,
sample_mask,
cd.gtSampleFrac);
if (SAVE_IMAGES) {
std::string save_file_name = "sparse_mask.png";
std::string save_url = save_dir + save_file_name;
std::cout << "{MASK} saving image to: " << save_url << std::endl;
cv::imwrite(save_url, sample_mask, compression_params);
}
cv::Mat masked_depth;
disp_image.copyTo(masked_depth, sample_mask);
// Save PLY file.
if ( cd.fnQ != "" ) {
std::string plyFn = save_dir + "Cloud_SGM.ply";
save_ply(plyFn, Q,
disp_SGM, left_image_clr,
cd.distLimit, cd.dOffs );
std::cout << "Point cloud saved to " << plyFn << "\n";
}
/* EVALUATION B: USE SPARSE LIDAR POINTS FOR NAIVE FUSION */
std::cout << "\n{EVALUATION B:} -- NAIVE LIDAR FUSION -- " << std::endl;
cv::Mat disparity_image_sl_naive;
SemiGlobalMatching(left_image_clr,
right_image_clr,
disparity_image_sl_naive,
STEREO_LEFT_ONLY,
"no_params_needed",
masked_depth,
cv::Mat(),
VOLUME_UPDATE_NAIVE,
cd.sgmParams);
if (SAVE_IMAGES) {
std::string save_file_name = "fuse_naive.png";
std::string save_url = save_dir + save_file_name;
std::cout << "{Naive Fusion} saving image to: " << save_url << std::endl;
cv::imwrite(save_url, disparity_image_sl_naive, compression_params);
}
cv::Mat_<double> disp_NF = disparity_image_sl_naive / SCALING_FACTOR;
/* evaluate naive fusion */
cv::Mat_<double> error_image_nf;
double average_error_nf;
utilities.calculateAccuracy(disp_NF,
disp_image,
average_error_nf,
error_image_nf, sample_mask);
std::cout << "{NAIVE FUSION} avg error: " << average_error_nf << std::endl;
// Save PLY file.
if ( cd.fnQ != "" ) {
std::string plyFn = save_dir + "Cloud_Naive.ply";
save_ply(plyFn, Q,
disp_NF, left_image_clr,
cd.distLimit, cd.dOffs );
std::cout << "Point cloud saved to " << plyFn << "\n";
}
/*EVALUATION C: USE DIFFUSION BASED METHOD */
std::cout << "\n{EVALUATION C:} -- DIFFUSION BASED -- " << std::endl;
cv::Mat disparity_image_db;
SemiGlobalMatching(left_image_clr,
right_image_clr,
disparity_image_db,
STEREO_LEFT_ONLY,
"no_params_needed",
masked_depth,
cv::Mat(),
VOLUME_UPDATE_DIFFB,
cd.sgmParams);
if (SAVE_IMAGES) {
std::string save_file_name = "fuse_diffusionbased.png";
std::string save_url = save_dir + save_file_name;
std::cout << "{DB} saving image to: " << save_url << std::endl;
cv::imwrite(save_url, disparity_image_db, compression_params);
}
cv::Mat_<double> disp_DB = disparity_image_db / SCALING_FACTOR;
/* evaluate diffusion based confidence propagation method */
cv::Mat_<double> error_image_db;
double average_error_db;
utilities.calculateAccuracy(disp_DB,
disp_image,
average_error_db,
error_image_db,
sample_mask);
std::cout << "{DB} avg error: " << average_error_db << std::endl;
// Save PLY file.
if ( cd.fnQ != "" ) {
std::string plyFn = save_dir + "Cloud_Diffusion.ply";
save_ply(plyFn, Q,
disp_DB, left_image_clr,
cd.distLimit, cd.dOffs );
std::cout << "Point cloud saved to " << plyFn << "\n";
}
/*EVALUATION D: USE BASIC BILATERAL COST UPDATE */
std::cout << "\n{EVALUATION D:} -- NEIGHBORHOOD SUPPORT -- " << std::endl;
cv::Mat disparity_image_ns;
SemiGlobalMatching(left_image_clr,
right_image_clr,
disparity_image_ns,
STEREO_LEFT_ONLY,
"no_params_needed",
masked_depth,
cv::Mat(),
VOLUME_UPDATE_NEIGH,
cd.sgmParams);
if (SAVE_IMAGES) {
std::string save_file_name = "fuse_neighborhoodsupport.png";
std::string save_url = save_dir + save_file_name;
std::cout << "{NS} saving image to: " << save_url << std::endl;
cv::imwrite(save_url, disparity_image_ns, compression_params);
}
cv::Mat_<double> disp_NS = disparity_image_ns / SCALING_FACTOR;
/* evaluate neighborhood support method */
cv::Mat_<double> error_image_ns;
double average_error_ns;
utilities.calculateAccuracy(disp_NS,
disp_image,
average_error_ns,
error_image_ns,
sample_mask);
std::cout << "{NS} avg error: " << average_error_ns << std::endl;
// Save PLY file.
if ( cd.fnQ != "" ) {
std::string plyFn = save_dir + "Cloud_Neighbor.ply";
save_ply(plyFn, Q,
disp_NS, left_image_clr,
cd.distLimit, cd.dOffs );
std::cout << "Point cloud saved to " << plyFn << "\n";
}
}
int main(int argc, char** argv)
{
if ( argc < 2 ) {
std::cerr << "Must specify the input JSON file. \n";
throw std::runtime_error("Must specify the input JSON file. ");
}
// Read the JSON file.
std::shared_ptr<JSON> pJSON = su::read_json(argv[1]);
auto& cases = (*pJSON)["cases"];
const int N = cases.size();
// Process all the cases.
for ( int i = 0; i < N; ++i ) {
if ( true != cases[i]["enable"] )
continue;
auto cd = CaseDescription();
cd.fn0 = cases[i]["fn0"]; // Filename of image 0.
cd.fn1 = cases[i]["fn1"]; // Filename of image 1.
// True disparity if exists.
cd.fnD = cases[i]["fnD"];
cd.name = cases[i]["name"]; // Case name.
cd.gtSampleFrac = cases[i]["gtSampleFrac"]; // The true data sample fraction.
std::stringstream ss;
std::string tempDir = cases[i]["outDir"]; // This strips the double quotes.
ss << tempDir << "/" << cd.name << "_" << cd.gtSampleFrac;
cd.outDir = ss.str(); // Output directory.
// Q matrix if exists.
if ( cases[i].find("fnQ") != cases[i].end() ) {
cd.fnQ = cases[i]["fnQ"];
cd.qFactor = cases[i]["QF"];
cd.dOffs = cases[i]["dOffs"];
cd.distLimit = cases[i]["distLimit"];
} else {
cd.fnQ = "";
cd.qFactor = 1.f;
cd.dOffs = 0.f;
cd.distLimit = 20.f;
}
// SGM parameters.
cd.sgmParams.P1 = cases[i]["sgm"]["P1"];
cd.sgmParams.P2 = cases[i]["sgm"]["P2"];
cd.sgmParams.total = cases[i]["sgm"]["total"];
std::cout << "\n========== Procesing " << cd.name << "_" << cd.gtSampleFrac << ". ==========\n\n";
process( cd );
}
std::cout << "SPS-Stereo done. \n";
return 0;
}
| 36.697337 | 133 | 0.555819 | [
"vector"
] |
d938c3f1eecf6b71eb0fa83c5087a7bf21d31a5a | 1,774 | cpp | C++ | Etherea/Splash.cpp | Perlucidus/Etherea2D | 04fc1359d5bb152ec9363a9cb049f143a13574a8 | [
"MIT"
] | null | null | null | Etherea/Splash.cpp | Perlucidus/Etherea2D | 04fc1359d5bb152ec9363a9cb049f143a13574a8 | [
"MIT"
] | null | null | null | Etherea/Splash.cpp | Perlucidus/Etherea2D | 04fc1359d5bb152ec9363a9cb049f143a13574a8 | [
"MIT"
] | null | null | null | #include "Splash.hpp"
#include "Log.hpp"
#define RENDER GetComponent<RenderComponent>()
Splash::Splash() : Entity("splash")
{
Texture texture = GAME.GetRenderer().LoadTexture("../assets/textures/splash.png");
AddComponent<RenderComponent>(texture);
}
void Splash::render(Renderer & renderer)
{
renderer.CopyTo(RENDER.getTexture(), Rectangle(Position(0), RENDER.getTextureSize()));
}
void Splash::update()
{
const float ratio = 0.67f;
SDL_Color color = RENDER.getTexture().GetColorMod();
color.a = static_cast<Uint8>((progress < ratio ? (progress / ratio) : ((1 - progress) / (1 - ratio))) * 255);
RENDER.getTexture().ColorMod(color);
}
void Splash::setProgress(float p)
{
progress = p;
}
SplashScreen::SplashScreen() : timer(2000, &SplashScreen::end) {}
void SplashScreen::initialize()
{
GAME.RegisterEventHandler<SplashEventHandler>(EventHandlerPriority::SPLASH);
timer.start(nullptr);
start = SDL_GetTicks();
}
void SplashScreen::update()
{
if (timer.isRunning()) {
splash.setProgress(static_cast<float>(SDL_GetTicks() - start) / timer.getDelay());
splash.update();
}
}
void SplashScreen::render(Renderer & renderer)
{
if (timer.isRunning())
splash.render(renderer);
}
TimerResult SplashScreen::end(Uint32 interval, void* param)
{
STDLOG << "Splash ended with interval " << interval;
EventHandler::PushCustomEvent<SplashEventData>(CustomEvent::SPLASH);
return TimerResult::ABORT;
}
bool SplashEventHandler::handle(SDL_Event const& event)
{
if (event.type != SDL_USEREVENT || event.user.code != CustomEvent::SPLASH)
return false;
GAME.EraseComponent("splash");
/////////////////////////////////////////////////
GAME.GetComponent<GameComponent>("test").initialize();
/////////////////////////////////////////////////
return true;
}
| 25.342857 | 110 | 0.684893 | [
"render"
] |
d9402456df53de66a4cd254d502da140e7e13634 | 14,149 | cpp | C++ | Samples/BasicFaceTracking/cpp/Scenario1_TrackInWebcam.xaml.cpp | Luisesp/Windows-universal-samples | 5a195ae2f4863ea6596718747ccc026fdf2b65d1 | [
"MIT"
] | 2 | 2018-12-25T14:44:11.000Z | 2020-05-25T08:41:59.000Z | Samples/BasicFaceTracking/cpp/Scenario1_TrackInWebcam.xaml.cpp | pjurkiewicz/Windows-universal-samples | 5a195ae2f4863ea6596718747ccc026fdf2b65d1 | [
"MIT"
] | null | null | null | Samples/BasicFaceTracking/cpp/Scenario1_TrackInWebcam.xaml.cpp | pjurkiewicz/Windows-universal-samples | 5a195ae2f4863ea6596718747ccc026fdf2b65d1 | [
"MIT"
] | 2 | 2020-07-13T03:05:00.000Z | 2021-08-11T15:16:12.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario1_TrackInWebcam.xaml.h"
using namespace SDKTemplate;
using namespace Windows::ApplicationModel;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Imaging;
using namespace Windows::Media;
using namespace Windows::Media::Capture;
using namespace Windows::Media::FaceAnalysis;
using namespace Windows::Media::MediaProperties;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Media::Imaging;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Shapes;
TrackFacesInWebcam::TrackFacesInWebcam() :
rootPage(MainPage::Current),
currentState(ScenarioState::Idle),
frameProcessingSemaphore(nullptr)
{
InitializeComponent();
App::Current->Suspending += ref new SuspendingEventHandler(this, &TrackFacesInWebcam::OnSuspending);
frameProcessingSemaphore = CreateSemaphoreEx(nullptr, 1, 1, nullptr, 0, SYNCHRONIZE | SEMAPHORE_MODIFY_STATE);
if (frameProcessingSemaphore == nullptr)
{
throw ref new Platform::Exception(HRESULT_FROM_WIN32(GetLastError()), "Failed to create frameProcessingSemaphore");
}
concurrency::create_task(FaceTracker::CreateAsync())
.then([this](FaceTracker^ tracker)
{
this->faceTracker = tracker;
});
}
TrackFacesInWebcam::~TrackFacesInWebcam()
{
if (frameProcessingSemaphore != nullptr)
{
CloseHandle(frameProcessingSemaphore);
frameProcessingSemaphore = nullptr;
}
}
void TrackFacesInWebcam::OnNavigatedTo(NavigationEventArgs^ e)
{
this->rootPage = MainPage::Current;
}
void TrackFacesInWebcam::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ e)
{
if (this->currentState == ScenarioState::Streaming)
{
auto deferral = e->SuspendingOperation->GetDeferral();
try
{
ChangeScenarioState(ScenarioState::Idle);
}
catch (...)
{
deferral->Complete();
throw;
}
}
}
Concurrency::task<bool> TrackFacesInWebcam::StartWebcamStreaming()
{
this->mediaCapture = ref new MediaCapture();
// For this scenario, we only need Video (not microphone) so specify this in the initializer.
// NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include
// microphone (default constructor) you must add "microphone" to the manifest or initialization will fail.
MediaCaptureInitializationSettings^ settings = ref new MediaCaptureInitializationSettings();
settings->StreamingCaptureMode = StreamingCaptureMode::Video;
// Start a task chain to initialize MediaCapture and start streaming. A "final" task is
// linked in to handle exceptions and return success/failure back to the caller.
return concurrency::create_task(this->mediaCapture->InitializeAsync(settings))
.then([this]()
{
this->mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &TrackFacesInWebcam::MediaCapture_CameraStreamFailed);
// Cache the media properties as we'll need them later.
auto deviceController = this->mediaCapture->VideoDeviceController;
this->videoProperties = dynamic_cast<VideoEncodingProperties^>(deviceController->GetMediaStreamProperties(MediaStreamType::VideoPreview));
// Immediately start streaming to our CaptureElement UI.
// NOTE: CaptureElement's Source must be set before streaming is started.
this->CamPreview->Source = this->mediaCapture.Get();
return concurrency::create_task(this->mediaCapture->StartPreviewAsync());
}).then([this](concurrency::task<void> finalTask)
{
bool successful;
try
{
finalTask.get();
// Ensure the Semaphore is in the signalled state.
ReleaseSemaphore(frameProcessingSemaphore, 1, nullptr);
// Use a 66 milisecond interval for our timer, i.e. 15 frames per second.
// NOTE: Timespan is measured in 100 nanosecond units
TimeSpan timerInterval;
timerInterval.Duration = 66 * 10000;
frameProcessingTimer = Windows::System::Threading::ThreadPoolTimer::CreatePeriodicTimer(ref new Windows::System::Threading::TimerElapsedHandler(this, &TrackFacesInWebcam::ProcessCurrentVideoFrame), timerInterval);
successful = true;
}
catch (Platform::AccessDeniedException^ ex)
{
// If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact.
this->rootPage->NotifyUser("Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType::ErrorMessage);
successful = false;
}
catch (Platform::Exception^ ex)
{
this->rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
successful = false;
}
return successful;
});
}
void TrackFacesInWebcam::ShutdownWebCam()
{
if (frameProcessingTimer != nullptr)
{
frameProcessingTimer->Cancel();
}
frameProcessingTimer = nullptr;
if (this->mediaCapture.Get() != nullptr)
{
if (this->mediaCapture->CameraStreamState == Windows::Media::Devices::CameraStreamState::Streaming)
{
// Attempt to stop preview screen and clean up MediaCapture object once Shutdown has completed.
concurrency::create_task(this->mediaCapture->StopPreviewAsync())
.then([this](concurrency::task<void> task)
{
try
{
task.get();
}
catch (Platform::Exception^)
{
; // Since we're going to destroy the MediaCapture object there's nothing to do here
}
this->mediaCapture = nullptr;
this->CamPreview->Source = nullptr;
this->CameraStreamingButton->IsEnabled = true;
});
}
else
{
this->mediaCapture = nullptr;
this->CamPreview->Source = nullptr;
this->CameraStreamingButton->IsEnabled = true;
}
}
else
{
this->CamPreview->Source = nullptr;
this->CameraStreamingButton->IsEnabled = true;
}
}
void TrackFacesInWebcam::ProcessCurrentVideoFrame(Windows::System::Threading::ThreadPoolTimer^ timer)
{
if (this->currentState != ScenarioState::Streaming)
{
return;
}
// If the semaphore is nonsignaled it means we're still waiting for processing work on the previous frame to complete.
// In this situation, don't wait on the semaphore but exit immediately.
if(WaitForSingleObject(frameProcessingSemaphore, 0) != WAIT_OBJECT_0)
{
return;
}
// Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case).
// GetPreviewFrame will convert the native webcam frame into this format.
const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat::Nv12;
VideoFrame^ previewFrame = ref new VideoFrame(InputPixelFormat, this->videoProperties->Width, this->videoProperties->Height);
concurrency::create_task(this->mediaCapture->GetPreviewFrameAsync(previewFrame))
.then([this](VideoFrame^ previewFrame)
{
// The returned VideoFrame should be in the supported NV12 format but we need to verify this.
if (FaceTracker::IsBitmapPixelFormatSupported(previewFrame->SoftwareBitmap->BitmapPixelFormat))
{
return concurrency::create_task(this->faceTracker->ProcessNextFrameAsync(previewFrame))
.then([this, previewFrame](IVector<DetectedFace^>^ faces)
{
// Create our visualization using the frame dimensions and face results but run it on the UI thread.
auto previewFrameSize = Windows::Foundation::Size(static_cast<float>(previewFrame->SoftwareBitmap->PixelWidth), static_cast<float>(previewFrame->SoftwareBitmap->PixelHeight));
concurrency::create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, previewFrameSize, faces]()
{
SetupVisualization(previewFrameSize, faces);
})));
});
}
else
{
// We need to return a task<void> object from this lambda to continue the task chain,
// and also the call to BitmapPixelFormat::ToString() must occur on the UI thread.
return concurrency::create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
ref new Windows::UI::Core::DispatchedHandler([this, previewFrame]()
{
this->rootPage->NotifyUser("PixelFormat '" + previewFrame->SoftwareBitmap->BitmapPixelFormat.ToString() + "' is not supported by FaceTracker", NotifyType::ErrorMessage);
})));
}
}).then([this](concurrency::task<void> finalTask)
{
// Use a final continuation task to handle any exceptions that may have been thrown
// during the task sequence.
try
{
finalTask.get();
}
catch (Platform::Exception^ ex)
{
concurrency::create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
ref new Windows::UI::Core::DispatchedHandler([this, ex]()
{
this->rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
})));
}
// Finally release the semaphore.
ReleaseSemaphore(frameProcessingSemaphore, 1, nullptr);
});
}
void TrackFacesInWebcam::SetupVisualization(
Windows::Foundation::Size framePizelSize,
IVector<DetectedFace^>^ foundFaces)
{
this->VisualizationCanvas->Children->Clear();
double actualWidth = this->VisualizationCanvas->ActualWidth;
double actualHeight = this->VisualizationCanvas->ActualHeight;
if (this->currentState == ScenarioState::Streaming && foundFaces != nullptr && actualWidth != 0 && actualHeight != 0)
{
double widthScale = framePizelSize.Width / actualWidth;
double heightScale = framePizelSize.Height / actualHeight;
for each(DetectedFace^ face in foundFaces)
{
// Create a rectangle element for displaying the face box but since we're using a Canvas
// we must scale the rectangles according to the frames's actual size.
Rectangle^ box = ref new Rectangle();
box->Tag = face->FaceBox;
box->Width = face->FaceBox.Width / widthScale;
box->Height = face->FaceBox.Height / heightScale;
box->Fill = this->fillBrush;
box->Stroke = this->lineBrush;
box->StrokeThickness = this->lineThickness;
box->Margin = Thickness(face->FaceBox.X / widthScale, face->FaceBox.Y / heightScale, 0, 0);
this->VisualizationCanvas->Children->Append(box);
}
}
}
void TrackFacesInWebcam::ChangeScenarioState(ScenarioState newState)
{
// Disable UI while state change is in progress
this->CameraStreamingButton->IsEnabled = false;
switch (newState)
{
case ScenarioState::Idle:
ShutdownWebCam();
this->VisualizationCanvas->Children->Clear();
this->CameraStreamingButton->Content = "Start Streaming";
this->currentState = newState;
break;
case ScenarioState::Streaming:
concurrency::create_task(this->StartWebcamStreaming())
.then([this, newState](concurrency::task<bool> task)
{
if (!task.get())
{
ChangeScenarioState(ScenarioState::Idle);
}
else
{
this->VisualizationCanvas->Children->Clear();
this->CameraStreamingButton->Content = "Stop Streaming";
this->currentState = newState;
}
this->CameraStreamingButton->IsEnabled = true;
});
break;
}
}
void TrackFacesInWebcam::MediaCapture_CameraStreamFailed(MediaCapture^ sender, MediaCaptureFailedEventArgs^ errorEventArgs)
{
// MediaCapture is not Agile and so we cannot invoke its methods on this caller's thread
// and instead need to schedule the state change on the UI thread.
concurrency::create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this]()
{
ChangeScenarioState(ScenarioState::Idle);
})));
}
void TrackFacesInWebcam::CameraStreamingButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
if (this->currentState == ScenarioState::Streaming)
{
this->rootPage->NotifyUser("", NotifyType::StatusMessage);
ChangeScenarioState(ScenarioState::Idle);
}
else
{
this->rootPage->NotifyUser("", NotifyType::StatusMessage);
ChangeScenarioState(ScenarioState::Streaming);
}
}
| 39.633053 | 226 | 0.637006 | [
"object"
] |
d94053f5f830e6ab1cba5c5995e63feb160d79c1 | 5,858 | cpp | C++ | examples/C++/DDS/ContentFilteredTopicExample/ContentFilteredTopicExampleSubscriber.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 575 | 2015-01-22T20:05:04.000Z | 2020-06-01T10:06:12.000Z | examples/C++/DDS/ContentFilteredTopicExample/ContentFilteredTopicExampleSubscriber.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 1,110 | 2015-04-20T19:30:34.000Z | 2020-06-01T08:13:52.000Z | examples/C++/DDS/ContentFilteredTopicExample/ContentFilteredTopicExampleSubscriber.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 273 | 2015-08-10T23:34:42.000Z | 2020-05-28T13:03:32.000Z | // Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 ContentFilteredTopicExampleSubscriber.cpp
*
*/
#include "ContentFilteredTopicExampleSubscriber.hpp"
#include <fastdds/dds/core/status/SubscriptionMatchedStatus.hpp>
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/dds/domain/qos/DomainParticipantQos.hpp>
#include <fastdds/dds/subscriber/Subscriber.hpp>
#include <fastdds/dds/subscriber/DataReader.hpp>
#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
#include <fastdds/dds/subscriber/SampleInfo.hpp>
using namespace eprosima::fastdds::dds;
bool ContentFilteredTopicExampleSubscriber::init(
bool custom_filter)
{
// Initialize internal variables
matched_ = 0;
// Set DomainParticipant name
DomainParticipantQos pqos;
pqos.name("Participant_sub");
// Create DomainParticipant
participant_ = DomainParticipantFactory::get_instance()->create_participant(0, pqos);
if (nullptr == participant_)
{
return false;
}
// If using the custom filter
if (custom_filter)
{
// Register the filter factory
if (ReturnCode_t::RETCODE_OK !=
participant_->register_content_filter_factory("MY_CUSTOM_FILTER", &filter_factory))
{
return false;
}
}
// Register the type
type_.register_type(participant_);
// Create the Subscriber
subscriber_ = participant_->create_subscriber(SUBSCRIBER_QOS_DEFAULT, nullptr);
if (nullptr == subscriber_)
{
return false;
}
// Create the Topic
topic_ = participant_->create_topic("HelloWorldTopic", type_->getName(), TOPIC_QOS_DEFAULT);
if (nullptr == topic_)
{
return false;
}
// Create the ContentFilteredTopic
std::string expression;
std::vector<std::string> parameters;
if (custom_filter)
{
// Custom filter: reject samples where index > parameters[0] and index < parameters[1].
// Custom filter does not use expression. However, an empty expression disables filtering, so some expression
// must be set.
expression = " ";
parameters.push_back("3");
parameters.push_back("5");
filter_topic_ =
participant_->create_contentfilteredtopic("HelloWorldFilteredTopic1", topic_, expression, parameters,
"MY_CUSTOM_FILTER");
}
else
{
// Default filter: accept samples meeting the given expression: index between the two given parameters
expression = "index between %0 and %1";
parameters.push_back("5");
parameters.push_back("9");
filter_topic_ =
participant_->create_contentfilteredtopic("HelloWorldFilteredTopic1", topic_, expression, parameters);
}
if (nullptr == filter_topic_)
{
return false;
}
// Create the DataReader
DataReaderQos rqos = DATAREADER_QOS_DEFAULT;
// In order to receive all samples, DataReader is configured as RELIABLE and TRANSIENT_LOCAL (ensure reception even
// if DataReader matching is after DataWriter one)
rqos.reliability().kind = RELIABLE_RELIABILITY_QOS;
rqos.durability().kind = TRANSIENT_LOCAL_DURABILITY_QOS;
reader_ = subscriber_->create_datareader(filter_topic_, rqos, this);
if (nullptr == reader_)
{
return false;
}
return true;
}
ContentFilteredTopicExampleSubscriber::~ContentFilteredTopicExampleSubscriber()
{
// Delete DDS entities contained within the DomainParticipant
participant_->delete_contained_entities();
// Delete DomainParticipant
DomainParticipantFactory::get_instance()->delete_participant(participant_);
}
void ContentFilteredTopicExampleSubscriber::on_subscription_matched(
DataReader*,
const SubscriptionMatchedStatus& info)
{
// New remote DataWriter discovered
if (info.current_count_change == 1)
{
matched_ = info.current_count;
std::cout << "Subscriber matched." << std::endl;
}
// New remote DataWriter undiscovered
else if (info.current_count_change == -1)
{
matched_ = info.current_count;
std::cout << "Subscriber unmatched." << std::endl;
}
// Non-valid option
else
{
std::cout << info.current_count_change
<< " is not a valid value for SubscriptionMatchedStatus current count change" << std::endl;
}
}
void ContentFilteredTopicExampleSubscriber::on_data_available(
DataReader* reader)
{
SampleInfo info;
// Take next sample from DataReader's history
if (ReturnCode_t::RETCODE_OK == reader->take_next_sample(&hello_, &info))
{
// Some samples only update the instance state. Only if it is a valid sample (with data)
if (ALIVE_INSTANCE_STATE == info.instance_state)
{
samples_++;
// Print structure data
std::cout << "Message " << hello_.message() << " " << hello_.index() << " RECEIVED" << std::endl;
}
}
}
void ContentFilteredTopicExampleSubscriber::run()
{
// Subscriber application thread running until stopped by the user
std::cout << "Subscriber running. Please press enter to stop the Subscriber" << std::endl;
std::cin.ignore();
}
| 33.666667 | 119 | 0.682656 | [
"vector"
] |
d9474a2f216057ad7a35cef47140ae012276c014 | 36,584 | cpp | C++ | source/gtrD3D11/gtDriverD3D11.cpp | lineCode/gost.engine | 5f69216b97fc638663b6a38bee3cacfea2abf7ba | [
"MIT"
] | null | null | null | source/gtrD3D11/gtDriverD3D11.cpp | lineCode/gost.engine | 5f69216b97fc638663b6a38bee3cacfea2abf7ba | [
"MIT"
] | null | null | null | source/gtrD3D11/gtDriverD3D11.cpp | lineCode/gost.engine | 5f69216b97fc638663b6a38bee3cacfea2abf7ba | [
"MIT"
] | 2 | 2020-01-22T08:45:44.000Z | 2020-02-15T20:08:41.000Z | //GoST
#include "common.h"
gtDriverD3D11::gtDriverD3D11( gtGraphicsSystemInfo params ):
m_system( nullptr ),
m_D3DLibrary( nullptr ),
m_SwapChain( nullptr ),
m_d3d11Device( nullptr ),
m_d3d11DevCon( nullptr ),
m_MainTargetView( nullptr ),
m_depthStencilBuffer( nullptr ),
m_depthStencilStateEnabled( nullptr ),
m_depthStencilStateDisabled( nullptr ),
m_depthStencilView( nullptr ),
m_RasterizerSolid( nullptr ),
m_RasterizerSolidNoBackFaceCulling( nullptr ),
m_RasterizerWireframeNoBackFaceCulling( nullptr ),
m_RasterizerWireframe( nullptr ),
m_blendStateAlphaEnabled( nullptr ),
m_blendStateAlphaEnabledWithATC( nullptr ),
m_blendStateAlphaDisabled( nullptr ),
m_shader2DStandart( nullptr ),
m_shader3DStandart( nullptr ),
m_shaderGUI( nullptr ),
m_shaderSprite( nullptr ),
m_shaderLine( nullptr ),
m_beginRender( false )
{
m_system = gtMainSystem::getInstance();
m_params = params;
s_instance = this;
if( params.m_outWindow ){
//m_currentWindowSize.x = params.m_outWindow->getRect().z; // нужно ли? МОжет быть правильнее везде где нужно брать m_outWindow->getClientRect
//m_currentWindowSize.y = params.m_outWindow->getRect().w;
}
}
gtDriverD3D11* gtDriverD3D11::s_instance = nullptr;
gtDriverD3D11* gtDriverD3D11::getInstance(){ return s_instance; }
gtTexture * gtDriverD3D11::getStandartTexture(){ return m_standartTexture.data(); }
gtTexture * gtDriverD3D11::getStandartTextureWhiteColor(){ return m_standartTextureWhiteColor.data(); }
gtDriverD3D11::~gtDriverD3D11(){
clearTextureCache();
clearModelCache();
if( m_shaderLine ) m_shaderLine->release();
if( m_shaderSprite ) m_shaderSprite->release();
if( m_shader3DStandart ) m_shader3DStandart->release();
if( m_shaderGUI ) m_shaderGUI->release();
if( m_shader2DStandart ) m_shader2DStandart->release();
if( m_standartTextureWhiteColor.data() ) m_standartTextureWhiteColor->release();
if( m_standartTexture.data() ) m_standartTexture->release();
if( m_blendStateAlphaDisabled ) m_blendStateAlphaDisabled->Release();
if( m_blendStateAlphaEnabledWithATC ) m_blendStateAlphaEnabledWithATC->Release();
if( m_blendStateAlphaEnabled ) m_blendStateAlphaEnabled->Release();
if( m_RasterizerWireframeNoBackFaceCulling ) m_RasterizerWireframeNoBackFaceCulling->Release();
if( m_RasterizerWireframe ) m_RasterizerWireframe->Release();
if( m_RasterizerSolidNoBackFaceCulling ) m_RasterizerSolidNoBackFaceCulling->Release();
if( m_RasterizerSolid ) m_RasterizerSolid->Release();
if( m_depthStencilView ) m_depthStencilView->Release();
if( m_depthStencilStateDisabled ) m_depthStencilStateDisabled->Release();
if( m_depthStencilStateEnabled ) m_depthStencilStateEnabled->Release();
if( m_depthStencilBuffer ) m_depthStencilBuffer->Release();
if( m_MainTargetView ) m_MainTargetView->Release();
if( m_d3d11DevCon ) m_d3d11DevCon->Release();
if( m_SwapChain ) m_SwapChain->Release();
if( m_d3d11Device ) m_d3d11Device->Release();
if( m_D3DLibrary ) FreeLibrary( m_D3DLibrary ); m_D3DLibrary = NULL;
}
HMODULE gtDriverD3D11::getD3DLibraryHandle(){ return m_D3DLibrary; }
ID3D11Device * gtDriverD3D11::getD3DDevice(){ return m_d3d11Device; }
ID3D11DeviceContext * gtDriverD3D11::getD3DDeviceContext(){ return m_d3d11DevCon; }
void gtDriverD3D11::setDepthState( bool state ){
state ? m_d3d11DevCon->OMSetDepthStencilState( this->m_depthStencilStateEnabled, 0 )
: m_d3d11DevCon->OMSetDepthStencilState( this->m_depthStencilStateDisabled, 0 );
}
void gtDriverD3D11::setActiveShader( gtShader* shader ){
m_d3d11DevCon->IASetInputLayout( ((gtShaderImpl*)shader)->m_vLayout );
m_d3d11DevCon->VSSetShader( ((gtShaderImpl*)shader)->m_vShader, 0, 0 );
m_d3d11DevCon->PSSetShader( ((gtShaderImpl*)shader)->m_pShader, 0, 0 );
}
bool gtDriverD3D11::initialize(){
HRESULT hr;
if( !m_params.m_outWindow ){
gtLogWriter::printError( u"No render out window." );
return false;
}
HWND outWindow = (HWND)m_params.m_outWindow->getHandle();
DXGI_MODE_DESC bufferDesc;
ZeroMemory( &bufferDesc, sizeof(bufferDesc) );
bufferDesc.Width = m_params.m_backBufferSize.x;
bufferDesc.Height = m_params.m_backBufferSize.y;
if( m_params.m_vSync )
bufferDesc.RefreshRate.Numerator = 60;
else bufferDesc.RefreshRate.Numerator = 0;
bufferDesc.RefreshRate.Denominator = 1;
bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
gtString d3dlib_str = gtFileSystem::getSystemPath();
d3dlib_str += u"d3d11.dll";
m_D3DLibrary = LoadLibrary( (wchar_t*)d3dlib_str.data() );
if( !m_D3DLibrary ){
gtLogWriter::printError( u"Could not load d3d11.dll" );
return false;
}
gtD3D11CreateDevice_t D3D11CreateDevice = GT_LOAD_FUNCTION_SAFE_CAST(gtD3D11CreateDevice_t,m_D3DLibrary, "D3D11CreateDevice");
//gtD3D11CreateDevice_t D3D11CreateDevice = (gtD3D11CreateDevice_t)GetProcAddress( m_D3DLibrary, "D3D11CreateDevice");
if( !D3D11CreateDevice ){
gtLogWriter::printError( u"Could not get proc adress of D3D11CreateDevice");
return false;
}
gtD3D11CreateDeviceAndSwapChain_t D3D11CreateDeviceAndSwapChain =
GT_LOAD_FUNCTION_SAFE_CAST(gtD3D11CreateDeviceAndSwapChain_t,m_D3DLibrary, "D3D11CreateDeviceAndSwapChain");
//(gtD3D11CreateDeviceAndSwapChain_t)GetProcAddress(m_D3DLibrary, "D3D11CreateDeviceAndSwapChain");
if( !D3D11CreateDeviceAndSwapChain ){
gtLogWriter::printError( u"Could not get proc adress of D3D11CreateDeviceAndSwapChain");
return false;
}
/*
D3D_FEATURE_LEVEL FeatureLevels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1
};
*/
D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
/*
if( FAILED(D3D11CreateDevice(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
0,
&FeatureLevels[0],
sizeof(FeatureLevels)/sizeof(FeatureLevels[0]),
D3D11_SDK_VERSION,
nullptr,
&featureLevel,
nullptr ))){
gtLogWriter::printError( u"Can not get D3D Feature Level");
return false;
}
*/
/*
if( featureLevel == D3D_FEATURE_LEVEL_11_0 ){
gtLogWriter::printInfo( u"D3D feature level 11.0" );
}else if( featureLevel == D3D_FEATURE_LEVEL_11_1 ){
gtLogWriter::printInfo( u"D3D feature level 11.1" );
}
*/
hr = D3D11CreateDevice(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
D3D11_CREATE_DEVICE_SINGLETHREADED,
nullptr,
0,
D3D11_SDK_VERSION,
&m_d3d11Device,
&featureLevel,
&m_d3d11DevCon );
gtLogWriter::printInfo( u"featureLevel : %u", featureLevel );
if( FAILED(hr)){
gtLogWriter::printError( u"Can't create Direct3D 11 Device : code %u", hr );
return false;
}
UINT numQualityLevels = 0;
hr = getD3DDevice()->CheckMultisampleQualityLevels(
DXGI_FORMAT_R8G8B8A8_UNORM,
4,
&numQualityLevels );
if( FAILED(hr)){
gtLogWriter::printError( u"Can't Check Multisample Quality Levels : code %u", hr );
return false;
}
gtLogWriter::printInfo( u"Hardware MSAA Quality levels : %u", numQualityLevels );
IDXGIDevice * dxgiDevice = nullptr;
IDXGIAdapter * dxgiAdapter = nullptr;
IDXGIFactory1* dxgiFactory = nullptr;
hr = m_d3d11Device->QueryInterface( IID_IDXGIDevice,(void**)&dxgiDevice );
if( FAILED(hr) ){
gtLogWriter::printError( u"Can't QueryInterface : IID_IDXGIDevice, code %u", hr );
return false;
}
hr = dxgiDevice->GetParent( IID_IDXGIAdapter, (void**)&dxgiAdapter );
if( FAILED(hr) ){
gtLogWriter::printError( u"Can't get DXGI adapter, code %u", hr );
return false;
}
hr = dxgiAdapter->GetParent( IID_IDXGIFactory, (void**)&dxgiFactory );
if( FAILED(hr) ){
gtLogWriter::printError( u"Can't get DXGI factory, code %u", hr );
return false;
}
DXGI_SWAP_CHAIN_DESC swapChainDesc;
memset( &swapChainDesc, 0, sizeof(swapChainDesc) );
swapChainDesc.BufferDesc = bufferDesc;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = outWindow;
swapChainDesc.BufferCount = 1;
swapChainDesc.Windowed = true/*m_params.m_fullScreen ? false : true*/;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = 0;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
hr = dxgiFactory->CreateSwapChain(
m_d3d11Device,
&swapChainDesc,
&m_SwapChain );
if( FAILED(hr)){
gtLogWriter::printError( u"Can't create Swap Chain : code %u", hr );
return false;
}
dxgiFactory->MakeWindowAssociation( (HWND)m_params.m_outWindow->getHandle(), DXGI_MWA_NO_ALT_ENTER);
dxgiDevice->Release();
dxgiAdapter->Release();
dxgiFactory->Release();
/*HRESULT hr = D3D11CreateDeviceAndSwapChain(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
0,
&featureLevel,
1,
D3D11_SDK_VERSION,
&swapChainDesc,
&m_SwapChain,
&m_d3d11Device,
nullptr,
&m_d3d11DevCon );
if( FAILED( hr ) ){
//0x887A0004
gtLogWriter::printError( u"Can't create Direct3D 11 Device, code : %u", hr );
return false;
}*/
ID3D11Texture2D* BackBuffer;
if( FAILED( m_SwapChain->GetBuffer(
0,
IID_ID3D11Texture2D,
(void**)&BackBuffer ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 back buffer" );
return false;
}
if( FAILED( this->m_d3d11Device->CreateRenderTargetView(
BackBuffer, 0, &m_MainTargetView ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 render target" );
if( BackBuffer ) BackBuffer->Release();
return false;
}
if( BackBuffer ) BackBuffer->Release();
D3D11_TEXTURE2D_DESC DSD;
ZeroMemory( &DSD, sizeof(DSD) );
DSD.Width = m_params.m_backBufferSize.x;
DSD.Height = m_params.m_backBufferSize.y;
DSD.MipLevels = 1;
DSD.ArraySize = 1;
DSD.Format = DXGI_FORMAT_D32_FLOAT;
DSD.SampleDesc.Count = 1;
DSD.SampleDesc.Quality = 0;
DSD.Usage = D3D11_USAGE_DEFAULT;
DSD.BindFlags = D3D11_BIND_DEPTH_STENCIL;
DSD.CPUAccessFlags = 0;
DSD.MiscFlags = 0;
if( FAILED( m_d3d11Device->CreateTexture2D( &DSD, 0, &m_depthStencilBuffer ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 depth stencil buffer" );
return false;
}
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory( &depthStencilDesc, sizeof(depthStencilDesc) );
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask= 0xFF;
depthStencilDesc.StencilWriteMask= 0xFF;
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp= D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp= D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
if( FAILED( m_d3d11Device->CreateDepthStencilState( &depthStencilDesc, &m_depthStencilStateEnabled ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 depth stencil state" );
return false;
}
m_d3d11DevCon->OMSetDepthStencilState( this->m_depthStencilStateEnabled, 0 );
depthStencilDesc.DepthEnable = false;
if( FAILED( m_d3d11Device->CreateDepthStencilState( &depthStencilDesc, &this->m_depthStencilStateDisabled ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 depth stencil state" );
return false;
}
ZeroMemory( &m_depthStencilViewDesc, sizeof( m_depthStencilViewDesc ) );
m_depthStencilViewDesc.Format = DXGI_FORMAT_D32_FLOAT;
m_depthStencilViewDesc.ViewDimension= D3D11_DSV_DIMENSION_TEXTURE2D;
m_depthStencilViewDesc.Texture2D.MipSlice = 0;
if( FAILED( m_d3d11Device->CreateDepthStencilView( m_depthStencilBuffer, &m_depthStencilViewDesc, &m_depthStencilView ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 depth stencil view" );
return false;
}
m_d3d11DevCon->OMSetRenderTargets( 1, &m_MainTargetView, m_depthStencilView );
D3D11_RASTERIZER_DESC rasterDesc;
ZeroMemory( &rasterDesc, sizeof( D3D11_RASTERIZER_DESC ) );
rasterDesc.AntialiasedLineEnable = true;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = true;
rasterDesc.SlopeScaledDepthBias = 0.0f;
if( FAILED( m_d3d11Device->CreateRasterizerState( &rasterDesc, &m_RasterizerSolid ))){
gtLogWriter::printError( u"Can not create rasterizer state" );
return false;
}
rasterDesc.CullMode = D3D11_CULL_NONE;
m_d3d11Device->CreateRasterizerState( &rasterDesc, &m_RasterizerSolidNoBackFaceCulling );
rasterDesc.FillMode = D3D11_FILL_WIREFRAME;
m_d3d11Device->CreateRasterizerState( &rasterDesc, &m_RasterizerWireframeNoBackFaceCulling );
rasterDesc.CullMode = D3D11_CULL_BACK;
m_d3d11Device->CreateRasterizerState( &rasterDesc, &m_RasterizerWireframe );
m_d3d11DevCon->RSSetState( m_RasterizerSolid );
D3D11_BLEND_DESC bd;
memset( &bd, 0, sizeof(bd) );
bd.AlphaToCoverageEnable = 0;
bd.RenderTarget[0].BlendEnable = TRUE;
bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
bd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
if( FAILED( m_d3d11Device->CreateBlendState( &bd, &m_blendStateAlphaEnabled ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 blend state" );
return false;
}
bd.AlphaToCoverageEnable = 1;
if( FAILED( m_d3d11Device->CreateBlendState( &bd, &m_blendStateAlphaEnabledWithATC ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 blend state" );
return false;
}
bd.RenderTarget[0].BlendEnable = FALSE;
if( FAILED( m_d3d11Device->CreateBlendState( &bd, &m_blendStateAlphaDisabled ) ) ){
gtLogWriter::printError( u"Can't create Direct3D 11 blend state" );
return false;
}
enableBlending( true );
scissorClear( true );
setViewport( v2f( m_params.m_backBufferSize ) );
createStandartTexture();
initCSM();
m_shaderProcessing = gtPtrNew<gtShaderProcessingD3D11>( new gtShaderProcessingD3D11(m_d3d11DevCon) );
if( !createShaders() ) return false;
if( m_params.m_fullScreen ){
gtMainSystem::getInstance()->setMainVideoDriver( this );
m_params.m_outWindow->switchToFullscreen();
}
return true;
}
void gtDriverD3D11::setViewport( const v2f& viewportSize ){
D3D11_VIEWPORT viewport;
viewport.Width = viewportSize.x;
viewport.Height = viewportSize.y;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
m_d3d11DevCon->RSSetViewports( 1, &viewport );
}
void gtDriverD3D11::createStandartTexture(){
this->setTextureFilterType( gtTextureFilterType::PPP );
{
gtImage * i = new gtImage;
i->bits = 24u;
i->width = gtConst8U;
i->height = gtConst8U;
i->pitch = i->width * gtConst3U;
i->dataSize = i->pitch * i->height;
i->format = gtImageFormat::R8G8B8;
i->frames = gtConst1U;
i->mipCount = gtConst1U;
//gtMainSystem::getInstance()->allocateMemory( (void**)&i->data, i->dataSize );
i->data = (u8*)gtMemAlloc(i->dataSize);
image::fillCheckerBoard( i, false, gtColor(u8(255),48,224), gtColor(u8(0),0,0) );
m_standartTexture = this->createTexture( i );
//gtMainSystem::getInstance()->freeMemory( (void**)&i->data );
gtMemFree(i->data);
delete i;
}
{
gtImage * i = new gtImage;
i->bits = 24u;
i->width = gtConst8U;
i->height = gtConst8U;
i->pitch = i->width * gtConst3U;
i->dataSize = i->pitch * i->height;
i->format = gtImageFormat::R8G8B8;
i->frames = gtConst1U;
i->mipCount = gtConst1U;
//gtMainSystem::getInstance()->allocateMemory( (void**)&i->data, i->dataSize );
i->data = (u8*)gtMemAlloc(i->dataSize);
image::fillSolid( i, false, gtColor( 1.f ) );
m_standartTextureWhiteColor = this->createTexture( i );
//gtMainSystem::getInstance()->freeMemory( (void**)&i->data );
gtMemFree(i->data);
delete i;
}
this->setTextureFilterType( gtTextureFilterType::Anisotropic );
}
void gtDriverD3D11::enableBlending( bool b, bool atc ){
float blendFactor[4];
blendFactor[0] = 1.0f;
blendFactor[1] = 1.0f;
blendFactor[2] = 1.0f;
blendFactor[3] = 1.0f;
if( b ){
if( atc )
m_d3d11DevCon->OMSetBlendState( m_blendStateAlphaEnabledWithATC, blendFactor, 0xffffffff );
else
m_d3d11DevCon->OMSetBlendState( m_blendStateAlphaEnabled, blendFactor, 0xffffffff );
}else{
m_d3d11DevCon->OMSetBlendState( m_blendStateAlphaDisabled, blendFactor, 0xffffffff );
}
}
void gtDriverD3D11::clearRenderTarget( const gtColor& color ){
m_d3d11DevCon->ClearRenderTargetView( m_MainTargetView, color.getData() );
}
void gtDriverD3D11::beginRender( bool _clearRenderTarget, const gtColor& color ){
if( !m_beginRender ){
m_beginRender = true;
if( _clearRenderTarget )
clearRenderTarget( color );
m_d3d11DevCon->ClearDepthStencilView( m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );
}
}
void gtDriverD3D11::endRender(){
if( m_beginRender ){
if( m_params.m_vSync )
this->m_SwapChain->Present( 1, 0 );
else
this->m_SwapChain->Present( 0, 0 );
m_beginRender = false;
}
}
void gtDriverD3D11::draw2DBox( const v4i& rect, const gtColor& color ){
gtMaterial m;
m.textureLayer[0].texture = m_standartTextureWhiteColor.data();
m.textureLayer[0].diffuseColor = color;
draw2DImage(rect, m );
}
void gtDriverD3D11::draw2DImage( const v4i& rect, gtTexture* texture ){
gtMaterial m;
m.textureLayer[ 0u ].texture = texture;
draw2DImage( rect, v4i(), m );
}
void gtDriverD3D11::draw2DImage( const v4i& rect, const v4i& region, gtTexture* texture ){
gtMaterial m;
m.textureLayer[ 0u ].texture = texture;
draw2DImage( rect, region, m );
}
void gtDriverD3D11::draw2DImage( const v4i& rect, const gtMaterial& m ){
draw2DImage( rect, v4i(), m );
}
void gtDriverD3D11::draw2DImage( const v4i& rect, const v4i& region, const gtMaterial& m ){
auto crc = m_params.m_outWindow->getClientRect();
v2i center( crc.z / 2, crc.w / 2 );
v4f realRect;
realRect.x = f32(rect.x - center.x ) / (f32)center.x;
realRect.y = (f32(rect.y - center.y ) * -1.f )/(f32)center.y;
realRect.z = (rect.z - center.x ) / (f32)center.x;
realRect.w = (f32(rect.w - center.y ) * -1.f )/(f32)center.y;
/*
2-------3
| |
| |
1-------4
*/
v2f lt, rb;
if( v4i() == region ){
lt.x = 0.f;
lt.y = 0.f;
rb.x = 1.f;
rb.y = 1.f;
}else{
GT_ASSERT2( m.textureLayer[ 0u ].texture, "texture != nullptr" );
u32 width = gtConst1U, height = gtConst1U;
if( m.textureLayer[ 0u ].texture ){
width = m.textureLayer[ 0u ].texture->getWidth();
height = m.textureLayer[ 0u ].texture->getHeight();
}
f32 mulX = 1.f / (f32)width;
f32 mulY = 1.f / (f32)height;
lt.x = region.x * mulX;
lt.y = region.y * mulY;
rb.x = region.z * mulX;
rb.y = region.w * mulY;
}
v8f uvs;
uvs.x = lt.x; // 1
uvs.y = rb.y;
uvs.z = lt.x; // 2
uvs.w = lt.y;
uvs.a = rb.x; // 3
uvs.b = lt.y;
uvs.c = rb.x; // 4
uvs.d = rb.y;
_draw2DImage( realRect, uvs, m );
}
void gtDriverD3D11::_draw2DImage( const v4f& rect, const v8f& region, const gtMaterial& material ){
gtShader * shader = material.shader;
if( !shader ){
shader = m_shader2DStandart;
}
setActiveShader( shader );
struct cbVerts{
v4f v1;
v4f v2;
v4f v3;
v4f v4;
v2f t1;
v2f t2;
v2f t3;
v2f t4;
gtColor color;
}cb;
cb.v1.x = rect.x; //x
cb.v1.y = rect.w; //y
cb.v1.z = 0.f; //z *
cb.v1.w = 1.f;
cb.t1.x = region.x; //u
cb.t1.y = region.y; //v
cb.v2.x = rect.x; //x *
cb.v2.y = rect.y; //y |
cb.v2.z = 0.f; //z *
cb.v2.w = 1.f;
cb.t2.x = region.z; //u
cb.t2.y = region.w; //v
cb.v3.x = rect.z; //x *-----*
cb.v3.y = rect.y; //y | /
cb.v3.z = 0.f; //z */
cb.v3.w = 1.f;
cb.t3.x = region.a; //u
cb.t3.y = region.b; //v
cb.v4.x = rect.z; //x *-----*
cb.v4.y = rect.w; //y | /
cb.v4.z = 0.f; //z */ *
cb.v4.w = 1.f;
cb.t4.x = region.c; //u
cb.t4.y = region.d; //v
cb.color = material.textureLayer[0].diffuseColor;
m_d3d11DevCon->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
u32 sz = ((gtShaderImpl*)shader)->m_constantBuffers.size();
struct cbPixel{
float transparent;
float padding[3];
}cb_pixel;
cb_pixel.transparent = material.transparent;
void * cbs[2] =
{
&cb,
&cb_pixel
};
for( u32 i = 0u; i < sz; ++i ){
D3D11_MAPPED_SUBRESOURCE mappedResource;
m_d3d11DevCon->Map(
((gtShaderImpl*)shader)->m_constantBuffers[ i ],
0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );
D3D11_BUFFER_DESC d;
((gtShaderImpl*)shader)->m_constantBuffers[ i ]->GetDesc( &d );
memcpy( mappedResource.pData, cbs[ i ], d.ByteWidth );
m_d3d11DevCon->Unmap( ((gtShaderImpl*)shader)->m_constantBuffers[ i ], 0 );
}
m_d3d11DevCon->VSSetConstantBuffers( 0, 1, &((gtShaderImpl*)shader)->m_constantBuffers[ 0u ] );
m_d3d11DevCon->PSSetConstantBuffers( 0, 1, &((gtShaderImpl*)shader)->m_constantBuffers[ gtConst1U ] );
for( u32 i = 0u; i < 16u; ++i ){
if( !material.textureLayer[ i ].texture ) break;
gtTextureD3D11* texture = (gtTextureD3D11*)material.textureLayer[ i ].texture;
m_d3d11DevCon->PSSetShaderResources( i, 1, texture->getResourceView() );
m_d3d11DevCon->PSSetSamplers( i, 1, texture->getSamplerState() );
}
if( material.flags & (u32)gtMaterialFlag::AlphaBlend )
enableBlending( true );
else
enableBlending( false );
m_d3d11DevCon->Draw( 6, 0 );
}
void gtDriverD3D11::drawModel( gtRenderModel* model, gtArray<gtMaterial>* materials ){
//auto * soft = model->getModel();
gtRenderModelD3D11* d3dm = (gtRenderModelD3D11*)model;
u32 smc = d3dm->m_subs.size();
u32 stride = d3dm->m_stride;
u32 offset = 0u;
for( u32 i( 0u ); i < smc; ++i ){
//auto * sub = soft->getSubModel( i );
// gtMaterial * material = d3dm->getMaterial( i );
gtMaterial * material = nullptr;
if( materials ){
material = &materials->at( i );
}else{
material = d3dm->getMaterial( i );
}
gtShader * shader = material->shader;
if( !shader ){
switch( material->type ){
case gtMaterialType::GUI:
shader = m_shaderGUI;
m_shaderProcessing->setStandartTexture( m_standartTextureWhiteColor.data() );
break;
case gtMaterialType::Standart:
default:
shader = m_shader3DStandart;
m_shaderProcessing->setStandartTexture( m_standartTexture.data() );
break;
case gtMaterialType::Sprite:
shader = m_shaderSprite;
m_shaderProcessing->setStandartTexture( m_standartTexture.data() );
break;
}
}
m_shaderProcessing->setShader( shader );
m_shaderProcessing->setMaterial( material );
gtShaderImpl * shaderD3D11 = ((gtShaderImpl*)shader);
m_d3d11DevCon->IASetInputLayout( ((gtShaderImpl*)shader)->m_vLayout );
m_d3d11DevCon->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
m_d3d11DevCon->IASetVertexBuffers( 0, 1, &d3dm->m_vBuffers[ i ], &stride, &offset );
m_d3d11DevCon->IASetIndexBuffer( d3dm->m_iBuffers[ i ], DXGI_FORMAT_R16_UINT, 0);
m_d3d11DevCon->VSSetShader( ((gtShaderImpl*)shader)->m_vShader, 0, 0 );
m_d3d11DevCon->PSSetShader( ((gtShaderImpl*)shader)->m_pShader, 0, 0 );
if( shaderD3D11->m_callback )
shaderD3D11->m_callback->onShader( *material, m_shaderProcessing.data() );
if( material->flags & (u32)gtMaterialFlag::AlphaBlend )
enableBlending( true, material->alphaToCoverage );
else
enableBlending( false );
if( material->flags & (u32)gtMaterialFlag::Backface ){
if( material->flags & (u32)gtMaterialFlag::Wireframe )
m_d3d11DevCon->RSSetState( m_RasterizerWireframeNoBackFaceCulling );
else
m_d3d11DevCon->RSSetState( m_RasterizerSolidNoBackFaceCulling );
}else{
if( material->flags & (u32)gtMaterialFlag::Wireframe )
m_d3d11DevCon->RSSetState( m_RasterizerWireframe );
else
m_d3d11DevCon->RSSetState( m_RasterizerSolid );
}
m_d3d11DevCon->DrawIndexed( d3dm->m_subs[ i ].iCount, 0, 0 );
}
}
void gtDriverD3D11::drawLine( const v4f& start, const v4f& end, const gtColor& color ){
gtShader * shader = m_shaderLine;
m_shaderProcessing->setShader( shader );
m_shaderProcessing->setMaterial( nullptr );
m_shaderLineCallback->s = start;
m_shaderLineCallback->e = end;
m_shaderLineCallback->c.x = color.getRed();
m_shaderLineCallback->c.y = color.getGreen();
m_shaderLineCallback->c.z = color.getBlue();
m_shaderLineCallback->c.w = color.getAlpha();
m_shaderLineCallback->s.w = 1.f;
m_shaderLineCallback->e.w = 1.f;
if( ((gtShaderImpl*)shader)->m_callback )
((gtShaderImpl*)shader)->m_callback->onShader( gtMaterial(), m_shaderProcessing.data() );
m_d3d11DevCon->IASetInputLayout( 0 );
m_d3d11DevCon->VSSetShader( ((gtShaderImpl*)shader)->m_vShader, 0, 0 );
m_d3d11DevCon->PSSetShader( ((gtShaderImpl*)shader)->m_pShader, 0, 0 );
m_d3d11DevCon->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST );
m_d3d11DevCon->Draw( 2, 0 );
}
gtShader * gtDriverD3D11::getShader(
gtShaderCallback * callback,
const gtString& vertexShader,
const gtStringA& vertexShaderMain,
const gtString& pixelShader,
const gtStringA& pixelShaderMain,
gtShaderModel shaderModel,
gtVertexType * vertexType
){
std::unique_ptr<s8[]> vertexBuffer;
std::unique_ptr<s8[]> pixelBuffer;
gtString fullPathVS = gtFileSystem::getRealPath( vertexShader );
gtString fullPathPS = gtFileSystem::getRealPath( pixelShader );
if( gtFileSystem::existFile( fullPathVS ) ){
gtFile_t file = util::openFileForReadText( fullPathVS );
u32 sz = file->size();
if( !sz ){
gtLogWriter::printError( u"Empty shader file [%s]", fullPathVS.data() );
return nullptr;
}
vertexBuffer.reset( new s8[ sz+gtConst1U ] );
vertexBuffer.get()[sz] = 0;
file->read( (u8*)vertexBuffer.get(), sz );
}else{
u32 sz = vertexShader.size();
if( !sz ){
gtLogWriter::printError( u"Empty shader file [%s]", vertexShader.data() );
return nullptr;
}
vertexBuffer.reset( new s8[ sz+gtConst1U ] );
vertexBuffer.get()[sz] = 0;
auto * data = vertexShader.data();
for( u32 i = 0u; i < sz; ++i ){
auto * b = vertexBuffer.get();
b[ i ] = (s8)data[ i ];
}
}
if( gtFileSystem::existFile( fullPathPS ) ){
gtFile_t file = util::openFileForReadText( fullPathPS );
u32 sz = file->size();
if( !sz ){
gtLogWriter::printError( u"Empty shader file [%s]", fullPathPS.data() );
return nullptr;
}
pixelBuffer.reset( new s8[ sz+1 ] );
pixelBuffer.get()[sz] = 0;
file->read( (u8*)pixelBuffer.get(), sz );
}else{
u32 sz = pixelShader.size();
if( !sz ){
gtLogWriter::printError( u"Empty shader file [%s]", pixelShader.data() );
return nullptr;
}
pixelBuffer.reset( new s8[ sz+1 ] );
pixelBuffer.get()[sz] = 0;
auto * data = pixelShader.data();
for( u32 i = 0u; i < sz; ++i ){
auto * b = pixelBuffer.get();
b[ i ] = (s8)data[ i ];
}
}
gtStringA v_target;
switch( shaderModel.vertexShaderModel ){
case gtShaderModel::shaderModel::_1_1:
case gtShaderModel::shaderModel::_1_2:
case gtShaderModel::shaderModel::_1_3:
case gtShaderModel::shaderModel::_1_4:
case gtShaderModel::shaderModel::_1_5:
v_target = "vs_1_1";
break;
case gtShaderModel::shaderModel::_2_0:
v_target = "vs_2_0";
break;
case gtShaderModel::shaderModel::_3_0:
case gtShaderModel::shaderModel::_3_3:
v_target = "vs_3_0";
break;
case gtShaderModel::shaderModel::_4_0:
v_target = "vs_4_0";
break;
case gtShaderModel::shaderModel::_4_1:
case gtShaderModel::shaderModel::_4_2:
case gtShaderModel::shaderModel::_4_3:
case gtShaderModel::shaderModel::_4_5:
v_target = "vs_4_1";
break;
case gtShaderModel::shaderModel::_5_0:
v_target = "vs_5_0";
break;
case gtShaderModel::shaderModel::_6_0:
v_target = "vs_6_0";
break;
}
gtStringA p_target;
switch( shaderModel.pixelShaderModel ){
case gtShaderModel::shaderModel::_1_1:
case gtShaderModel::shaderModel::_1_2:
case gtShaderModel::shaderModel::_1_3:
case gtShaderModel::shaderModel::_1_4:
case gtShaderModel::shaderModel::_1_5:
p_target = "ps_1_1";
break;
case gtShaderModel::shaderModel::_2_0:
p_target = "ps_2_0";
break;
case gtShaderModel::shaderModel::_3_0:
case gtShaderModel::shaderModel::_3_3:
p_target = "ps_3_0";
break;
case gtShaderModel::shaderModel::_4_0:
p_target = "ps_4_0";
break;
case gtShaderModel::shaderModel::_4_1:
case gtShaderModel::shaderModel::_4_2:
case gtShaderModel::shaderModel::_4_3:
case gtShaderModel::shaderModel::_4_5:
p_target = "ps_4_1";
break;
case gtShaderModel::shaderModel::_5_0:
p_target = "ps_5_0";
break;
case gtShaderModel::shaderModel::_6_0:
p_target = "ps_6_0";
break;
}
gtPtr< gtShaderImpl > shader = gtPtrNew< gtShaderImpl >( new gtShaderImpl(this) );
if( !shader->compileShader(
callback,
v_target,
p_target,
vertexBuffer.get(),
pixelBuffer.get(),
(s8*)vertexShaderMain.data(),
(s8*)pixelShaderMain.data(),
vertexType ) ){
return nullptr;
}
shader->addRef();
return shader.data();
}
void gtDriverD3D11::setRenderTarget( gtTexture * rtt, bool clearDepth, bool clearTarget, const gtColor& color ){
v2f viewport;
ID3D11RenderTargetView* rtv = nullptr;
if( rtt ){
gtTextureD3D11 * t = (gtTextureD3D11 *)rtt;
rtv = *t->getRenderTargetView();
viewport = v2f( (f32)rtt->getWidth(), (f32)rtt->getHeight() );
}else{
rtv = m_MainTargetView;
viewport = v2f( m_params.m_backBufferSize );
}
m_d3d11DevCon->OMSetRenderTargets(1, &rtv, m_depthStencilView);
if( clearTarget )
m_d3d11DevCon->ClearRenderTargetView( rtv, color.getData() );
if( clearDepth )
m_d3d11DevCon->ClearDepthStencilView( m_depthStencilView, D3D11_CLEAR_DEPTH, 1.f, 0 );
setViewport( viewport );
}
gtPtr<gtTexture> gtDriverD3D11::createRenderTargetTexture( const v2u& size, gtImageFormat pixelFormat ){
auto ptr = new gtTextureD3D11( this );
gtPtr<gtTexture> texture = gtPtrNew<gtTexture>( ptr );
gtImage image;
image.width = size.x;
image.height = size.y;
image.format = pixelFormat;
image.frames = -1;
if( !ptr->init( &image ) ){
gtLogWriter::printWarning( u"Can not init D3D11 render target texture" );
return nullptr;
}
return texture;
}
gtPtr<gtTexture> gtDriverD3D11::createTexture( gtImage* image ){
GT_ASSERT2( image, "gtImage != nullptr" );
auto ptr = new gtTextureD3D11( this );
gtPtr<gtTexture> texture = gtPtrNew<gtTexture>( ptr );
if( !ptr->init( image ) ){
gtLogWriter::printWarning( u"Can not init D3D11 texture" );
return nullptr;
}
return texture;
}
gtPtr<gtRenderModel> gtDriverD3D11::createModel( gtModel* m, gtRenderModelInfo * info ){
GT_ASSERT2( m, "gtModel != nullptr" );
auto ptr = new gtRenderModelD3D11( this );
gtPtr<gtRenderModel> model = gtPtrNew<gtRenderModel>( ptr );
if( !ptr->init( m, info ) ){
gtLogWriter::printWarning( u"Can not init D3D11 model" );
return nullptr;
}
return model;
}
bool gtDriverD3D11::createShaders(){
gtShaderModel shaderModel;
shaderModel.pixelShaderModel = gtShaderModel::shaderModel::_5_0;
shaderModel.vertexShaderModel = gtShaderModel::shaderModel::_5_0;
gtVertexType vertexType2D[] = {
gtVertexType::Position,
gtVertexType::End
};
m_shader2DStandart = getShader(
nullptr,
u"../shaders/2d_basic.hlsl",
"VSMain",
u"../shaders/2d_basic.hlsl",
"PSMain",
shaderModel,
vertexType2D
);
if( m_shader2DStandart ){
if( !m_shader2DStandart->createShaderObject( 96u + (sizeof(v4f)) ) ) return false;
if( !m_shader2DStandart->createShaderObject( 16u ) ) return false;
}
gtVertexType vertexType3D[] =
{
gtVertexType::Position,
gtVertexType::UV,
gtVertexType::Normal,
gtVertexType::End
};
gtVertexType vertexTypeGUI[] =
{
gtVertexType::Position,
gtVertexType::UV,
gtVertexType::Normal,
gtVertexType::Color,
gtVertexType::End
};
m_shader3DStandartCallback = gtPtrNew<gtD3D11StandartShaderCallback>( new gtD3D11StandartShaderCallback );
m_shaderGUICallback = gtPtrNew<gtD3D11GUIShaderCallback>( new gtD3D11GUIShaderCallback );
m_shaderSpriteCallback = gtPtrNew<gtD3D11SpriteShaderCallback>( new gtD3D11SpriteShaderCallback );
m_shaderLineCallback = gtPtrNew<gtD3D11LineShaderCallback>( new gtD3D11LineShaderCallback );
m_shader3DStandart = getShader( m_shader3DStandartCallback.data(), u"../shaders/3d_basic.hlsl", "VSMain",
u"../shaders/3d_basic.hlsl", "PSMain", shaderModel, vertexType3D );
m_shaderGUI = getShader( m_shaderGUICallback.data(), u"../shaders/GUI.hlsl", "VSMain",
u"../shaders/GUI.hlsl", "PSMain", shaderModel, vertexTypeGUI );
m_shaderSprite = getShader( m_shaderSpriteCallback.data(), u"../shaders/sprite.hlsl", "VSMain",
u"../shaders/sprite.hlsl", "PSMain", shaderModel, vertexType3D );
m_shaderLine = getShader( m_shaderLineCallback.data(), u"../shaders/line.hlsl", "VSMain",
u"../shaders/line.hlsl", "PSMain", shaderModel, vertexType2D );
if( m_shader3DStandart ) if( !m_shader3DStandart->createShaderObject( (16u * 5u * sizeof(f32))) ) return false;
if( m_shader3DStandart ) if( !m_shader3DStandart->createShaderObject( (sizeof(v4f)*6)+sizeof(s32)*8u ) ) return false;
if( m_shaderSprite ) if( !m_shaderSprite->createShaderObject( 24u * sizeof(f32) ) ) return false;
if( m_shaderLine ) if( !m_shaderLine->createShaderObject( 28u * sizeof(f32) ) ) return false;
if( m_shaderGUI ) if( !m_shaderGUI->createShaderObject( gtConst8U * sizeof(f32) ) ) return false;
return true;
}
void gtDriverD3D11::applyScissor(){
m_d3d11DevCon->RSSetScissorRects( m_scissorRects.size(), (D3D11_RECT*)m_scissorRects.data() );
}
// D3DX_PI / 4, 1.0f, 0.1f , 1000.0f
void CSMCallback(gtCamera* camera){
gtMatrix4 P, V;
math::makePerspectiveRHMatrix( P, camera->getFOV(),
camera->getAspect(), camera->getNear(), camera->getFar() );
math::makeLookAtRHMatrix( camera->getPosition(), camera->getTarget(),
camera->getUpVector(), V );
camera->setViewMatrix( V );
camera->setProjectionMatrix( P );
}
void gtDriverD3D11::initCSM(){
m_CSMLightCamera = gtMainSystem::getInstance()->getSceneSystem( nullptr )->addCamera();
m_CSMLightCamera->addRef(); //возможно нужно сделать это чтобы clearScene не удалил камеру
m_CSMLightCamera->setName( "CSMLightCamera" );
m_CSMLightCamera->setPosition( v4f( -320.f, 300.f, -220.3f ) );
m_CSMLightCamera->setTarget( v4f( 0.f, 0.f, 0.f ) );
m_CSMLightCamera->setCameraType( gtCameraType::Custom );
m_CSMLightCamera->setUpdateCallback( CSMCallback );
m_CSMLightCamera->setFOV( math::PI / 4.f );
m_CSMLightCamera->setAspect( 1.0f );
m_CSMLightCamera->setNear( 0.1f );
m_CSMLightCamera->setFar( 1000.f );
}
void gtDriverD3D11::renderEffects(){
}
gtTexture* gtDriverD3D11::getDefaultTexture(){
return m_standartTextureWhiteColor.data();
}
/*
Copyright (c) 2017-2018 532235
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.
*/ | 30.284768 | 144 | 0.719714 | [
"render",
"model"
] |
d94a0b5ac093df1e395992a4aec94f2c45f30a0e | 1,202 | hpp | C++ | src/client/headers/shared.hpp | brainslush/intercept | fd9bdade3174ba43ab39357593fcdd0ae0cbb56a | [
"MIT"
] | null | null | null | src/client/headers/shared.hpp | brainslush/intercept | fd9bdade3174ba43ab39357593fcdd0ae0cbb56a | [
"MIT"
] | null | null | null | src/client/headers/shared.hpp | brainslush/intercept | fd9bdade3174ba43ab39357593fcdd0ae0cbb56a | [
"MIT"
] | null | null | null | #pragma once
// This is a warning normally for returning references to local/stack allocated variables
// It is so dangerous though that we need to force it as a warning because it can break
// everything.
#pragma warning( error : 4172 )
#ifdef _WIN32
// #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#endif
#include <assert.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <memory>
#include <cmath>
#include <cstdint>
#include <streambuf>
#include <istream>
#include <variant>
#include <optional>
#ifdef _DEBUG
#define ZERO_OUTPUT() { memset(output, 0x00, outputSize); }
#define EXTENSION_RETURN() {output[outputSize-1] = 0x00; } return;
#else
#define ZERO_OUTPUT()
#define EXTENSION_RETURN() return;
#endif
#ifdef _DEBUG
#define INTERCEPT_ASSERT assert()
#else
#define INTERCEPT_ASSERT intercept::runtime_assert()
#endif
#ifdef __GNUC__
#define CDECL __attribute__ ((__cdecl__))
#else
#undef CDECL
#define CDECL __cdecl
#endif
#ifdef __GNUC__
#define DLLEXPORT __attribute__((visibility("default")))
#else
#define DLLEXPORT __declspec(dllexport)
#endif | 22.679245 | 90 | 0.722962 | [
"vector"
] |
d94a25ac75dd09d7bbb088b7f183fb06199fac34 | 1,216 | cpp | C++ | codebase/arrays/05_remove_element/remove_element.cpp | olpotkin/ds_and_algos_modern_cpp | 12876686a8fb26bc9358930378d235d4470bb6fc | [
"MIT"
] | null | null | null | codebase/arrays/05_remove_element/remove_element.cpp | olpotkin/ds_and_algos_modern_cpp | 12876686a8fb26bc9358930378d235d4470bb6fc | [
"MIT"
] | null | null | null | codebase/arrays/05_remove_element/remove_element.cpp | olpotkin/ds_and_algos_modern_cpp | 12876686a8fb26bc9358930378d235d4470bb6fc | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cassert>
/// Remove Elements from Array (in-place)
///
/// Given an array nums and a value val, remove all instances of that
/// value in-place and return the new length.
///
/// Do not allocate extra space for another array, you must do this by modifying
/// the input array in-place with O(1) extra memory.
///
/// The order of elements can be changed. It doesn't matter what you leave beyond the new length.
int removeElement(std::vector<int>& nums, const int val) {
int i = 0;
for (int j = 0; j < nums.size(); ++j) {
if (nums[j] != val) {
nums[i] = nums[j];
++i;
}
}
return i;
}
void test_solution() {
/// Function should return length = 2, with the first two elements of nums being 2.
std::vector<int> input_1 {3, 2, 2, 3};
assert(removeElement(input_1, 3) == 2);
std::cout << "Test 1 passed..." << std::endl;
/// Function should return length = 5, with the first five elements of nums
/// containing 0, 1, 3, 0, and 4.
std::vector<int> input_2 {0, 1, 2, 2, 3, 0, 4, 2};
assert(removeElement(input_2, 2) == 5);
std::cout << "Test 2 passed..." << std::endl;
}
int main() {
test_solution();
return 0;
}
| 24.32 | 97 | 0.625822 | [
"vector"
] |
d94da65dde7227a3944ae76673aff9d945a03ae0 | 13,797 | cpp | C++ | src/qt/qtbase/src/plugins/platforms/android/qandroidplatformintegration.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/plugins/platforms/android/qandroidplatformintegration.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/plugins/platforms/android/qandroidplatformintegration.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qandroidplatformintegration.h"
#include <QtCore/private/qjni_p.h>
#include <QGuiApplication>
#include <QOpenGLContext>
#include <QThread>
#include <QOffscreenSurface>
#include <QtPlatformSupport/private/qeglpbuffer_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <qpa/qplatformwindow.h>
#include <qpa/qplatformoffscreensurface.h>
#include "androidjnimain.h"
#include "qabstracteventdispatcher.h"
#include "qandroideventdispatcher.h"
#include "qandroidplatformbackingstore.h"
#include "qandroidplatformaccessibility.h"
#include "qandroidplatformclipboard.h"
#include "qandroidplatformforeignwindow.h"
#include "qandroidplatformfontdatabase.h"
#include "qandroidplatformopenglcontext.h"
#include "qandroidplatformopenglwindow.h"
#include "qandroidplatformscreen.h"
#include "qandroidplatformservices.h"
#include "qandroidplatformtheme.h"
#include "qandroidsystemlocale.h"
QT_BEGIN_NAMESPACE
int QAndroidPlatformIntegration::m_defaultGeometryWidth = 320;
int QAndroidPlatformIntegration::m_defaultGeometryHeight = 455;
int QAndroidPlatformIntegration::m_defaultScreenWidth = 320;
int QAndroidPlatformIntegration::m_defaultScreenHeight = 455;
int QAndroidPlatformIntegration::m_defaultPhysicalSizeWidth = 50;
int QAndroidPlatformIntegration::m_defaultPhysicalSizeHeight = 71;
Qt::ScreenOrientation QAndroidPlatformIntegration::m_orientation = Qt::PrimaryOrientation;
Qt::ScreenOrientation QAndroidPlatformIntegration::m_nativeOrientation = Qt::PrimaryOrientation;
void *QAndroidPlatformNativeInterface::nativeResourceForIntegration(const QByteArray &resource)
{
if (resource=="JavaVM")
return QtAndroid::javaVM();
if (resource == "QtActivity")
return QtAndroid::activity();
if (resource == "AndroidStyleData") {
if (m_androidStyle) {
if (m_androidStyle->m_styleData.isEmpty())
m_androidStyle->m_styleData = AndroidStyle::loadStyleData();
return &m_androidStyle->m_styleData;
}
else
return Q_NULLPTR;
}
if (resource == "AndroidStandardPalette") {
if (m_androidStyle)
return &m_androidStyle->m_standardPalette;
else
return Q_NULLPTR;
}
if (resource == "AndroidQWidgetFonts") {
if (m_androidStyle)
return &m_androidStyle->m_QWidgetsFonts;
else
return Q_NULLPTR;
}
if (resource == "AndroidDeviceName") {
static QString deviceName = QtAndroid::deviceName();
return &deviceName;
}
return 0;
}
QAndroidPlatformIntegration::QAndroidPlatformIntegration(const QStringList ¶mList)
: m_touchDevice(0)
#ifndef QT_NO_ACCESSIBILITY
, m_accessibility(0)
#endif
{
Q_UNUSED(paramList);
m_androidPlatformNativeInterface = new QAndroidPlatformNativeInterface();
m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (m_eglDisplay == EGL_NO_DISPLAY)
qFatal("Could not open egl display");
EGLint major, minor;
if (!eglInitialize(m_eglDisplay, &major, &minor))
qFatal("Could not initialize egl display");
if (!eglBindAPI(EGL_OPENGL_ES_API))
qFatal("Could not bind GL_ES API");
m_primaryScreen = new QAndroidPlatformScreen();
screenAdded(m_primaryScreen);
m_primaryScreen->setPhysicalSize(QSize(m_defaultPhysicalSizeWidth, m_defaultPhysicalSizeHeight));
m_primaryScreen->setSize(QSize(m_defaultScreenWidth, m_defaultScreenHeight));
m_primaryScreen->setAvailableGeometry(QRect(0, 0, m_defaultGeometryWidth, m_defaultGeometryHeight));
m_mainThread = QThread::currentThread();
QtAndroid::setAndroidPlatformIntegration(this);
m_androidFDB = new QAndroidPlatformFontDatabase();
m_androidPlatformServices = new QAndroidPlatformServices();
#ifndef QT_NO_CLIPBOARD
m_androidPlatformClipboard = new QAndroidPlatformClipboard();
#endif
m_androidSystemLocale = new QAndroidSystemLocale;
QJNIObjectPrivate javaActivity(QtAndroid::activity());
if (javaActivity.isValid()) {
QJNIObjectPrivate resources = javaActivity.callObjectMethod("getResources", "()Landroid/content/res/Resources;");
QJNIObjectPrivate configuration = resources.callObjectMethod("getConfiguration", "()Landroid/content/res/Configuration;");
int touchScreen = configuration.getField<jint>("touchscreen");
if (touchScreen == QJNIObjectPrivate::getStaticField<jint>("android/content/res/Configuration", "TOUCHSCREEN_FINGER")
|| touchScreen == QJNIObjectPrivate::getStaticField<jint>("android/content/res/Configuration", "TOUCHSCREEN_STYLUS"))
{
m_touchDevice = new QTouchDevice;
m_touchDevice->setType(QTouchDevice::TouchScreen);
m_touchDevice->setCapabilities(QTouchDevice::Position
| QTouchDevice::Area
| QTouchDevice::Pressure
| QTouchDevice::NormalizedPosition);
QJNIObjectPrivate pm = javaActivity.callObjectMethod("getPackageManager", "()Landroid/content/pm/PackageManager;");
Q_ASSERT(pm.isValid());
if (pm.callMethod<jboolean>("hasSystemFeature","(Ljava/lang/String;)Z",
QJNIObjectPrivate::getStaticObjectField("android/content/pm/PackageManager", "FEATURE_TOUCHSCREEN_MULTITOUCH_JAZZHAND", "Ljava/lang/String;").object())) {
m_touchDevice->setMaximumTouchPoints(10);
} else if (pm.callMethod<jboolean>("hasSystemFeature","(Ljava/lang/String;)Z",
QJNIObjectPrivate::getStaticObjectField("android/content/pm/PackageManager", "FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT", "Ljava/lang/String;").object())) {
m_touchDevice->setMaximumTouchPoints(4);
} else if (pm.callMethod<jboolean>("hasSystemFeature","(Ljava/lang/String;)Z",
QJNIObjectPrivate::getStaticObjectField("android/content/pm/PackageManager", "FEATURE_TOUCHSCREEN_MULTITOUCH", "Ljava/lang/String;").object())) {
m_touchDevice->setMaximumTouchPoints(2);
}
QWindowSystemInterface::registerTouchDevice(m_touchDevice);
}
}
}
bool QAndroidPlatformIntegration::needsBasicRenderloopWorkaround()
{
static bool needsWorkaround =
QtAndroid::deviceName().compare(QLatin1String("samsung SM-T211"), Qt::CaseInsensitive) == 0
|| QtAndroid::deviceName().compare(QLatin1String("samsung SM-T210"), Qt::CaseInsensitive) == 0
|| QtAndroid::deviceName().compare(QLatin1String("samsung SM-T215"), Qt::CaseInsensitive) == 0;
return needsWorkaround;
}
bool QAndroidPlatformIntegration::hasCapability(Capability cap) const
{
switch (cap) {
case ThreadedPixmaps: return true;
case ApplicationState: return true;
case NativeWidgets: return true;
case OpenGL: return true;
case ForeignWindows: return true;
case ThreadedOpenGL:
if (needsBasicRenderloopWorkaround())
return false;
else
return true;
case RasterGLSurface: return true;
default:
return QPlatformIntegration::hasCapability(cap);
}
}
QPlatformBackingStore *QAndroidPlatformIntegration::createPlatformBackingStore(QWindow *window) const
{
return new QAndroidPlatformBackingStore(window);
}
QPlatformOpenGLContext *QAndroidPlatformIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
{
QSurfaceFormat format(context->format());
format.setAlphaBufferSize(8);
format.setRedBufferSize(8);
format.setGreenBufferSize(8);
format.setBlueBufferSize(8);
return new QAndroidPlatformOpenGLContext(format, context->shareHandle(), m_eglDisplay);
}
QPlatformOffscreenSurface *QAndroidPlatformIntegration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const
{
QSurfaceFormat format(surface->requestedFormat());
format.setAlphaBufferSize(8);
format.setRedBufferSize(8);
format.setGreenBufferSize(8);
format.setBlueBufferSize(8);
return new QEGLPbuffer(m_eglDisplay, format, surface);
}
QPlatformWindow *QAndroidPlatformIntegration::createPlatformWindow(QWindow *window) const
{
if (window->type() == Qt::ForeignWindow)
return new QAndroidPlatformForeignWindow(window);
else
return new QAndroidPlatformOpenGLWindow(window, m_eglDisplay);
}
QAbstractEventDispatcher *QAndroidPlatformIntegration::createEventDispatcher() const
{
return new QAndroidEventDispatcher;
}
QAndroidPlatformIntegration::~QAndroidPlatformIntegration()
{
if (m_eglDisplay != EGL_NO_DISPLAY)
eglTerminate(m_eglDisplay);
delete m_androidPlatformNativeInterface;
delete m_androidFDB;
delete m_androidSystemLocale;
#ifndef QT_NO_CLIPBOARD
delete m_androidPlatformClipboard;
#endif
QtAndroid::setAndroidPlatformIntegration(NULL);
}
QPlatformFontDatabase *QAndroidPlatformIntegration::fontDatabase() const
{
return m_androidFDB;
}
#ifndef QT_NO_CLIPBOARD
QPlatformClipboard *QAndroidPlatformIntegration::clipboard() const
{
return m_androidPlatformClipboard;
}
#endif
QPlatformInputContext *QAndroidPlatformIntegration::inputContext() const
{
return &m_platformInputContext;
}
QPlatformNativeInterface *QAndroidPlatformIntegration::nativeInterface() const
{
return m_androidPlatformNativeInterface;
}
QPlatformServices *QAndroidPlatformIntegration::services() const
{
return m_androidPlatformServices;
}
QVariant QAndroidPlatformIntegration::styleHint(StyleHint hint) const
{
switch (hint) {
case ShowIsMaximized:
return true;
default:
return QPlatformIntegration::styleHint(hint);
}
}
Qt::WindowState QAndroidPlatformIntegration::defaultWindowState(Qt::WindowFlags flags) const
{
// Don't maximize dialogs on Android
if (flags & Qt::Dialog & ~Qt::Window)
return Qt::WindowNoState;
return QPlatformIntegration::defaultWindowState(flags);
}
static const QLatin1String androidThemeName("android");
QStringList QAndroidPlatformIntegration::themeNames() const
{
return QStringList(QString(androidThemeName));
}
QPlatformTheme *QAndroidPlatformIntegration::createPlatformTheme(const QString &name) const
{
if (androidThemeName == name)
return new QAndroidPlatformTheme(m_androidPlatformNativeInterface);
return 0;
}
void QAndroidPlatformIntegration::setDefaultDisplayMetrics(int gw, int gh, int sw, int sh, int screenWidth, int screenHeight)
{
m_defaultGeometryWidth = gw;
m_defaultGeometryHeight = gh;
m_defaultPhysicalSizeWidth = sw;
m_defaultPhysicalSizeHeight = sh;
m_defaultScreenWidth = screenWidth;
m_defaultScreenHeight = screenHeight;
}
void QAndroidPlatformIntegration::setDefaultDesktopSize(int gw, int gh)
{
m_defaultGeometryWidth = gw;
m_defaultGeometryHeight = gh;
}
void QAndroidPlatformIntegration::setScreenOrientation(Qt::ScreenOrientation currentOrientation,
Qt::ScreenOrientation nativeOrientation)
{
m_orientation = currentOrientation;
m_nativeOrientation = nativeOrientation;
}
#ifndef QT_NO_ACCESSIBILITY
QPlatformAccessibility *QAndroidPlatformIntegration::accessibility() const
{
if (!m_accessibility)
m_accessibility = new QAndroidPlatformAccessibility();
return m_accessibility;
}
#endif
void QAndroidPlatformIntegration::setDesktopSize(int width, int height)
{
if (m_primaryScreen)
QMetaObject::invokeMethod(m_primaryScreen, "setAvailableGeometry", Qt::AutoConnection, Q_ARG(QRect, QRect(0,0,width, height)));
}
void QAndroidPlatformIntegration::setDisplayMetrics(int width, int height)
{
if (m_primaryScreen)
QMetaObject::invokeMethod(m_primaryScreen, "setPhysicalSize", Qt::AutoConnection, Q_ARG(QSize, QSize(width, height)));
}
void QAndroidPlatformIntegration::setScreenSize(int width, int height)
{
if (m_primaryScreen)
QMetaObject::invokeMethod(m_primaryScreen, "setSize", Qt::AutoConnection, Q_ARG(QSize, QSize(width, height)));
}
QT_END_NAMESPACE
| 36.792 | 198 | 0.725593 | [
"object"
] |
d950a951c46bb4bd45385c207a8597775ab513cf | 2,193 | hpp | C++ | AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/closest_points/geographic.hpp | kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine- | 72c8f34b6b6d507319069e681ff8c5008337b7c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/closest_points/geographic.hpp | kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine- | 72c8f34b6b6d507319069e681ff8c5008337b7c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/closest_points/geographic.hpp | kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine- | 72c8f34b6b6d507319069e681ff8c5008337b7c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | // Boost.Geometry
// Copyright (c) 2021, Oracle and/or its affiliates.
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_GEOMETRY_STRATEGIES_CLOSEST_POINTS_GEOGRAPHIC_HPP
#define BOOST_GEOMETRY_STRATEGIES_CLOSEST_POINTS_GEOGRAPHIC_HPP
#include <boost/geometry/strategies/detail.hpp>
#include <boost/geometry/strategies/distance/detail.hpp>
#include <boost/geometry/strategies/closest_points/services.hpp>
#include <boost/geometry/strategies/geographic/closest_points_pt_seg.hpp>
#include <boost/geometry/strategies/geographic/parameters.hpp>
#include <boost/geometry/strategies/distance/geographic.hpp>
#include <boost/geometry/util/type_traits.hpp>
namespace boost { namespace geometry
{
namespace strategies { namespace closest_points
{
template
<
typename FormulaPolicy = geometry::strategy::andoyer,
typename Spheroid = srs::spheroid<double>,
typename CalculationType = void
>
class geographic
: public strategies::distance::geographic<FormulaPolicy, Spheroid, CalculationType>
{
using base_t = strategies::distance::geographic<FormulaPolicy, Spheroid, CalculationType>;
public:
geographic() = default;
explicit geographic(Spheroid const& spheroid)
: base_t(spheroid)
{}
template <typename Geometry1, typename Geometry2>
auto closest_points(Geometry1 const&, Geometry2 const&,
distance::detail::enable_if_ps_t<Geometry1, Geometry2> * = nullptr) const
{
return strategy::closest_points::geographic_cross_track
<
FormulaPolicy,
Spheroid,
CalculationType
>(base_t::m_spheroid);
}
};
namespace services
{
template <typename Geometry1, typename Geometry2>
struct default_strategy<Geometry1, Geometry2, geographic_tag, geographic_tag>
{
using type = strategies::closest_points::geographic<>;
};
} // namespace services
}} // namespace strategies::closest_points
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGIES_CLOSEST_POINTS_GEOGRAPHIC_HPP
| 27.759494 | 97 | 0.743274 | [
"geometry"
] |
d95652c960de75a951e6e97c47255b66e0e56da8 | 14,513 | cpp | C++ | vmcon2D/MusculoSkeletalSystem.cpp | snumrl/volcon2D | 4b4277cef2caa0f62429781acedc71d9f8b6bd0d | [
"Apache-2.0"
] | null | null | null | vmcon2D/MusculoSkeletalSystem.cpp | snumrl/volcon2D | 4b4277cef2caa0f62429781acedc71d9f8b6bd0d | [
"Apache-2.0"
] | null | null | null | vmcon2D/MusculoSkeletalSystem.cpp | snumrl/volcon2D | 4b4277cef2caa0f62429781acedc71d9f8b6bd0d | [
"Apache-2.0"
] | null | null | null | #include "MusculoSkeletalSystem.h"
#include "DART_Interface.h"
#include <tinyxml.h>
using namespace dart::dynamics;
using namespace dart::simulation;
using namespace FEM;
Eigen::Vector2d GetPoint(const AnchorPoint& p)
{
Eigen::Vector3d point = p.first->getTransform()*p.second;
return Eigen::Vector2d(point[0],point[1]);
}
void
Muscle::
TransferForce(Eigen::Vector2d& f_origin,Eigen::Vector2d& f_insertion)
{
int no = originWayPoints.size();
int ni = insertionWayPoints.size();
if(no>1)
{
Eigen::Vector2d u = (GetPoint(insertionWayPoints[0])-GetPoint(originWayPoints[0])).normalized();
Eigen::Vector2d v = (GetPoint(originWayPoints[no-2])-GetPoint(originWayPoints[no-1])).normalized();
double angle = acos(u.dot(v));
double sign = u[0]*v[1] - u[1]*v[0];
if(sign<0)
angle = -angle;
Eigen::Rotation2D<double> R(angle);
f_origin = R*f_origin;
}
if(ni>1)
{
Eigen::Vector2d u = (GetPoint(originWayPoints[0])-GetPoint(insertionWayPoints[0])).normalized();
Eigen::Vector2d v = (GetPoint(insertionWayPoints[ni-2])-GetPoint(insertionWayPoints[ni-1])).normalized();
double angle = acos(u.dot(v));
double sign = u[0]*v[1] - u[1]*v[0];
if(sign<0)
angle = -angle;
Eigen::Rotation2D<double> R(angle);
f_insertion = R*f_insertion;
}
}
MusculoSkeletalSystem::
MusculoSkeletalSystem()
:mTendonStiffness(1E5),mMuscleStiffness(1E6),mYoungsModulus(1E6),mPoissonRatio(0.3)
{
}
void
MusculoSkeletalSystem::
AddMuscle(
const std::vector<AnchorPoint>& origin,
const int& origin_i,
const std::vector<AnchorPoint>& insertion,
const int& insertion_i,
const Eigen::Vector2d& fiber_direction,
Mesh* mesh)
{
mMuscles.push_back(new Muscle());
auto muscle = mMuscles.back();
muscle->mesh = mesh;
muscle->originWayPoints = origin;
muscle->insertionWayPoints = insertion;
std::vector<Eigen::Vector2d> p_origin,p_insertion;
double l0_origin=0,l0_insertion=0;
const auto& vertices = muscle->mesh->GetVertices();
const auto& triangles = muscle->mesh->GetTriangles();
for(int i=0;i<origin.size();i++)
p_origin.push_back(GetPoint(origin[i]));
for(int i=0;i<p_origin.size()-1;i++)
l0_origin += (p_origin[i] - p_origin[i+1]).norm();
l0_origin += (p_origin[0]- vertices[origin_i]).norm();
for(int i=0;i<insertion.size();i++)
p_insertion.push_back(GetPoint(insertion[i]));
for(int i=0;i<p_insertion.size()-1;i++)
l0_insertion += (p_insertion[i] - p_insertion[i+1]).norm();
l0_insertion += (p_insertion[0]- vertices[insertion_i]).norm();
for(const auto& tri : triangles)
{
int i0,i1,i2;
Eigen::Vector2d p0,p1,p2;
i0 = tri[0];
i1 = tri[1];
i2 = tri[2];
p0 = vertices[i0];
p1 = vertices[i1];
p2 = vertices[i2];
Eigen::Matrix2d Dm;
Dm.block<2,1>(0,0) = p1 - p0;
Dm.block<2,1>(0,1) = p2 - p0;
if(Dm.determinant()<0)
{
i0 = tri[0];
i1 = tri[2];
i2 = tri[1];
p0 = vertices[i0];
p1 = vertices[i1];
p2 = vertices[i2];
Dm.block<2,1>(0,0) = p1 - p0;
Dm.block<2,1>(0,1) = p2 - p0;
muscle->constraints.push_back(new CorotateFEMConstraint(mYoungsModulus,mPoissonRatio,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));
// muscle->constraints.push_back(new SpringConstraint(10000.0,i0,i1,(p0-p1).norm()));
// muscle->constraints.push_back(new SpringConstraint(10000.0,i1,i2,(p1-p2).norm()));
// muscle->constraints.push_back(new SpringConstraint(10000.0,i2,i0,(p2-p0).norm()));
muscle->muscleConstraints.push_back(new LinearMuscleConstraint(mMuscleStiffness,fiber_direction,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));
// muscle->muscleConstraints.push_back(new HillTypeMuscleConstraint(mMuscleStiffness,fiber_direction,i0,i1,i2,1.0/6.0*(Dm.determinant()),Dm.inverse()));
}
}
muscle->origin = new AttachmentConstraint(mTendonStiffness,origin_i,p_origin[0]);
muscle->insertion = new AttachmentConstraint(mTendonStiffness,insertion_i,p_insertion[0]);
mAttachementConstraintVector.push_back(muscle->origin);
mAttachementConstraintVector.push_back(muscle->insertion);
muscle->activationLevel = 0.0;
}
void
MusculoSkeletalSystem::
Initialize(FEM::World* world)
{
int offset = world->GetNumVertices();
for(int i=0;i<mMuscles.size();i++)
{
Muscle* muscle = mMuscles[i];
const std::vector<Eigen::Vector2d>& vertices = muscle->mesh->GetVertices();
muscle->origin->AddOffset(offset);
muscle->insertion->AddOffset(offset);
for(auto& c : muscle->constraints)
c->AddOffset(offset);
for(auto& c : muscle->muscleConstraints)
c->AddOffset(offset);
Eigen::VectorXd v(vertices.size()*2);
for(int i =0;i<vertices.size();i++)
v.block<2,1>(i*2,0) = vertices[i];
world->AddBody(v,muscle->constraints,1.0);
for(auto& c: muscle->muscleConstraints)
world->AddConstraint(c);
world->AddConstraint(muscle->origin);
world->AddConstraint(muscle->insertion);
offset += vertices.size();
}
mActivationLevel.resize(mMuscles.size());
mActivationLevel.setZero();
}
void
MusculoSkeletalSystem::
TransformAttachmentPoints()
{
for(auto& muscle : mMuscles)
{
auto& origin_way_points = muscle->originWayPoints;
auto& insertion_way_points = muscle->insertionWayPoints;
auto po = GetPoint(origin_way_points[0]);
auto pi = GetPoint(insertion_way_points[0]);
muscle->origin->GetP() = po;
muscle->insertion->GetP() = pi;
}
}
void
MusculoSkeletalSystem::
SetActivationLevel(const Eigen::VectorXd& a)
{
mActivationLevel = a;
for(int i=0;i<mMuscles.size();i++)
for(auto& mc : mMuscles[i]->muscleConstraints)
mc->SetActivationLevel(a[i]);
}
void
MusculoSkeletalSystem::
ApplyForcesToSkeletons(FEM::World* world)
{
Eigen::VectorXd X = world->GetPositions();
Eigen::VectorXd force_origin(X.rows()),force_insertion(X.rows());
Eigen::Vector2d fo,fi;
for(auto& muscle : mMuscles)
{
auto& origin_way_points = muscle->originWayPoints;
auto& insertion_way_points = muscle->insertionWayPoints;
int no = origin_way_points.size();
int ni = insertion_way_points.size();
force_origin.setZero();
force_insertion.setZero();
muscle->origin->EvalGradient(X,force_origin);
muscle->insertion->EvalGradient(X,force_insertion);
fo = force_origin.block<2,1>(muscle->origin->GetI0()*2,0);
fi = force_insertion.block<2,1>(muscle->insertion->GetI0()*2,0);
muscle->TransferForce(fo,fi);
Eigen::Vector3d f_origin_3D(fo[0],fo[1],0.0);
Eigen::Vector3d f_insertion_3D(fi[0],fi[1],0.0);
origin_way_points[no-1].first->addExtForce(f_origin_3D,origin_way_points[no-1].second);
insertion_way_points[ni -1].first->addExtForce(f_insertion_3D,insertion_way_points[ni-1].second);
muscle->force_origin =fo;
muscle->force_insertion =fi;
}
}
Eigen::MatrixXd
MusculoSkeletalSystem::
ComputeForceDerivative(FEM::World* world)
{
Eigen::VectorXd X = world->GetPositions();
Eigen::MatrixXd J(mMuscles.size()*4,mMuscles.size());
J.setZero();
for(int i=0;i<mMuscles.size();i++)
{
auto& muscle = mMuscles[i];
J.block(0,i,mMuscles.size()*4,1) = world->ComputeJacobian(muscle->muscleConstraints,mAttachementConstraintVector);
for(int j=0;j<mMuscles.size();j++){
Eigen::Vector2d fo,fi;
fo = J.block<2,1>(j*4+0,i);
fi = J.block<2,1>(j*4+2,i);
mMuscles[j]->TransferForce(fo,fi);
J.block<2,1>(j*4+0,i) = fo;
J.block<2,1>(j*4+2,i) = fi;
}
}
// for(int i =0;i<J.rows();i++)
// for(int j =0;j<J.cols();j++)
// if(fabs(J(i,j))<1E-4)
// J(i,j) =0.0;
return J;
}
Eigen::VectorXd
MusculoSkeletalSystem::
ComputeForce(FEM::World* world)
{
Eigen::VectorXd X = world->GetPositions();
Eigen::VectorXd b(mMuscles.size()*4);
Eigen::VectorXd force_origin(X.rows()),force_insertion(X.rows());
Eigen::Vector2d fo,fi;
for(int i=0;i<mMuscles.size();i++)
{
auto& muscle = mMuscles[i];
auto& origin_way_points = muscle->originWayPoints;
auto& insertion_way_points = muscle->insertionWayPoints;
force_origin.setZero();
force_insertion.setZero();
muscle->origin->EvalGradient(X,force_origin);
muscle->insertion->EvalGradient(X,force_insertion);
fo = force_origin.block<2,1>(muscle->origin->GetI0()*2,0);
fi = force_insertion.block<2,1>(muscle->insertion->GetI0()*2,0);
muscle->TransferForce(fo,fi);
b.block<2,1>(4*i+0,0) = fo;
b.block<2,1>(4*i+2,0) = fi;
}
// for(int i =0;i<b.rows();i++)
// if(fabs(b[i])<1E-4)
// b[i] = 0.0;
return b;
}
void
MakeSkeleton(MusculoSkeletalSystem* ms)
{
ms->GetSkeleton() = Skeleton::create("human");
auto& skel = ms->GetSkeleton();
MakeRootBody(skel,"Torso",Eigen::Vector3d(0.05,0.6,0.0),Eigen::Vector3d(0,-0.3,0),10);
MakeBody(skel,skel->getBodyNode("Torso"),"NeckR",
Eigen::Vector3d(0.3,0.05,0.0),
Eigen::Vector3d(0.0,0.3,0),
Eigen::Vector3d(-0.15,0.0,0),5);
MakeBody(skel,skel->getBodyNode("Torso"),"NeckL",
Eigen::Vector3d(0.3,0.05,0.0),
Eigen::Vector3d(0.0,0.3,0),
Eigen::Vector3d(0.15,0.0,0),5);
MakeBody(skel,skel->getBodyNode("NeckR"),"ShoulderR",
Eigen::Vector3d(0.3,0.05,0.0),
Eigen::Vector3d(0.15,0.0,0),
Eigen::Vector3d(-0.15,0.0,0),5);
MakeBody(skel,skel->getBodyNode("NeckL"),"ShoulderL",
Eigen::Vector3d(0.3,0.05,0.0),
Eigen::Vector3d(-0.15,0.0,0),
Eigen::Vector3d(0.15,0.0,0),5);
MakeBody(skel,skel->getBodyNode("ShoulderR"),"ElbowR",
Eigen::Vector3d(0.3,0.05,0.0),
Eigen::Vector3d(0.15,0.0,0),
Eigen::Vector3d(-0.15,0.0,0),5);
MakeBody(skel,skel->getBodyNode("ShoulderL"),"ElbowL",
Eigen::Vector3d(0.3,0.05,0.0),
Eigen::Vector3d(-0.15,0.0,0),
Eigen::Vector3d(0.15,0.0,0),5);
MakeWeldBody(skel,skel->getBodyNode("Torso"),"Head",
0.07,
Eigen::Vector3d(0,0.40,0),
Eigen::Vector3d(0,0,0),
10);
MakeWeldBody(skel,skel->getBodyNode("ElbowR"),"HandR",
0.02,
Eigen::Vector3d(0.17,0,0),
Eigen::Vector3d(0,0,0),
3);
MakeWeldBody(skel,skel->getBodyNode("ElbowL"),"HandL",
0.02,
Eigen::Vector3d(-0.17,0.0,0),
Eigen::Vector3d(0,0,0),
3);
auto pos = skel->getPositions();
pos[0] = 0.0;
pos[1] = 0.1;
pos[2] = -0.1;
pos[3] = -1.0;
pos[4] = 1.0;
pos[5] = -1.0;
pos[6] = 1.0;
skel->setPositions(pos);
skel->computeForwardKinematics(true,false,false);
// skel->getDof(0)->setPositionLimits(-0.0,0.0);
// skel->getDof(1)->setPositionLimits(0.0,0.0);
// skel->getDof(2)->setPositionLimits(-0.0,0.0);
// skel->getDof(3)->setPositionLimits(0.0,0.0);
// skel->getDof(4)->setPositionLimits(0.0,0.0);
skel->getDof(0)->setPositionLimits(-0.1,0.1);
skel->getDof(1)->setPositionLimits(-0.4,0.2);
skel->getDof(2)->setPositionLimits(-0.2,0.4);
// skel->getDof(3)->setPositionLimits(-1.57,0.0);
// skel->getDof(4)->setPositionLimits(0.0,1.57);
// skel->getDof(5)->setPositionLimits(-2.0,2.0);
// skel->getDof(6)->setPositionLimits(-2.0,2.0);
// skel->getDof(0)->setPositionLimits(0.0,0.0);
// skel->getDof(1)->setPositionLimits(-0.1,0.2);
// // skel->getDof(2)->setPositionLimits(-0.2,0.0);
// skel->getDof(2)->setPositionLimits(-1.0,-1.0);
// // skel->getDof(4)->setPositionLimits(0.0,1.57);
// skel->getDof(3)->setPositionLimits(-1.0,-1.0);
// // skel->getDof(6)->setPositionLimits(-2.0,2.0);
for(int i =0;i<skel->getNumDofs();i++)
skel->getDof(i)->getJoint()->setPositionLimitEnforced(true);
for(int i=0;i<skel->getNumBodyNodes();i++)
skel->getBodyNode(i)->setCollidable(false);
}
void
MakeMuscles(const std::string& path,MusculoSkeletalSystem* ms)
{
auto& skel = ms->GetSkeleton();
TiXmlDocument doc;
if(!doc.LoadFile(path))
{
std::cout<<"Cant open XML file : "<<path<<std::endl;
return;
}
TiXmlElement* muscles = doc.FirstChildElement("Muscles");
for(TiXmlElement* unit = muscles->FirstChildElement("unit");unit!=nullptr;unit = unit->NextSiblingElement("unit"))
{
TiXmlElement* ori = unit->FirstChildElement("origin");
std::vector<AnchorPoint> p_ori,p_ins;
for(TiXmlElement* anc = ori->FirstChildElement("anchor");anc!=nullptr;anc = anc->NextSiblingElement("anchor"))
{
std::string body_name = anc->Attribute("body");
double x = std::stod(anc->Attribute("x"));
double y = std::stod(anc->Attribute("y"));
p_ori.push_back(AnchorPoint(skel->getBodyNode(body_name.c_str()),Eigen::Vector3d(x,y,0.0)));
}
TiXmlElement* ins = unit->FirstChildElement("insertion");
for(TiXmlElement* anc = ins->FirstChildElement("anchor");anc!=nullptr;anc = anc->NextSiblingElement("anchor"))
{
std::string body_name = anc->Attribute("body");
double x = std::stod(anc->Attribute("x"));
double y = std::stod(anc->Attribute("y"));
p_ins.push_back(AnchorPoint(skel->getBodyNode(body_name.c_str()),Eigen::Vector3d(x,y,0.0)));
}
Eigen::Vector2d muscle_start,muscle_end;
muscle_start = GetPoint(p_ori[0]);
muscle_end = GetPoint(p_ins[0]);
// p_ori.erase(p_ori.begin());
// p_ins.erase(p_ins.begin());
double len = (muscle_start - muscle_end).norm();
Eigen::Vector2d unit_dir = (muscle_start - muscle_end).normalized();
double cosa = unit_dir[0];
double sina = unit_dir[1];
double angle = atan2(sina,cosa);
TiXmlElement* mesh_element = unit->FirstChildElement("mesh");
std::string mesh_type = mesh_element->Attribute("type");
Eigen::Affine2d T = Eigen::Affine2d::Identity();
Eigen::Rotation2D<double> R(angle);
T.translation() = 0.5*(muscle_start + muscle_end);
T.linear() = R*Eigen::Scaling(Eigen::Vector2d(len,len*std::stod(mesh_element->Attribute("ratio"))));
if(!mesh_type.compare("Rectangle"))
{
int nx = std::stoi(mesh_element->Attribute("nx"));
int ny = std::stoi(mesh_element->Attribute("ny"));
// double ratio = std::stod(mesh_element->Attribute("ratio"));
DiamondMesh* dm = new DiamondMesh(1.0,(double)ny/(double)nx,nx,ny,T);
int i_ori = dm->GetEndingPointIndex();
int i_ins = dm->GetStartingPointIndex();
// int i_ori = (ny+1)*(nx)+ny/2;
// int i_ins = ny/2;
ms->AddMuscle(p_ori,i_ori,p_ins,i_ins,unit_dir,dm);
}
else
{
int i_ori,i_ins;
i_ori = std::stoi(unit->FirstChildElement("mesh")->Attribute("origin_index"));
i_ins = std::stoi(unit->FirstChildElement("mesh")->Attribute("insertion_index"));
ms->AddMuscle(p_ori,i_ori,p_ins,i_ins,unit_dir,
new OBJLoader(unit->FirstChildElement("mesh")->Attribute("path"),T));
}
}
} | 30.618143 | 156 | 0.65934 | [
"mesh",
"vector"
] |
d956bcdd3948e10ba83ff5c03d483abdfd819975 | 18,425 | cpp | C++ | src/vcf2genoLoader.cpp | QBRC/seqminer | 959fdb8819aef614ed811afaa1c8c23b0c6f0d46 | [
"BSD-3-Clause"
] | null | null | null | src/vcf2genoLoader.cpp | QBRC/seqminer | 959fdb8819aef614ed811afaa1c8c23b0c6f0d46 | [
"BSD-3-Clause"
] | null | null | null | src/vcf2genoLoader.cpp | QBRC/seqminer | 959fdb8819aef614ed811afaa1c8c23b0c6f0d46 | [
"BSD-3-Clause"
] | null | null | null | #include "vcf2genoLoader.h"
#include <map>
#include <set>
#include <string>
#include <vector>
#include "R_CPP_interface.h"
#include "TabixReader.h"
#include "VCFUtil.h"
#include "tabix.h"
#include <R.h>
#include "GeneLoader.h"
/**
* Read from @param vin and return a matrix of marker by people
*/
SEXP readVCF2Matrix(VCFExtractor* vin) {
std::vector<double> genoVec;
std::vector<std::string> posVec;
std::vector<std::string> idVec;
std::string posString;
// print header
std::vector<std::string>& names = idVec;
vin->getVCFHeader()->getPeopleName(&names);
while (vin->readRecord()) {
// REprintf("read a record\n");
VCFRecord& r = vin->getVCFRecord();
VCFPeople& people = r.getPeople();
VCFIndividual* indv;
// store all results here
posString = r.getChrom();
posString += ':';
posString += r.getPosStr();
posVec.push_back(posString);
for (size_t i = 0; i < people.size(); i++) {
indv = people[i];
int g = indv->justGet(0).getGenotype();
// Rprintf( "\t%d", g);
genoVec.push_back(g);
}
// Rprintf( "\n");
}; // end while
// REprintf("posVec = %zu, idVec = %zu, genoVec = %zu\n", posVec.size(),
// idVec.size(), genoVec.size());
// pass value back to R (see Manual Chapter 5)
int nx = (int)posVec.size();
int ny = (int)idVec.size();
SEXP ans = R_NilValue;
PROTECT(ans = allocMatrix(REALSXP, nx, ny));
double* rans = REAL(ans);
int idx = 0;
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
// Rprintf("idx = %d, i = %d, j=%d, geno = %g\n", idx, i, j,
// genoVec[idx]);
rans[i + nx * j] = genoVec[idx];
++idx;
}
}
// set row and col names
SEXP dim;
PROTECT(dim = allocVector(INTSXP, 2));
INTEGER(dim)[0] = nx;
INTEGER(dim)[1] = ny;
setAttrib(ans, R_DimSymbol, dim);
SEXP rowName;
PROTECT(rowName = allocVector(STRSXP, nx));
for (int i = 0; i < nx; i++)
SET_STRING_ELT(rowName, i, mkChar(posVec[i].c_str()));
SEXP colName;
PROTECT(colName = allocVector(STRSXP, ny));
for (int i = 0; i < ny; i++)
SET_STRING_ELT(colName, i, mkChar(idVec[i].c_str()));
SEXP dimnames;
PROTECT(dimnames = allocVector(VECSXP, 2));
SET_VECTOR_ELT(dimnames, 0, rowName);
SET_VECTOR_ELT(dimnames, 1, colName);
setAttrib(ans, R_DimNamesSymbol, dimnames);
// finish up
UNPROTECT(5);
return (ans);
} // end readVCF2Matrix
/**
* @param file name
* @return check whether VCF files has ANNO tag
*/
bool vcfHasAnnotation(const std::string& fn) {
// Rprintf( "range = %s\n", range.c_str());
VCFInputFile vin(fn);
while (vin.readRecord()) {
VCFRecord& r = vin.getVCFRecord();
VCFInfo& info = r.getVCFInfo();
bool tagMissing;
info.getTag("ANNO", &tagMissing);
if (tagMissing) {
return false;
}
return true;
}
return false;
}
/**
* @param arg_fileName: a string character
* @param arg_geneFile: which gene file to use
* @param arg_geneName: which gene we are interested. (just allow One gene
* name).
* @param arg_annoType: allow annotation type, can be regular expression. (e.g.
* Synonymous|Nonsynonymous)
*/
SEXP impl_readVCFToMatrixByRange(SEXP arg_fileName, SEXP arg_range,
SEXP arg_annoType) {
SEXP ans = R_NilValue;
std::string FLAG_fileName = CHAR(STRING_ELT(arg_fileName, 0));
std::vector<std::string> FLAG_range;
extractStringArray(arg_range, &FLAG_range);
std::string FLAG_annoType = CHAR(STRING_ELT(arg_annoType, 0));
if (FLAG_fileName.size() == 0) {
error("Please provide VCF file name");
return ans;
}
if (FLAG_range.empty()) {
error("Please provide a given range, e.g. '1:100-200'");
return ans;
}
if (!FLAG_annoType.empty() && !vcfHasAnnotation(FLAG_fileName)) {
REprintf(
"Please use annotated VCF as input (cannot find ANNO in the INFO "
"field);\n");
REprintf("Prefer using ANNO from https://github.com/zhanxw/anno \n");
return ans;
}
int nGene = FLAG_range.size();
Rprintf("%d region to be extracted.\n", nGene);
int numAllocated = 0;
// allocate return value
PROTECT(ans = allocVector(VECSXP, nGene));
numAllocated++;
setListNames(FLAG_range, &ans);
for (int i = 0; i < nGene; ++i) {
// REprintf("range = %s\n", FLAG_range[i].c_str());
VCFExtractor vin(FLAG_fileName.c_str());
vin.setRangeList(FLAG_range[i].c_str());
if (FLAG_annoType.size()) {
vin.setAnnoType(FLAG_annoType.c_str());
}
// real working part
SET_VECTOR_ELT(ans, i, readVCF2Matrix(&vin));
}
UNPROTECT(numAllocated);
return ans;
} // end impl_readVCFToMatrixByRange
/**
* @param arg_fileName: a string character
* @param arg_geneFile: which gene file to use
* @param arg_geneName: which gene we are interested. (just allow One gene
* name).
* @param arg_annoType: allow annotation type, can be regular expression. (e.g.
* Synonymous|Nonsynonymous)
*/
SEXP impl_readVCFToMatrixByGene(SEXP arg_fileName, SEXP arg_geneFile,
SEXP arg_geneName, SEXP arg_annoType) {
SEXP ans = R_NilValue;
std::string FLAG_fileName = CHAR(STRING_ELT(arg_fileName, 0));
std::string FLAG_geneFile = CHAR(STRING_ELT(arg_geneFile, 0));
std::vector<std::string> FLAG_geneName;
extractStringArray(arg_geneName, &FLAG_geneName);
std::string FLAG_annoType = CHAR(STRING_ELT(arg_annoType, 0));
if (FLAG_fileName.size() == 0) {
error("Please provide VCF file name");
}
if (FLAG_geneName.size() && FLAG_geneFile.size() == 0) {
error("Please provide gene file name when extract genotype by gene");
}
if (!FLAG_annoType.empty() && !vcfHasAnnotation(FLAG_fileName)) {
REprintf(
"Please use annotated VCF as input (cannot find ANNO in the INFO "
"field);\n");
REprintf("Prefer using ANNO from https://github.com/zhanxw/anno \n");
return ans;
}
int nGene = FLAG_geneName.size();
Rprintf("%d region to be extracted.\n", nGene);
int numAllocated = 0;
// allocate return value
PROTECT(ans = allocVector(VECSXP, nGene));
numAllocated++;
setListNames(FLAG_geneName, &ans);
OrderedMap<std::string, std::string> geneRange;
loadGeneFile(FLAG_geneFile, FLAG_geneName, &geneRange);
for (int i = 0; i < nGene; ++i) {
// REprintf("range = %s\n", FLAG_geneName[i].c_str());
const std::string& range = geneRange[FLAG_geneName[i]];
// Rprintf( "range = %s\n", range.c_str());
VCFExtractor vin(FLAG_fileName.c_str());
if (range.size())
vin.setRangeList(range.c_str());
else {
warning("Gene name [ %s ] does not exists in provided gene file",
FLAG_geneName[i].c_str());
UNPROTECT(numAllocated);
return (ans);
};
if (FLAG_annoType.size()) {
vin.setAnnoType(FLAG_annoType.c_str());
}
// real working part
SET_VECTOR_ELT(ans, i, readVCF2Matrix(&vin));
}
UNPROTECT(numAllocated);
return ans;
}
SEXP readVCF2List(VCFInputFile* vin,
const std::set<std::string>& FLAG_vcfColumn,
const std::vector<std::string>& FLAG_infoTag,
const std::vector<std::string>& FLAG_indvTag) {
// Rprintf("vcfColumn.size() = %u\n", FLAG_vcfColumn.size());
// Rprintf("vcfInfo.size() = %u\n", FLAG_infoTag.size());
// Rprintf("vcfIndv.size() = %u\n", FLAG_indvTag.size());
// also append sample names at the end
int retListLen =
FLAG_vcfColumn.size() + FLAG_infoTag.size() + FLAG_indvTag.size() + 1;
if (retListLen == 0) {
return R_NilValue;
}
int numAllocated =
0; // record how many times we allocate (using PROTECT in R);
SEXP ret;
PROTECT(ret = allocVector(VECSXP, retListLen));
numAllocated++;
// store results
std::vector<std::string> idVec;
std::vector<std::string> chrom;
std::vector<int> pos;
std::vector<std::string> rsId;
std::vector<std::string> ref;
std::vector<std::string> alt;
std::vector<std::string> qual;
std::vector<std::string> filt;
std::vector<std::string> info;
std::vector<std::string> format;
std::map<std::string, std::vector<std::string> > infoMap;
// std::vector<int> gtVec;
// std::vector<int> gdVec;
// std::vector<int> gqVec;
std::map<std::string, std::vector<std::string> > indvMap;
int nRow = 0; // # of positions that will be outputed
// print header
std::vector<std::string>& names = idVec;
vin->getVCFHeader()->getPeopleName(&names);
bool FLAG_variantOnly = false;
// real working part
int nonVariantSite = 0;
while (vin->readRecord()) {
// REprintf("read a record\n");
VCFRecord& r = vin->getVCFRecord();
VCFPeople& people = r.getPeople();
VCFIndividual* indv;
if (FLAG_variantOnly) {
// REprintf("filter by var\n");
bool hasVariant = false;
int geno;
int GTidx = r.getFormatIndex("GT");
for (size_t i = 0; i < people.size(); i++) {
indv = people[i];
geno = indv->justGet(GTidx).getGenotype();
if (geno != 0 && geno != MISSING_GENOTYPE) hasVariant = true;
}
if (!hasVariant) {
nonVariantSite++;
continue;
}
}
// store results here
nRow++;
if (FLAG_vcfColumn.count("CHROM")) {
chrom.push_back(r.getChrom());
}
if (FLAG_vcfColumn.count("POS")) {
pos.push_back(r.getPos());
}
if (FLAG_vcfColumn.count("ID")) {
rsId.push_back(r.getID());
}
if (FLAG_vcfColumn.count("REF")) {
ref.push_back(r.getRef());
}
if (FLAG_vcfColumn.count("ALT")) {
alt.push_back(r.getAlt());
}
if (FLAG_vcfColumn.count("QUAL")) {
qual.push_back(r.getQual());
}
if (FLAG_vcfColumn.count("FILTER")) {
filt.push_back(r.getFilt());
}
if (FLAG_vcfColumn.count("INFO")) {
info.push_back(r.getInfo());
}
if (FLAG_vcfColumn.count("FORMAT")) {
format.push_back(r.getFormat());
}
// store INFO field
for (std::vector<std::string>::const_iterator it = FLAG_infoTag.begin();
it != FLAG_infoTag.end(); ++it) {
bool missing;
VCFValue v = r.getInfoTag(it->c_str(), &missing);
if (missing) {
infoMap[*it].push_back("");
} else {
infoMap[*it].push_back(v.toStr());
// Rprintf("add info field [ %s ] = %s\n", it->c_str(), v.toStr());
}
};
// Rprintf("Done add info\n");
// store indv values
for (size_t i = 0; i < people.size(); i++) {
indv = people[i];
for (std::vector<std::string>::const_iterator it = FLAG_indvTag.begin();
it != FLAG_indvTag.end(); ++it) {
int idx = r.getFormatIndex(it->c_str());
if (idx < 0) {
indvMap[*it].push_back("");
} else {
bool missing;
VCFValue v = indv->get(idx, &missing);
if (missing) {
indvMap[*it].push_back("");
} else {
indvMap[*it].push_back(v.toStr());
// Rprintf("add indv field [ %s ] = %s\n", it->c_str(), v.toStr());
}
}
};
}
// Rprintf("Done add indv\n");
}; // end while
// Rprintf("indvMap.size() = %zu\n", indvMap.size());
// REprintf("posVec = %zu, idVec = %zu, genoVec = %zu\n", posVec.size(),
// idVec.size(), genoVec.size());
// pass value back to R (see Manual Chapter 5)
std::vector<std::string> listNames;
int retListIdx = 0;
if (FLAG_vcfColumn.count("CHROM")) {
storeResult(chrom, ret, retListIdx++);
listNames.push_back("CHROM");
}
if (FLAG_vcfColumn.count("POS")) {
storeResult(pos, ret, retListIdx++);
listNames.push_back("POS");
}
if (FLAG_vcfColumn.count("ID")) {
storeResult(rsId, ret, retListIdx++);
listNames.push_back("ID");
}
if (FLAG_vcfColumn.count("REF")) {
storeResult(ref, ret, retListIdx++);
listNames.push_back("REF");
}
if (FLAG_vcfColumn.count("ALT")) {
storeResult(alt, ret, retListIdx++);
listNames.push_back("ALT");
}
if (FLAG_vcfColumn.count("QUAL")) {
storeResult(qual, ret, retListIdx++);
listNames.push_back("QUAL");
}
if (FLAG_vcfColumn.count("FILTER")) {
storeResult(filt, ret, retListIdx++);
listNames.push_back("FILTER");
}
if (FLAG_vcfColumn.count("INFO")) {
storeResult(info, ret, retListIdx++);
listNames.push_back("INFO");
}
if (FLAG_vcfColumn.count("FORMAT")) {
storeResult(format, ret, retListIdx++);
listNames.push_back("FORMAT");
}
// pass info values to R
for (std::map<std::string, std::vector<std::string> >::iterator it =
infoMap.begin();
it != infoMap.end(); ++it) {
storeResult(it->first, it->second, ret, retListIdx++);
listNames.push_back(it->first);
}
// pass indv tags to R
// Rprintf("pass idnv tags\n");
for (std::map<std::string, std::vector<std::string> >::iterator it =
indvMap.begin();
it != indvMap.end(); ++it) {
// dump(it->second);
storeResult(it->first, it->second, ret, retListIdx);
// Rprintf("results done\n");
// NOTE: R internally store values into matrix by column first!
// thus the matrix is people by marker
setDim(idVec.size(), nRow, ret, retListIdx);
retListIdx++;
listNames.push_back(it->first);
}
// Rprintf("pass idnv tags done.\n");
// store sample ids
// Rprintf("set sample id");
listNames.push_back("sampleId");
storeResult(idVec, ret, retListIdx++);
// Rprintf("set list names\n");
SEXP sListNames;
PROTECT(sListNames = allocVector(STRSXP, listNames.size()));
numAllocated++;
for (unsigned int i = 0; i != listNames.size(); ++i) {
SET_STRING_ELT(sListNames, i, mkChar(listNames[i].c_str()));
}
setAttrib(ret, R_NamesSymbol, sListNames);
// finish up
UNPROTECT(numAllocated);
// Rprintf("Unprotected: %d\n", (retListLen + 1));
return (ret);
}
/**
* @param arg_fileName: a string character
* @param arg_range: which range to extract. NOTE: only use first element
* @param arg_annoType: allow annotation type, can be regular expression. (e.g.
* Synonymous|Nonsynonymous)
* @param arg_columns: a list of which columns to extract (e.g. CHROM, POS ...)
* @param arg_infoTag: a list of which tag under INFO tag will be extracted
* (e.g. ANNO, ANNO_FULL, AC ...)
* @param arg_indvTag: a list of which tag given in individual's column (e.g.
* GT, GD, GQ ...)
*/
SEXP impl_readVCFToListByRange(SEXP arg_fileName, SEXP arg_range,
SEXP arg_annoType, SEXP arg_columns,
SEXP arg_infoTag, SEXP arg_indvTag) {
// begin
std::string FLAG_fileName = CHAR(STRING_ELT(arg_fileName, 0));
std::string FLAG_range = CHAR(STRING_ELT(arg_range, 0));
std::string FLAG_annoType = CHAR(STRING_ELT(arg_annoType, 0));
std::set<std::string> FLAG_vcfColumn;
std::vector<std::string> FLAG_infoTag, FLAG_indvTag;
extractStringSet(arg_columns, &FLAG_vcfColumn);
extractStringArray(arg_infoTag, &FLAG_infoTag);
extractStringArray(arg_indvTag, &FLAG_indvTag);
// Rprintf( "range = %s\n", range.c_str());
VCFExtractor vin(FLAG_fileName.c_str());
if (FLAG_range.size())
vin.setRangeList(FLAG_range.c_str());
else {
error("Please provide a range before we can continue.\n");
};
if (!FLAG_annoType.empty() && !vcfHasAnnotation(FLAG_fileName)) {
REprintf(
"Please use annotated VCF as input (cannot find ANNO in the INFO "
"field);\n");
REprintf("Prefer using ANNO from https://github.com/zhanxw/anno \n");
SEXP ans = R_NilValue;
return ans;
}
if (FLAG_annoType.size()) {
vin.setAnnoType(FLAG_annoType.c_str());
}
return readVCF2List(&vin, FLAG_vcfColumn, FLAG_infoTag, FLAG_indvTag);
} // impl_readVCFToListByRange
/**
* @param arg_fileName: a string character
* @param arg_geneFile: which gene file to use
* @param arg_geneName: which gene we are interested. (NOTE: only first one gene
* is used).
* @param arg_annoType: allow annotation type, can be regular expression. (e.g.
* Synonymous|Nonsynonymous)
* @param arg_columns: a list of which columns to extract (e.g. CHROM, POS ...)
* @param arg_infoTag: a list of which tag under INFO tag will be extracted
* (e.g. ANNO, ANNO_FULL, AC ...)
* @param arg_indvTag: a list of which tag given in individual's column (e.g.
* GT, GD, GQ ...)
*/
SEXP impl_readVCFToListByGene(SEXP arg_fileName, SEXP arg_geneFile,
SEXP arg_geneName, SEXP arg_annoType,
SEXP arg_columns, SEXP arg_infoTag,
SEXP arg_indvTag) {
// begin
std::string FLAG_fileName = CHAR(STRING_ELT(arg_fileName, 0));
std::string FLAG_geneFile = CHAR(STRING_ELT(arg_geneFile, 0));
std::string FLAG_geneName = CHAR(STRING_ELT(arg_geneName, 0));
std::string FLAG_annoType = CHAR(STRING_ELT(arg_annoType, 0));
std::set<std::string> FLAG_vcfColumn;
std::vector<std::string> FLAG_infoTag, FLAG_indvTag;
extractStringSet(arg_columns, &FLAG_vcfColumn);
extractStringArray(arg_infoTag, &FLAG_infoTag);
extractStringArray(arg_indvTag, &FLAG_indvTag);
if (!FLAG_annoType.empty() && !vcfHasAnnotation(FLAG_fileName)) {
REprintf(
"Please use annotated VCF as input (cannot find ANNO in the INFO "
"field);\n");
REprintf("Prefer using ANNO from https://github.com/zhanxw/anno \n");
SEXP ans = R_NilValue;
return ans;
}
// Rprintf("vcfColumn.size() = %u\n", FLAG_vcfColumn.size());
// Rprintf("vcfInfo.size() = %u\n", FLAG_infoTag.size());
// Rprintf("vcfIndv.size() = %u\n", FLAG_indvTag.size());
// also append sample names at the end
int retListLen =
FLAG_vcfColumn.size() + FLAG_infoTag.size() + FLAG_indvTag.size() + 1;
if (retListLen == 0) {
return R_NilValue;
}
OrderedMap<std::string, std::string> geneRange;
loadGeneFile(FLAG_geneFile, FLAG_geneName, &geneRange);
std::string range;
int n = geneRange.size();
for (int i = 0; i < n; ++i) {
if (range.size() > 0) {
range += ",";
}
range += geneRange.valueAt(i);
}
REprintf("range = %s\n", range.c_str());
VCFExtractor vin(FLAG_fileName.c_str());
if (range.size())
vin.setRangeList(range.c_str());
else {
error("Please provide a valid gene name before we can continue.\n");
};
if (FLAG_annoType.size()) {
vin.setAnnoType(FLAG_annoType.c_str());
}
return readVCF2List(&vin, FLAG_vcfColumn, FLAG_infoTag, FLAG_indvTag);
} // end readVCF2List
| 31.175973 | 80 | 0.630719 | [
"vector"
] |
d95843177f5654fb8f757e301d0c2a7d90b0afdc | 1,522 | cpp | C++ | src/render/GLGpuShaderProgramUniform.cpp | ErnestasJa/TheEngine2 | a16778e18b844c2044cf3bab31f661c1fb3da840 | [
"MIT"
] | 2 | 2015-12-16T22:02:53.000Z | 2018-04-10T14:43:26.000Z | src/render/GLGpuShaderProgramUniform.cpp | ErnestasJa/TheEngine2 | a16778e18b844c2044cf3bab31f661c1fb3da840 | [
"MIT"
] | 48 | 2015-12-20T14:23:49.000Z | 2016-07-18T12:15:37.000Z | src/render/GLGpuShaderProgramUniform.cpp | ErnestasJa/TheEngine2 | a16778e18b844c2044cf3bab31f661c1fb3da840 | [
"MIT"
] | 1 | 2015-12-20T14:30:26.000Z | 2015-12-20T14:30:26.000Z | #include "GLGpuShaderProgramUniform.h"
#include "OpenGL.hpp"
namespace render {
GLGpuShaderProgramUniform::GLGpuShaderProgramUniform(const gl::gpu_shader_uniform_handle& handle)
: m_handle(handle)
{
}
GLGpuShaderProgramUniform::~GLGpuShaderProgramUniform()
{
}
const core::String& GLGpuShaderProgramUniform::GetName()
{
return m_handle.name;
}
const void GLGpuShaderProgramUniform::Set(int value)
{
gl::SetUniform(m_handle, value);
}
const void GLGpuShaderProgramUniform::Set(float value)
{
gl::SetUniform(m_handle, value);
}
const void GLGpuShaderProgramUniform::Set(const int size, float* vec)
{
gl::SetUniform(m_handle, size, vec);
}
const void GLGpuShaderProgramUniform::Set(const core::pod::Vec2<float>& value)
{
gl::SetUniform(m_handle, value);
}
const void GLGpuShaderProgramUniform::Set(const core::pod::Vec3<float>& value)
{
gl::SetUniform(m_handle, value);
}
const void GLGpuShaderProgramUniform::Set(const core::pod::Vec4<float>& value)
{
gl::SetUniform(m_handle, value);
}
const void GLGpuShaderProgramUniform::SetMat4(float* value)
{
gl::SetUniformMat4(m_handle, value);
}
const void GLGpuShaderProgramUniform::SetMat3(float* value)
{
gl::SetUniformMat3(m_handle, value);
}
const void GLGpuShaderProgramUniform::SetMat3x4(float* value, int count)
{
gl::SetUniformMat3x4(m_handle, value, count);
}
const void GLGpuShaderProgramUniform::SetMat4(const float* value, int count, bool transpose)
{
gl::SetUniformMat4(m_handle, value, count, transpose);
}
} // namespace render
| 22.382353 | 97 | 0.764126 | [
"render"
] |
d95c024144056e506b50bd3e03bbd97ad2f0b51a | 32,784 | cpp | C++ | code/Torsion/ProjectCtrl.cpp | Bloodknight/NeuTorsion | a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea | [
"MIT"
] | 38 | 2016-02-20T02:46:28.000Z | 2021-11-17T11:39:57.000Z | code/Torsion/ProjectCtrl.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 17 | 2016-02-20T02:19:55.000Z | 2021-02-08T15:15:17.000Z | code/Torsion/ProjectCtrl.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 46 | 2016-02-20T02:47:33.000Z | 2021-01-31T15:46:05.000Z | // Torsion TorqueScript IDE - Copyright (C) Sickhead Games, LLC
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
#include "PreCompiled.h"
#include "ProjectCtrl.h"
#include "ProjectDoc.h"
#include "MainFrame.h"
#include "TorsionApp.h"
#include "FileTypeImageList.h"
#include "Platform.h"
#include "tsMenu.h"
#include "ScriptView.h"
#include "Icons.h"
#include <wx/dir.h>
#include <wx/image.h>
#include <wx/mimetype.h>
#include <wx/timer.h>
#include <wx/file.h>
#include <wx/dcbuffer.h>
#include <map>
#include "icons\dragcursor.xpm"
wxBitmap ts_drag_bitmap( dragcursor_xpm );
#ifdef __WXMSW__
#include <commctrl.h>
#include "ShellMenu.h"
#endif
#include <wx/arrimpl.cpp>
WX_DEFINE_OBJARRAY(TreeItemIdArray);
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_CLASS( ProjectCtrl, wxTreeCtrl )
BEGIN_EVENT_TABLE( ProjectCtrl, wxTreeCtrl )
EVT_TREE_ITEM_ACTIVATED( wxID_ANY, OnOpenItem )
EVT_TREE_ITEM_MENU( wxID_ANY, OnItemMenu )
EVT_TREE_ITEM_EXPANDING( wxID_ANY, OnItemExpanding )
EVT_TREE_ITEM_EXPANDED( wxID_ANY, OnItemExpanded )
EVT_TREE_ITEM_COLLAPSING( wxID_ANY, OnItemCollapsing )
EVT_TREE_ITEM_COLLAPSED( wxID_ANY, OnItemCollapsed )
EVT_TREE_ITEM_GETTOOLTIP( wxID_ANY, OnToolTip )
EVT_TREE_BEGIN_LABEL_EDIT( wxID_ANY, OnBeginRename )
EVT_TREE_END_LABEL_EDIT( wxID_ANY, OnEndRename )
// We only use EVT_TREE_BEGIN_DRAG to trigger our
// custom drag code. Our EVT_MOTION, EVT_TIMER,
// and EVT_LEFT_UP handlers do the rest of the work.
EVT_TREE_BEGIN_DRAG( wxID_ANY, OnDragBegin )
EVT_MOTION( OnDragMove )
EVT_TIMER( 0, OnDragExpandTimer )
EVT_KEY_UP( OnDragKey )
EVT_LEFT_UP( OnDragEnd )
EVT_SET_FOCUS( OnSetFocus )
EVT_KILL_FOCUS( OnKillFocus )
// To fix flicker!
#ifdef __WXMSW__
EVT_ERASE_BACKGROUND( ProjectCtrl::OnEraseBackground )
EVT_PAINT( ProjectCtrl::OnPaint )
#endif // __WXMSW__
END_EVENT_TABLE()
ProjectCtrl::ProjectCtrl( wxWindow* parent )
: wxTreeCtrl( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxSTATIC_BORDER | wxTR_EDIT_LABELS | wxTR_MULTIPLE ),
m_ProjectDoc( NULL ),
m_IsDragging( false ),
m_ImageList( NULL ),
m_ShowAllMods( false ),
m_ShowAllFiles( true ),
m_DonePaint( false ),
m_FocusView( NULL )
{
m_DragExpandTimer.SetOwner( this, 0 );
#ifdef __WXMSW__
m_OsMenu = NULL;
// We need to have an extra pixel space between items
// because icons are 16x16.
DWORD style = ::GetWindowLong( GetHwnd(), GWL_STYLE );
style |= TVS_NONEVENHEIGHT;
::SetWindowLong( GetHwnd(), GWL_STYLE, style );
::SendMessage( GetHwnd(), TVM_SETITEMHEIGHT, 17, 0 );
#endif // __WXMSW__
// Create the drag cursor.
{
wxImage image = ts_drag_bitmap.ConvertToImage();
image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, 0);
image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, 0);
m_DragCursor = wxCursor( image );
}
// Create the image list and add any fixed icons well need.
m_ImageList = new FileTypeImageList();
m_ImageList->Add( ts_new_project16 );
m_ImageList->Add( ts_folder_closed16 );
m_ImageList->Add( ts_folder_open16 );
SetImageList( m_ImageList );
}
ProjectCtrl::~ProjectCtrl()
{
wxDELETE( m_ImageList );
}
#ifdef __WXMSW__
void ProjectCtrl::OnEraseBackground( wxEraseEvent& event )
{
// Let the native control draw the background up
// until we get our first real paint.
if ( !m_DonePaint )
event.Skip();
}
void ProjectCtrl::OnPaint( wxPaintEvent& event )
{
// Don't erase the background anymore.
m_DonePaint = true;
// To clear up flicker we draw the background here
// ourselves in only the invalid area.
wxBufferedPaintDC dc( this );
wxDCClipper clipper( dc, GetUpdateRegion().GetBox() );
dc.SetBackground( GetBackgroundColour() );
dc.Clear();
// Unhook ourselves from message handling for a sec
// and let the native control render to our buffered dc.
SetEvtHandlerEnabled( false );
::SendMessage( GetHwnd(), WM_PAINT, (WPARAM)GetHdcOf( dc ), 0 );
SetEvtHandlerEnabled( true );
}
#endif // __WXMSW__
size_t ProjectCtrl::GetSelectedCount()
{
wxArrayTreeItemIds selection;
return GetSelections( selection );
}
wxString ProjectCtrl::GetSelectedPath() const
{
wxArrayTreeItemIds selection;
if ( GetSelections( selection ) == 0 )
return wxEmptyString;
return GetItemPath( selection[0] );
}
void ProjectCtrl::OnSetFocus( wxFocusEvent& event )
{
// If we have a focus view... then redirect the
// focus to it instead!
if ( m_FocusView )
{
m_FocusView->SetCtrlFocused();
m_FocusView = NULL;
return;
}
if ( m_ProjectDoc )
{
wxASSERT( m_ProjectDoc->GetFirstView() );
m_ProjectDoc->GetFirstView()->Activate( true );
}
// If we don't skip it the TreeCtrl base
// will never get to handle it.
event.Skip();
}
void ProjectCtrl::OnKillFocus( wxFocusEvent& event )
{
if ( m_ProjectDoc )
{
wxASSERT( m_ProjectDoc->GetFirstView() );
m_ProjectDoc->GetFirstView()->Activate( false );
}
// If we don't skip it the TreeCtrl base
// will never get to handle it.
event.Skip();
}
int ProjectCtrl::GetFileIcon( const wxString& file )
{
wxASSERT( m_ImageList );
return m_ImageList->AddFileIcon( file );
}
class ProjectCtrlItemData : public wxTreeItemData
{
public:
ProjectCtrlItemData( const wxString& FullPath )
: wxTreeItemData(),
m_FullPath( FullPath )
{
}
const wxString& GetPath() const { return m_FullPath; }
protected:
wxString m_FullPath;
};
class ProjectDirTraverser : public wxDirTraverser
{
public:
ProjectDirTraverser( ProjectCtrl* treeCtrl, wxTreeItemId parent, TreeItemIdArray& children, bool showAllMods, bool showAllFiles )
: m_TreeCtrl( treeCtrl ),
m_Parent( parent ),
m_Children( children ),
m_ShowAllMods( showAllMods ),
m_ShowAllFiles( showAllFiles )
{
wxASSERT( m_TreeCtrl );
m_Project = m_TreeCtrl->GetProjectDoc();
wxASSERT( m_Project );
}
virtual wxDirTraverseResult OnFile( const wxString& filename )
{
wxFileName file( filename );
// The app preferences defines what files to
// allow in the tree view.
if ( tsGetPrefs().IsExcludedFile( filename ) )
return wxDIR_CONTINUE;
// If this is a DSO skip it if the script exists.
if ( tsGetPrefs().IsDSOExt( file.GetExt() ) )
{
wxString script = filename.BeforeLast( '.' );
if ( wxFileName::FileExists( script ) )
return wxDIR_CONTINUE;
}
// Check if we're filtering non-script files.
if ( !m_ShowAllFiles && !tsGetPrefs().IsScriptFile( filename ) )
return wxDIR_CONTINUE;
// If we already have it in the child list then
// remove it and don't add a new one.
for ( int i=0; i < m_Children.GetCount(); i++ )
{
wxASSERT( m_Children[i].IsOk() );
wxFileName name( m_TreeCtrl->GetItemText( m_Children[i] ) );
if ( name == file.GetFullName() )
{
// Colorize it depending on the filters.
ColorizeItem( m_Children[i], file.GetPath() );
m_Children.RemoveAt( i );
return wxDIR_CONTINUE;
}
}
int icon = m_TreeCtrl->GetFileIcon( filename );
// Add this new file to the tree.
wxTreeItemId Id = m_TreeCtrl->AppendItem( m_Parent, file.GetFullName(),
icon, icon, new ProjectCtrlItemData( file.GetFullPath() ) );
// Colorize it depending on the filters.
ColorizeItem( Id, file.GetPath() );
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir( const wxString& dirname )
{
wxASSERT( m_TreeCtrl );
wxASSERT( m_Project );
if ( !m_ShowAllMods && !m_Project->IsMod( dirname ) )
return wxDIR_IGNORE;
wxFileName dir;
dir.AssignDir( dirname );
// If we already have it in the child list then
// let it be and don't add a new one.
for ( int i=0; i < m_Children.GetCount(); i++ )
{
wxASSERT( m_Children[i].IsOk() );
wxFileName name( m_TreeCtrl->GetItemText( m_Children[i] ) );
if ( name.SameAs( dir.GetDirs().Last() ) )
{
//if ( !m_TreeCtrl->IsExpanded( m_Children[i] ) )
m_TreeCtrl->SetItemHasChildren( m_Children[i], true );
// If a folder has no children.
//if ( !m_TreeCtrl->ItemHasChildren( m_Children[i] ) && )
//m_TreeCtrl->SetItemHasChildren( m_Children[i], true );
// Colorize it depending on the filters.
ColorizeItem( m_Children[i], dir.GetFullPath() );
m_Children.RemoveAt( i );
// Should we recurse it?
//if ( m_TreeCtrl->IsExpanded( m_Children[i] ) )
//return wxDIR_CONTINUE
return wxDIR_IGNORE;
}
}
if ( tsGetPrefs().IsExcludedFolder( dir.GetDirs().Last() ) )
return wxDIR_IGNORE;
// Add the folder to the tree.
wxTreeItemId item = m_TreeCtrl->AppendItem( m_Parent, dir.GetDirs().Last(),
1, 1, new ProjectCtrlItemData( dir.GetFullPath() ) );
m_TreeCtrl->SetItemImage( item, 2, wxTreeItemIcon_Expanded );
// Add a dummy child to allow for expansion later.
m_TreeCtrl->SetItemHasChildren( item, true );
// Colorize it depending on the filters.
ColorizeItem( item, dir.GetPath() );
return wxDIR_IGNORE;
}
private:
void ColorizeItem( const wxTreeItemId& item, const wxString& folder )
{
wxColour color( 0, 0, 0 );
wxASSERT( m_Project );
if ( m_ShowAllMods && !m_Project->IsMod( folder ) )
color.Set( 255, 0, 0 );
m_TreeCtrl->SetItemTextColour( item, color );
}
ProjectCtrl* m_TreeCtrl;
ProjectDoc* m_Project;
bool m_ShowAllMods;
bool m_ShowAllFiles;
wxTreeItemId m_Parent;
TreeItemIdArray& m_Children;
};
void ProjectCtrl::Refresh( ProjectDoc* project, bool showAllMods, bool showAllFiles, bool clearFirst )
{
m_ProjectDoc = project;
m_ShowAllMods = showAllMods;
m_ShowAllFiles = showAllFiles;
wxASSERT( m_ProjectDoc );
// If we have a root be sure it's ok and has
// not been changed on us.
wxFileName rootdir;
rootdir.AssignDir( m_ProjectDoc->GetWorkingDir() );
wxTreeItemId root = GetRootItem();
if ( root.IsOk() )
{
if ( clearFirst || !rootdir.SameAs( GetItemPath( root ) ) )
{
Delete( root );
root.Unset();
}
}
// Do we need to create a new root?
if ( !root.IsOk() )
{
root = AddRoot( m_ProjectDoc->GetName(), 0, 0, new ProjectCtrlItemData( rootdir.GetFullPath() ) );
const wxArrayString& excluded = tsGetPrefs().GetExcludedFolders();
m_DirWatcher.SetWatch( rootdir.GetFullPath(), DIRCHANGE_FILE_NAME | DIRCHANGE_DIR_NAME, excluded );
// Add a dummy child to allow for expansion.
SetItemHasChildren( root, true );
//AppendItem( root, "", -1, -1 );
// Do an initial expand of the root which
// will automaticly update children as needed.
Expand( root );
return;
}
RefreshFolder( root );
FixupFolders( root );
}
void ProjectCtrl::OnItemCollapsing( wxTreeEvent& Event )
{
wxTreeItemId item = Event.GetItem();
// Never let the root collapse.
if ( item == GetRootItem() )
{
Event.Veto();
return;
}
}
void ProjectCtrl::OnItemCollapsed( wxTreeEvent& event )
{
wxTreeItemId item = event.GetItem();
DeleteChildren( item );
SetItemHasChildren( item, true );
}
void ProjectCtrl::OnItemExpanding( wxTreeEvent& Event )
{
wxTreeItemId item = Event.GetItem();
RefreshFolder( item );
}
void ProjectCtrl::OnItemExpanded( wxTreeEvent& Event )
{
wxTreeItemId item = Event.GetItem();
FixupFolders( item );
}
bool ProjectCtrl::RefreshFolder( wxTreeItemId item )
{
wxString itemPath = GetItemPath( item );
wxASSERT( !itemPath.IsEmpty() );
if ( !wxFileName::DirExists( itemPath ) )
{
Delete( item );
return false;
}
// Grab the existing children.
TreeItemIdArray children;
children.Alloc( GetChildrenCount( item, false ) );
wxTreeItemIdValue dummy;
wxTreeItemId child = GetFirstChild( item, dummy );
while ( child.IsOk() )
{
children.Add( child );
child = GetNextChild( item, dummy );
}
// Enumerate the dir adding new children.
ProjectDirTraverser sink( this, item, children, m_ShowAllMods, m_ShowAllFiles );
wxDir dir( itemPath );
if ( dir.IsOpened() )
dir.Traverse( sink, wxEmptyString, wxDIR_DIRS | wxDIR_FILES );
// Any children still in the list need to be deleted!
for ( int i=0; i < children.GetCount(); i++ )
{
wxASSERT( children[i].IsOk() );
Delete( children[i] );
}
children.Clear();
// Recurse the remaining expanded folders.
child = GetFirstChild( item, dummy );
while ( child.IsOk() )
{
if ( IsExpanded( child ) )
RefreshFolder( child );
child = GetNextChild( item, dummy );
}
// If we have no children then clear the children flag!
if ( GetChildrenCount( item, false ) < 1 )
{
AppendItem( item, "dummy", 0, 0, NULL );
Collapse( item );
DeleteChildren( item );
SetItemHasChildren( item, false );
}
return true;
}
void ProjectCtrl::FixupFolders( wxTreeItemId item )
{
bool hasChildren = GetChildrenCount( item, false ) > 0;
if ( IsExpanded( item ) && !hasChildren )
{
// First add a dummy child... else we cannot collapse!
AppendItem( item, "dummy", 0, 0, NULL );
Collapse( item );
DeleteChildren( item );
SetItemHasChildren( item, true );
return;
}
if ( hasChildren )
SortChildren( item );
wxTreeItemIdValue dummy;
wxTreeItemId child = GetFirstChild( item, dummy );
while ( child.IsOk() )
{
if ( IsExpanded( child ) )
FixupFolders( child );
child = GetNextChild( item, dummy );
}
}
void ProjectCtrl::OnInternalIdle()
{
wxTreeCtrl::OnInternalIdle();
CheckWatcher();
}
void ProjectCtrl::CheckWatcher()
{
wxArrayString signaled;
if ( m_DirWatcher.GetSignaled( &signaled ) <= 0 )
return;
Freeze();
for ( int i=0; i < signaled.GetCount(); i++ )
{
const wxString& dir = signaled[i];
// Find the signaled tree item if it exists
// without needing to expand any items.
wxTreeItemId item = FindIdFromPath( dir, false );
if ( !item.IsOk() )
continue;
// If the directory doesn't exist delete it.
if ( !wxFileName::DirExists( dir ) )
{
Delete( item );
continue;
}
// Refresh the children in the item.
RefreshFolder( item );
}
Thaw();
}
wxTreeItemId ProjectCtrl::FindIdFromPath( const wxString& signaled, bool expand )
{
wxTreeItemId item = GetRootItem();
if ( !item.IsOk() )
return item;
// Make it relative to the project.
wxASSERT( m_ProjectDoc );
wxFileName path;
path.AssignDir( m_ProjectDoc->MakeReleativeTo( signaled ) );
if ( path.IsAbsolute() )
return wxTreeItemId();
const wxArrayString& dirs = path.GetDirs();
wxTreeItemIdValue dummy;
// Walk the dir paths looking for the the id.
for ( int i=0; i < dirs.GetCount(); i++ )
{
if ( expand && !IsExpanded( item ) )
Expand( item );
// Look at the child elements for it.
wxTreeItemId child = GetFirstChild( item, dummy );
while ( child.IsOk() )
{
if ( GetItemText( child ).IsSameAs( dirs[i], wxFileName::IsCaseSensitive() ) )
break;
child = GetNextChild( item, dummy );
}
item = child;
if ( !item.IsOk() )
break;
}
return item;
}
void ProjectCtrl::OnBeginRename( wxTreeEvent& Event )
{
if ( Event.GetItem() == GetRootItem() )
Event.Veto();
}
void ProjectCtrl::OnEndRename( wxTreeEvent& Event )
{
// We never allow the label to be changed here...
// if we want the change, rename the file and the
// dir watcher will take care of updating the item.
Event.Veto();
wxString newName = Event.GetLabel();
if ( newName.IsEmpty() )
return;
wxFileName Source = GetItemPath( Event.GetItem() );
wxFileName Dest;
Dest.AssignDir( Source.GetPath() );
if ( Source.IsDir() )
{
Dest.RemoveLastDir();
Dest.AppendDir( newName );
}
else
Dest.SetFullName( newName );
if ( Dest.SameAs( Source ) )
return;
if ( !wxRenameFile( Source.GetFullPath(), Dest.GetFullPath() ) )
return;
// Give the views a hint to rename any open docs.
wxASSERT( tsGetMainFrame() );
tsFileRenameHint hint;
hint.oldPath = Source.GetFullPath();
hint.newPath = Dest.GetFullPath();
tsGetMainFrame()->SendHintToAllViews( &hint, true );
// Immediately update the dir watch which
// will delete this item and replace it with
// the renamed one.
CheckWatcher();
}
void ProjectCtrl::OnDragBegin( wxTreeEvent& event )
{
// We sometimes get a double drag start on wxMSW... this
// is because wxTreeCtrl implements its own drag detection
// and doesn't disable the native treeview control from
// sending it's own begin drag event. Reported bug.
if ( m_IsDragging )
return;
// Grab the current selection.
UnnestSelections();
GetSelections( m_DragItems );
// We cannot drag the root!
if ( m_DragItems.Index( GetRootItem().m_pItem ) != wxNOT_FOUND )
return;
m_LastHighlight = event.GetItem();
UnselectAll();
SetItemDropHighlight( m_LastHighlight );
m_IsDragging = true;
CaptureMouse();
::wxSetCursor( m_DragCursor );
}
void ProjectCtrl::OnDragMove( wxMouseEvent& event )
{
if ( !m_IsDragging )
{
event.Skip();
return;
}
// Check for lost captures.
if ( !HasCapture() )
{
m_IsDragging = false;
SetItemDropHighlight( m_LastHighlight, false );
m_LastHighlight.Unset();
//::wxSetCursor( wxNullCursor );
m_DragExpandTimer.Stop();
SelectItems( m_DragItems );
return;
}
int flags = 0;
wxTreeItemId newItem = HitTest( event.GetPosition(), flags );
if ( !newItem.IsOk() )
{
::wxSetCursor( wxCursor( wxCURSOR_NO_ENTRY ) );
if ( m_LastHighlight.IsOk() )
{
SetItemDropHighlight( m_LastHighlight, false );
SelectItems( m_DragItems );
m_DragExpandTimer.Stop();
m_LastHighlight.Unset();
}
return;
}
::wxSetCursor( m_DragCursor );
if ( newItem != m_LastHighlight )
{
UnselectAll();
SetItemDropHighlight( m_LastHighlight, false );
m_LastHighlight = newItem;
SetItemDropHighlight( m_LastHighlight );
m_DragExpandTimer.Start( 750, true );
}
}
void ProjectCtrl::OnDragExpandTimer( wxTimerEvent& event )
{
if ( m_LastHighlight.IsOk() &&
ItemHasChildren( m_LastHighlight ) &&
!IsExpanded( m_LastHighlight ) )
Expand( m_LastHighlight );
}
void ProjectCtrl::OnDragKey( wxKeyEvent& event )
{
if ( !m_IsDragging )
{
event.Skip();
return;
}
if ( event.GetKeyCode() == WXK_ESCAPE )
{
m_IsDragging = false;
SetItemDropHighlight( m_LastHighlight, false );
m_LastHighlight.Unset();
m_DragExpandTimer.Stop();
SelectItems( m_DragItems );
ReleaseMouse();
}
}
void ProjectCtrl::OnDragEnd( wxMouseEvent& event )
{
if ( !m_IsDragging )
{
event.Skip();
return;
}
m_IsDragging = false;
m_DragExpandTimer.Stop();
//::wxSetCursor( wxNullCursor );
SetItemDropHighlight( m_LastHighlight, false );
m_LastHighlight.Unset();
if ( !HasCapture() )
{
SelectItems( m_DragItems );
return;
}
ReleaseMouse();
int flags = 0;
wxTreeItemId destItem = HitTest( event.GetPosition(), flags );
if ( !destItem.IsOk() )
{
SelectItems( m_DragItems );
return;
}
// Get the dest item.
wxFileName dest = GetItemPath( destItem );
if ( !dest.IsDir() )
{
// The dest must be a folder... so assume
// the user means the operation to occur
// on the dest file's folder.
destItem = GetItemParent( destItem );
dest = GetItemPath( destItem );
if ( !dest.IsDir() )
{
SelectItems( m_DragItems );
return;
}
}
// Make an array of the items that can be moved and copied to the dest.
wxArrayTreeItemIds sourceItems = m_DragItems;
{
// First remove items which are a parent to the dest.
wxTreeItemId id = destItem;
while ( id.IsOk() )
{
size_t index = sourceItems.Index( id.m_pItem );
if ( index != wxNOT_FOUND )
sourceItems.RemoveAt( index );
id = GetItemParent( id );
}
// Now remove items whos parent is the dest and
// the operation would be redundent.
for ( int i=0; i < sourceItems.GetCount(); )
{
if ( destItem == GetItemParent( sourceItems[i] ) )
{
sourceItems.RemoveAt( i );
continue;
}
i++;
}
}
// If we have no items left then the drag was
// completely invalid... so barf.
if ( sourceItems.IsEmpty() )
{
SelectItems( m_DragItems );
tsBellEx( wxICON_INFORMATION );
return;
}
// Popup a menu and get the result inline.
int result = 0;
{
tsMenu* menu = new tsMenu;
menu->Append( tsID_MOVE, _T( "Move Here" ) );
menu->Append( tsID_COPY, _T( "Copy Here" ) );
menu->AppendSeparator();
menu->Append( wxID_CANCEL, _T( "Cancel" ) );
result = tsTrackPopupMenu( menu, true, event.GetPosition(), this );
delete menu;
}
if ( result == 0 || result == wxID_CANCEL )
{
SelectItems( m_DragItems );
return;
}
// Ok build the source string array.
wxArrayString sourceArray;
for ( int i=0; i < sourceItems.GetCount(); i++ )
{
wxString path = GetItemPath( sourceItems[i] );
wxASSERT( !path.IsEmpty() );
sourceArray.Add( path );
}
if ( result == tsID_COPY )
tsCopyFiles( sourceArray, dest.GetFullPath() );
else
{
wxASSERT( result == tsID_MOVE );
tsMoveFiles( sourceArray, dest.GetFullPath() );
}
// Let the watcher update the tree items.
CheckWatcher();
// Go ahead and expand the dest if it's not already so.
if ( !IsExpanded( destItem ) )
{
// Gotta force it to have children to
// get it to expand.
SetItemHasChildren( destItem, true );
Expand( destItem );
}
}
void ProjectCtrl::OnOpenItem( wxTreeEvent& Event )
{
if ( Event.GetItem().IsOk() )
{
OpenItem( Event.GetItem() );
return;
}
// Open all selected items.
wxArrayTreeItemIds selected;
GetSelections( selected );
for ( int i=0; i < selected.GetCount(); i++ )
OpenItem( selected[i] );
}
void ProjectCtrl::OnItemMenu( wxTreeEvent& Event )
{
// We're about to force the focus to ourselves
// so remove any focus view override.
m_FocusView = NULL;
// Make sure we have the focus and the
// active document.
SetFocus();
wxASSERT( this == FindFocus() );
wxASSERT( m_ProjectDoc );
wxASSERT( m_ProjectDoc->GetFirstView() );
m_ProjectDoc->GetFirstView()->Activate( true );
wxASSERT( this == FindFocus() );
wxASSERT( m_ProjectDoc->GetDocumentManager()->GetCurrentView() == m_ProjectDoc->GetFirstView() );
// TODO: Add icons to context menu!
// Get the current selection set.
wxArrayTreeItemIds selected;
GetSelections( selected );
// If this is only the root then have a very
// simple menu... just do it and return.
if ( selected.GetCount() == 1 && selected[0] == GetRootItem() )
{
tsMenu* menu = new tsMenu;
menu->AppendIconItem( tsID_EXPLORE, _T( "&Explore" ), ts_explorer16 );
menu->AppendSeparator();
menu->Append( tsID_NEW_FILE, _T( "New Script" ) );
menu->Append( tsID_NEW_FOLDER, _T( "New Folder" ) );
menu->AppendSeparator();
menu->Append( tsID_CLEARDSOS, _T( "&Delete DSOs" ) );
menu->AppendSeparator();
menu->Append( tsID_PROJECT_PROPERTIES, _T( "&Properties" ) );
// Pop them menu... doesn't return till the menu is
// canceled or it executes a command.
PopupMenu( menu, Event.GetPoint() );
delete menu;
return;
}
// If we have multiple selections and one is the
// root item... remove it.
const wxTreeItemId rootId = GetRootItem();
if ( selected.GetCount() > 1 && selected.Index( rootId.m_pItem ) != wxNOT_FOUND )
{
SelectItem( rootId, false );
selected.Empty();
GetSelections( selected );
wxASSERT( selected.Index( rootId.m_pItem ) == wxNOT_FOUND );
}
// Get some counts on the number of files and folder selected.
size_t DSOs = 0; size_t files = 0; size_t folders = 0;
{
wxString path;
for ( int i=0; i < selected.GetCount(); i++ )
{
path = GetItemPath( selected[i] );
if ( wxFileName::DirExists( path ) )
++folders;
else
{
++files;
if ( tsGetPrefs().IsScriptFile( path ) )
{
if ( !tsGetPrefs().GetDSOForScript( path ).IsEmpty() )
++DSOs;
}
}
}
}
tsMenu* menu = new tsMenu;
if ( files == selected.GetCount() )
{
menu->AppendIconItem( tsID_PROJECT_OPEN, _T( "&Open" ), ts_open_document16 );
if ( files == 1 )
menu->Append( tsID_PROJECT_OPENWITH, _T( "Open Wit&h..." ) );
if ( DSOs )
menu->Append( tsID_CLEARDSO, _T( "Delete DSO" ) );
if ( files == 1 )
menu->AppendIconItem( tsID_EXPLORE, _T( "E&xplore" ), ts_explorer16 );
menu->AppendSeparator();
}
else if ( folders == 1 && files == 0 )
{
menu->AppendIconItem( tsID_EXPLORE, _T( "E&xplore" ), ts_explorer16 );
menu->AppendSeparator();
menu->Append( tsID_NEW_FILE, _T( "&New Script" ) );
menu->Append( tsID_NEW_FOLDER, _T( "&New Folder" ) );
menu->AppendSeparator();
menu->AppendIconItem( tsID_FINDINFILES, _T( "F&ind in Files" ), ts_findinfiles16 );
menu->AppendSeparator();
}
#ifdef __WXMSW__
if ( selected.GetCount() == 1 )
{
wxString file = GetItemPath( selected[0] );
m_OsMenu = new ShellMenu( file );
menu->Append( wxID_ANY, _T( "&Explorer" ), m_OsMenu );
menu->AppendSeparator();
}
#endif
menu->AppendIconItem( wxID_DELETE, _T( "&Delete" ), ts_delete16 );
if ( selected.GetCount() == 1 )
{
menu->Append( tsID_RENAME, _T( "Rena&me" ) );
menu->AppendSeparator();
menu->Append( wxID_PROPERTIES, _T( "P&roperties" ) );
}
// Pop them menu... doesn't return till the menu is
// canceled or it executes a command.
PopupMenu( menu, Event.GetPoint() );
delete menu;
#ifdef __WXMSW__
m_OsMenu = NULL;
#endif
}
#ifdef __WXMSW__
WXLRESULT ProjectCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
{
if ( m_OsMenu &&
m_OsMenu->MSWWindowProc(nMsg, wParam, lParam) == 0 )
return 0;
return wxTreeCtrl::MSWWindowProc(nMsg, wParam, lParam);
}
#endif
void ProjectCtrl::OpenItem( const wxTreeItemId& item )
{
wxFileName file( GetItemPath( item ) );
if ( file.IsDir() ) {
return;
}
if ( tsGetPrefs().IsScriptFile( file.GetFullPath() ) ||
tsGetPrefs().IsTextFile( file.GetFullPath() ) ) {
// While OpenFile() will set focus to the editor control
// it is stomped on by a mystery WM_FOCUS message on this
// control. Store the focus view which we redirect the
// focus message to when we recieve it.
wxASSERT( tsGetMainFrame() );
m_FocusView = tsGetMainFrame()->OpenFile( file.GetFullPath() );
} else {
// Launch the associated application.
wxString command;
wxFileType* type = wxTheMimeTypesManager->GetFileTypeFromExtension( file.GetExt() );
if ( type ) {
wxString command = type->GetOpenCommand( file.GetFullPath() );
if ( !command.IsEmpty() ) {
if ( wxExecute( command, wxEXEC_ASYNC, NULL ) != 0 ) {
return;
}
}
}
OpenItemWith( item );
}
}
void ProjectCtrl::OpenItemWith( const wxTreeItemId& item )
{
wxFileName file( GetItemPath( item ) );
if ( file.IsDir() ) {
return;
}
// If we got here then let the shell handle it!
tsShellOpenAs( file.GetFullPath() );
}
wxTreeItemId ProjectCtrl::Select( const wxString& path )
{
// Before we select do an idle tick, so
// than any pending changes in the project
// tree are dealt with.
CheckWatcher();
wxTreeItemId item = FindIdFromPath( path, true );
if ( item.IsOk() )
{
UnselectAll();
EnsureVisible( item );
SelectItem( item );
}
return item;
}
wxString ProjectCtrl::GetItemPath( const wxTreeItemId& item ) const
{
if ( !item.IsOk() )
return wxEmptyString;
ProjectCtrlItemData* data = (ProjectCtrlItemData*)GetItemData( item );
if ( !data )
return wxEmptyString;
return data->GetPath();
}
void ProjectCtrl::OnToolTip( wxTreeEvent& Event )
{
wxTreeItemId item = Event.GetItem();
if ( item.IsOk() ) {
ProjectCtrlItemData* data = (ProjectCtrlItemData*)GetItemData( item );
if ( data ) {
/*
wxFileName file( data->m_FullPath );
wxDateTime mod = file.GetModificationTime();
wxFileName::();
Event.SetToolTip( );
*/
}
}
}
int ProjectCtrl::OnCompareItems( const wxTreeItemId& item1, const wxTreeItemId& item2 )
{
wxFileName file1( GetItemPath( item1 ) );
wxFileName file2( GetItemPath( item2 ) );
// Directories always go first!
if ( file1.IsDir() && !file2.IsDir() )
return -1;
if ( file2.IsDir() && !file1.IsDir() )
return 1;
return file1.GetFullPath().CmpNoCase( file2.GetFullPath() );
}
void ProjectCtrl::NewFolder( wxTreeItemId item )
{
wxFileName parent = GetItemPath( item );
// Get a folder name!
wxFileName folder;
int i = 1;
do
{
wxString name;
name << "NewFolder" << i++;
folder.AssignDir( parent.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR ) + name );
} while ( folder.DirExists() );
// Create the folder.
if ( !wxMkdir( folder.GetFullPath() ) )
{
wxMessageDialog dlg( this, "The folder could not be created!", "Torsion", wxOK | wxICON_ERROR );
dlg.ShowModal();
return;
}
// Select the folder in the view.
item = Select( folder.GetFullPath() );
EditLabel( item );
}
void ProjectCtrl::NewFile( wxTreeItemId item )
{
wxFileName parent = GetItemPath( item );
// Get a file name!
wxFileName file;
const wxString ext = tsGetPrefs().GetDefaultScriptExtension();
int i = 1;
do
{
wxString name;
name << parent.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR ) << "NewScript" << i++ << "." << ext;
file.Assign( name );
} while ( file.FileExists() );
// Create the file.
wxFile dummy( file.GetFullPath(), wxFile::write_excl );
if ( !dummy.IsOpened() )
{
wxMessageDialog dlg( this, "The file could not be created!", "Torsion", wxOK | wxICON_ERROR );
dlg.ShowModal();
return;
}
// Make sure the parent is expanded!
if ( !IsExpanded( item ) )
{
SetItemHasChildren( item, true );
Expand( item );
}
// Select the file in the view and edit it's name.
item = Select( file.GetFullPath() );
EditLabel( item );
}
void ProjectCtrl::UnnestSelections()
{
wxArrayTreeItemIds selected;
GetSelections( selected );
// Remove any id that is a child of another id
// in the list. This removes children that may
// be selected under a folder.
for ( int i=0; i < selected.GetCount(); i++ )
{
wxTreeItemId id = selected[i];
int found = wxNOT_FOUND;
while ( (id = GetItemParent(id)).IsOk() )
{
found = selected.Index( id.m_pItem );
if ( found != wxNOT_FOUND )
{
SelectItem( selected[i], false );
break;
}
}
}
}
void ProjectCtrl::SelectItems( const wxArrayTreeItemIds& items )
{
UnselectAll();
for ( int i=0; i < items.GetCount(); i++ )
SelectItem( items[i] );
}
| 26.122709 | 142 | 0.622926 | [
"render"
] |
d95d46e14ce4983bcd05bea9fec0798c9bcda106 | 4,954 | cpp | C++ | Client/mainwindow.cpp | Maximsiv1410/udp_project | ff123139d2f15da27cc8f0896741daebe80e71b0 | [
"MIT"
] | null | null | null | Client/mainwindow.cpp | Maximsiv1410/udp_project | ff123139d2f15da27cc8f0896741daebe80e71b0 | [
"MIT"
] | null | null | null | Client/mainwindow.cpp | Maximsiv1410/udp_project | ff123139d2f15da27cc8f0896741daebe80e71b0 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <vector>
#include <QBuffer>
#include <QMessageBox>
#include <fstream>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->graphicsView->setScene(new QGraphicsScene(this));
ui->graphicsView->scene()->addItem(&myPixmap);
work.reset(new work_entity(ios));
auto threads = std::thread::hardware_concurrency();
if (!threads) threads = 2;
for (std::size_t i = 0; i < 4; i++) {
task_force.push_back(std::thread([this]{ ios.run(); }));
}
//sipper.set_begin_handler([](){});
//sipper.set_end_handler([](){});
sipper = std::make_unique<sip_engine>(ios, "127.0.0.1", 5060);
sipper->start(true);
connect(sipper.get(), &sip_engine::incoming_call, this, &MainWindow::incoming_call);
}
void MainWindow::on_startBtn_clicked()
{
if (video.isOpened()) {
ui->startBtn->setText("Start");
video.release();
return;
}
int deviceID = 0; // 0 = open default camera
int apiID = cv::CAP_ANY; // 0 = autodetect default API
if (video.open(deviceID, apiID)) {
ui->startBtn->setText("Stop");
std::size_t id = 0;
while (video.isOpened()) {
cv::Mat frame;
video >> frame;
if (!frame.empty()) {
QImage img(frame.data,
frame.cols,
frame.rows,
frame.step,
QImage::Format_RGB888);
myPixmap.setPixmap(QPixmap::fromImage(img.rgbSwapped()));
ui->graphicsView->fitInView(&myPixmap, Qt::KeepAspectRatio);
//ui->graphicsView->scene()->setSceneRect(0, 0, img.width(), img.height()); // bad
if (rtp_service) {
rtp_service->cache_frame(frame, id++);
}
}
qApp->processEvents();
}
}
}
void MainWindow::frame_gathered(QImage frame) {
qDebug() << "frame got!!! form\n";
partnerPixmap.setPixmap(QPixmap::fromImage(frame.rgbSwapped()));
ui->partnerGraphicsView->fitInView(&partnerPixmap, Qt::KeepAspectRatio);
}
void MainWindow::incoming_call(/* session_info */) {
rtp_service.reset(new rtp_io(ios, "127.0.0.1", 45777));
rtp_service->start(true);
connect(rtp_service.get(), &rtp_io::frame_gathered, this, &MainWindow::frame_gathered);
ui->partnerGraphicsView->setScene(new QGraphicsScene(this));
ui->partnerGraphicsView->scene()->addItem(&partnerPixmap);
sipper->incoming_call_accepted();
startStream();
}
void MainWindow::startStream() {
if (video.isOpened()) {
ui->startBtn->setText("Start");
video.release();
return;
}
if (video.open(0)) {
ui->startBtn->setText("Stop");
std::size_t id = 0;
while (video.isOpened()) {
cv::Mat frame;
video >> frame;
if (!frame.empty()) {
QImage img(frame.data,
frame.cols,
frame.rows,
frame.step,
QImage::Format_RGB888);
myPixmap.setPixmap(QPixmap::fromImage(img.rgbSwapped()));
ui->graphicsView->fitInView(&myPixmap, Qt::KeepAspectRatio);
//ui->graphicsView->scene()->setSceneRect(0, 0, img.width(), img.height()); // bad
if (rtp_service) {
rtp_service->cache_frame(frame, id++);
}
}
qApp->processEvents();
}
}
}
void MainWindow::on_callButton_clicked()
{
if (!sipper) return;
if (ui->callName->text().isEmpty()) return;
rtp_service.reset(new rtp_io(ios, "127.0.0.1", 45777));
rtp_service->start(true);
connect(rtp_service.get(), &rtp_io::frame_gathered, this, &MainWindow::frame_gathered);
ui->partnerGraphicsView->setScene(new QGraphicsScene(this));
ui->partnerGraphicsView->scene()->addItem(&partnerPixmap);
sipper->invite(ui->callName->text().toStdString());
startStream();
}
void MainWindow::on_registerBtn_clicked()
{
if (ui->registerTxt->text().isEmpty()) return;
sipper->do_register(ui->registerTxt->text().toStdString());
}
MainWindow::~MainWindow()
{
delete ui;
/* if (sipper) {
sipper->shutdown();
}
if (rtp_service) {
rtp_service->shutdown();
} */
if (work) {
work.reset(nullptr);
}
if (!ios.stopped()) {
ios.stop();
}
for (auto & thread : task_force) {
if (thread.joinable()) {
thread.join();
}
}
}
| 25.802083 | 99 | 0.534316 | [
"vector"
] |
d96a8437b43ee85ba3f810aefaba979688061286 | 5,546 | cpp | C++ | inference-engine/tests/unit/cpu/bf16_transformer_test.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 2 | 2021-02-26T15:46:19.000Z | 2021-05-16T20:48:13.000Z | inference-engine/tests/unit/cpu/bf16_transformer_test.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | 1 | 2020-12-22T05:01:12.000Z | 2020-12-23T09:49:43.000Z | inference-engine/tests/unit/cpu/bf16_transformer_test.cpp | shre2398/openvino | f84a6d97ace26b75ae9d852525a997cbaba32e6a | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <memory>
#include <gtest/gtest.h>
#include <ngraph/ngraph.hpp>
#include <ngraph_ops/fully_connected.hpp>
#include <inference_engine.hpp>
#include <details/ie_cnn_network_tools.h>
#include <convert_function_to_cnn_network.hpp>
#include <bf16transformer.h>
using ngraph::Shape;
using ngraph::element::Type;
using namespace ngraph::op;
using std::make_shared;
using InferenceEngine::Precision;
std::map<std::string, InferenceEngine::CNNLayerPtr> get_layer_collection(InferenceEngine::CNNNetwork net) {
IE_SUPPRESS_DEPRECATED_START
auto all_layers = InferenceEngine::details::CNNNetSortTopologically(net);
std::map<std::string, InferenceEngine::CNNLayerPtr> res;
for (auto &layer : all_layers) {
res[layer->name] = layer;
}
IE_SUPPRESS_DEPRECATED_END
return res;
}
enum TypeOfNet { NG, IE };
InferenceEngine::CNNNetwork create_net(std::shared_ptr<ngraph::Function> &func, TypeOfNet type) {
InferenceEngine::CNNNetwork ng_net(func);
if (type == NG)
return ng_net;
else
return InferenceEngine::CNNNetwork {InferenceEngine::details::convertFunctionToICNNNetwork(func, ng_net)};
}
TEST(BF16TransformerTest, KeepMemoryPrecision) {
/*
* Suggested pattern
* _______ _____
* [_mem_r_] [_inp_]
* _|______|_
* [___mul____]
* __|__
* [_sig_]
* __|__
* [_fc1_]
* ___|____
* ___|___ __|__
* [_mem_w_] [_fc2_]
* __|__
* [_out_]
*
* If does'n care about memory precision the mem_w will have precicion of data
* between fc1 and fc2 operations. In case of enabled BF16 it should be BF16.
* However mem_r still keep original precision.
*/
Shape shape = {3, 2};
Type type = ngraph::element::f32;
auto input = make_shared<Parameter>(type, shape);
auto mem_i = make_shared<Constant>(type, shape, 0);
auto mem_r = make_shared<ReadValue>(mem_i, "id");
mem_r->set_friendly_name("mem_r");
auto mul = make_shared<Multiply>(mem_r, input);
auto sig = make_shared<Sigmoid>(mul);
auto fc1_w = make_shared<Constant>(type, Shape{2, 2}, 1);
auto fc1_b = make_shared<Constant>(type, Shape{2}, 1);
auto fc1 = make_shared<FullyConnected>(sig, fc1_w, fc1_b, shape);
auto fc2_w = make_shared<Constant>(type, Shape{2, 2}, 1);
auto fc2_b = make_shared<Constant>(type, Shape{2}, 1);
auto fc2 = make_shared<FullyConnected>(fc1, fc2_w, fc2_b, shape);
auto mem_w = make_shared<Assign>(fc1, "id");
mem_w->set_friendly_name("mem_w");
// WA. Limitation of ngraph. control_dependency are required.
mem_w->add_control_dependency(mem_r);
fc2->add_control_dependency(mem_w);
auto function = make_shared<ngraph::Function>(
ngraph::NodeVector {fc2},
ngraph::ParameterVector {input});
auto net = create_net(function, IE);
// Apply tested BF16 transformation
MKLDNNPlugin::BF16Transformer transformer;
transformer.convertToBFloat16(net);
// Check precision
auto layers = get_layer_collection(net);
IE_SUPPRESS_DEPRECATED_START
Precision prc_mem_r = layers["mem_r"]->outData[0]->getPrecision();
Precision prc_mem_w = layers["mem_w"]->insData[0].lock()->getPrecision();
IE_SUPPRESS_DEPRECATED_END
ASSERT_EQ(prc_mem_r, Precision::BF16);
ASSERT_EQ(prc_mem_w, Precision::BF16);
}
TEST(BF16TransformerTest, DISABLED_KeepMemoryPrecisionWithGEMM) {
/* _______ _____
* [_mem_r_] [_inp_]
* _|______|_
* [___mul____]
* __|__
* [_sig_]
* __|____
* [_gemm1_]
* ___|____
* ___|___ __|____
* [_mem_w_] [_gemm2_]
* __|__
* [_out_]
*
* Same as KeepMemoryPrecision test with replacing FC -> GEMM
*/
Shape shape = {3, 2};
Type type = ngraph::element::f32;
auto input = make_shared<Parameter>(type, shape);
auto mem_i = make_shared<Constant>(type, shape, 0);
auto mem_r = make_shared<ReadValue>(mem_i, "id");
mem_r->set_friendly_name("mem_r");
auto mul = make_shared<Multiply>(mem_r, input);
auto sig = make_shared<Sigmoid>(mul);
auto fc1_w = make_shared<Constant>(type, Shape{2, 2}, 1);
auto fc1 = make_shared<MatMul>(sig, fc1_w);
auto fc2_w = make_shared<Constant>(type, Shape{2, 2}, 1);
auto fc2 = make_shared<MatMul>(fc1, fc2_w);
auto mem_w = make_shared<Assign>(fc1, "id");
mem_w->set_friendly_name("mem_w");
// WA. Limitation of ngraph. control_dependency are required.
mem_w->add_control_dependency(mem_r);
fc2->add_control_dependency(mem_w);
auto function = make_shared<ngraph::Function>(
ngraph::NodeVector {fc2},
ngraph::ParameterVector {input});
auto net = create_net(function, IE);
// Apply tested BF16 transformation
MKLDNNPlugin::BF16Transformer transformer;
transformer.convertToBFloat16(net);
// Check precision
auto layers = get_layer_collection(net);
IE_SUPPRESS_DEPRECATED_START
Precision prc_mem_r = layers["mem_r"]->outData[0]->getPrecision();
Precision prc_mem_w = layers["mem_w"]->insData[0].lock()->getPrecision();
IE_SUPPRESS_DEPRECATED_END
ASSERT_EQ(prc_mem_r, Precision::BF16);
ASSERT_EQ(prc_mem_w, Precision::BF16);
}
| 32.432749 | 114 | 0.652182 | [
"shape"
] |
d96a8eb9efa96d1d0b81496d1e5e4b58d3d3199f | 1,348 | cpp | C++ | codeforces/1216D.cpp | NafiAsib/competitive-programming | 3255b2fe3329543baf9e720e1ccaf08466d77303 | [
"MIT"
] | null | null | null | codeforces/1216D.cpp | NafiAsib/competitive-programming | 3255b2fe3329543baf9e720e1ccaf08466d77303 | [
"MIT"
] | null | null | null | codeforces/1216D.cpp | NafiAsib/competitive-programming | 3255b2fe3329543baf9e720e1ccaf08466d77303 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define sf scanf
#define pf printf
#define endl "\n"
#define off ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define fr freopen("in.txt", "r", stdin)
#define fw freopen("out.txt", "w", stdout)
#define pb push_back
#define eb emplace_back
#define watch(x) cout<<(#x)<<" is "<<(x)<<endl
#define pass(x) cout<<"Passed step "<<(x)<<endl
#define RESET(a, b) memset(a, b, sizeof a)
typedef long long ll;
typedef unsigned int ui;
typedef pair<int, int> pii;
typedef vector< int > vi;
typedef vector < vi > vii;
int mod = 1000000007; //10^9+7
const double eps = 1e-9;
//const double pi = 2*acos(0.0);
//int fx[]={+1,-1,+0,+0};
//int fy[]={+0,+0,+1,-1};
//int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};
//int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};
int main()
{
//fr;
int n;
cin>>n;
ll ara[n+2];
for(int i=0; i<n; i++) cin>>ara[i];
sort(ara, ara+n, greater<int>());
if(n == 2) {
cout<<'1'<<" "<<ara[0]-ara[1]<<endl;
return 0;
}
ll gc;
ll mx = ara[0];
gc = __gcd(mx-ara[1], mx-ara[2]);
for(int i=3; i<n; i++) {
gc = __gcd(gc, mx-ara[i]);
}
ll cnt = 0LL;
for(int i=1; i<n; i++) {
cnt += (mx-ara[i])/gc;
}
//watch(mx);
cout<<cnt<<" "<<gc<<endl;
return 0;
} | 24.962963 | 68 | 0.515579 | [
"vector"
] |
d96f902381e523b0a10d24a200abbe322689b007 | 1,724 | hpp | C++ | etcd/v3/V3Response.hpp | edmund-troche/etcd-cpp-apiv3 | f21c45b362297131b191ea8fc5033f8ffca4cc04 | [
"BSD-3-Clause"
] | 139 | 2016-09-20T00:28:04.000Z | 2020-09-27T15:05:11.000Z | etcd/v3/V3Response.hpp | edmund-troche/etcd-cpp-apiv3 | f21c45b362297131b191ea8fc5033f8ffca4cc04 | [
"BSD-3-Clause"
] | 12 | 2016-12-09T02:58:47.000Z | 2020-09-04T09:17:22.000Z | etcd/v3/V3Response.hpp | edmund-troche/etcd-cpp-apiv3 | f21c45b362297131b191ea8fc5033f8ffca4cc04 | [
"BSD-3-Clause"
] | 63 | 2016-12-06T11:42:29.000Z | 2020-09-24T06:15:49.000Z | #ifndef __V3_RESPONSE_HPP__
#define __V3_RESPONSE_HPP__
#include <grpc++/grpc++.h>
#include "proto/kv.pb.h"
#include "proto/v3election.pb.h"
#include "etcd/v3/KeyValue.hpp"
namespace etcdv3
{
class V3Response
{
public:
V3Response(): error_code(0), index(0){};
void set_error_code(int code);
int get_error_code() const;
std::string const & get_error_message() const;
void set_error_message(std::string msg);
void set_action(std::string action);
int64_t get_index() const;
std::string const & get_action() const;
std::vector<etcdv3::KeyValue> const & get_values() const;
std::vector<etcdv3::KeyValue> const & get_prev_values() const;
etcdv3::KeyValue const & get_value() const;
etcdv3::KeyValue const & get_prev_value() const;
bool has_values() const;
int64_t get_compact_revision() const;
void set_lock_key(std::string const &key);
std::string const &get_lock_key() const;
void set_name(std::string const &name);
std::string const &get_name() const;
std::vector<mvccpb::Event> const & get_events() const;
uint64_t get_cluster_id() const;
uint64_t get_member_id() const;
uint64_t get_raft_term() const;
protected:
int error_code;
int64_t index;
std::string error_message;
std::string action;
etcdv3::KeyValue value;
etcdv3::KeyValue prev_value;
std::vector<etcdv3::KeyValue> values;
std::vector<etcdv3::KeyValue> prev_values;
int64_t compact_revision = -1;
std::string lock_key; // for lock
std::string name; // for campaign (in v3election)
std::vector<mvccpb::Event> events; // for watch
uint64_t cluster_id;
uint64_t member_id;
uint64_t raft_term;
};
}
#endif
| 30.785714 | 66 | 0.693155 | [
"vector"
] |
d97aa5747b8c1e5db78a3ec91a84d24b0deac40b | 1,306 | cpp | C++ | Quasics2021Code/MaeTester/src/main/cpp/subsystems/Lights.cpp | quasics/quasics-frc-sw-2015 | e5a4f1b4e209ba941f12c2cc41759854f3c5420b | [
"BSD-3-Clause"
] | 5 | 2016-12-16T19:05:05.000Z | 2021-03-05T01:23:27.000Z | Quasics2021Code/MaeTester/src/main/cpp/subsystems/Lights.cpp | quasics/quasics-frc-sw-2015 | e5a4f1b4e209ba941f12c2cc41759854f3c5420b | [
"BSD-3-Clause"
] | null | null | null | Quasics2021Code/MaeTester/src/main/cpp/subsystems/Lights.cpp | quasics/quasics-frc-sw-2015 | e5a4f1b4e209ba941f12c2cc41759854f3c5420b | [
"BSD-3-Clause"
] | 2 | 2020-01-03T01:52:43.000Z | 2022-02-02T01:23:45.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "subsystems/Lights.h"
Lights::Lights() {
SetSubsystem("Lights");
// We need to tell the addressable LED thing how many lights it is
// theoretically equipped with. (If we go over, no biggie. But it
// needs to get a valid length for comparison to the size of the
// buffer when "SetData()" is called later: if the buffer is too big,
// that will fail.)
m_led.SetLength(kLength);
// Start with all of the lights off.
TurnStripOff();
}
// This method will be called once per scheduler run
void Lights::Periodic() {}
void Lights::SetStripColor(int red, int green, int blue){
std::cout << "Setting strip to solid color" << std::endl;
for (int i = 0; i < kLength; i++) {
m_ledBuffer[i].SetRGB(red, green, blue);
}
m_led.SetData(m_ledBuffer);
}
void Lights::SetStripColor(
std::function<frc::AddressableLED::LEDData(int position)> colorFcn) {
std::cout << "Setting strip colors" << std::endl;
for (int i = 0; i < kLength; i++) {
m_ledBuffer[i] = colorFcn(i);
}
m_led.SetData(m_ledBuffer);
}
void Lights::TurnStripOff() {
SetStripColor(0, 0, 0);
} | 30.372093 | 74 | 0.683767 | [
"solid"
] |
d97ae9f90fe947e2f34f536770210fdb61efc401 | 16,313 | cpp | C++ | source/CDDraw.cpp | prokoptasis/defenders | 773fb4ec898d54e76df4cd1a7a6fc16d8f304725 | [
"MIT"
] | null | null | null | source/CDDraw.cpp | prokoptasis/defenders | 773fb4ec898d54e76df4cd1a7a6fc16d8f304725 | [
"MIT"
] | null | null | null | source/CDDraw.cpp | prokoptasis/defenders | 773fb4ec898d54e76df4cd1a7a6fc16d8f304725 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Name : CDDraw.cpp
// Desc : DDraw Class
// Date : 2002.11.17
// Mail : jhook@hanmail.net
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// INCLUDE
/////////////////////////////////////////////////////////////////////////////
#include "CDDraw.h"
/////////////////////////////////////////////////////////////////////////////
// Define
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// GLOBAL
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// TYPE
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// PROTOTYPES
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// FUNCTIONS
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Name : CDDraw()
// Desc :
/////////////////////////////////////////////////////////////////////////////
CDDraw::CDDraw()
{
lpdd7 = NULL; // dd object
lpddsprimary = NULL; // dd primary surface
lpddsback = NULL;
lpddclipper = NULL;
m_bWindowed = TRUE;
primary_buffer = NULL;
back_buffer = NULL;
primary_lpitch = NULL;
back_lpitch = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// Name : ~CDDraw()
// Desc :
/////////////////////////////////////////////////////////////////////////////
CDDraw::~CDDraw()
{
DestoryCDDraw();
}
/////////////////////////////////////////////////////////////////////////////
// Name : CreateFullScreen(HWND hWnd,DWORD dwWidth,DWORD dwHeight,DWORD dwBPP)
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::CreateFullScreen(HWND hWnd,DWORD dwWidth,DWORD dwHeight,DWORD dwBPP)
{
DestoryCDDraw();
if( FAILED( hr = DirectDrawCreateEx( NULL, (VOID**)&lpdd7, IID_IDirectDraw7, NULL ) ) )
return E_FAIL;
hr = lpdd7->SetCooperativeLevel( hWnd, DDSCL_EXCLUSIVE|DDSCL_FULLSCREEN );
if( FAILED(hr) )
return E_FAIL;
if( FAILED( lpdd7->SetDisplayMode( dwWidth, dwHeight, dwBPP, 0, 0 ) ) )
return E_FAIL;
CDDRAW_INITSTRUCT(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP |
DDSCAPS_COMPLEX | DDSCAPS_3DDEVICE;
ddsd.dwBackBufferCount = 1;
if( FAILED( hr = lpdd7->CreateSurface( &ddsd, &lpddsprimary,NULL ) ) )
return E_FAIL;
// Get a pointer to the back buffer
ZeroMemory( &ddscaps, sizeof( ddscaps ) );
ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
if( FAILED( hr = lpddsprimary->GetAttachedSurface( &ddscaps,&lpddsback ) ) )
return E_FAIL;
lpddsback->AddRef();
m_hWnd = hWnd;
UpdateBounds();
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Name : CreateWindowedScreen(HWND hWnd,DWORD dwWidth,DWORD dwHeight)
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::CreateWindowedScreen(HWND hWnd,DWORD dwWidth,DWORD dwHeight)
{
DestoryCDDraw();
if( FAILED( hr = DirectDrawCreateEx( NULL, (VOID**)&lpdd7,IID_IDirectDraw7, NULL ) ) )
return E_FAIL;
hr = lpdd7->SetCooperativeLevel( hWnd, DDSCL_NORMAL );
if( FAILED(hr) )
return E_FAIL;
RECT rcWork;
RECT rc;
DWORD dwStyle;
dwStyle = GetWindowStyle( hWnd );
dwStyle &= ~WS_POPUP;
dwStyle |= WS_OVERLAPPED | WS_CAPTION | WS_THICKFRAME;
SetWindowLong( hWnd, GWL_STYLE, dwStyle );
SetRect( &rc, 0, 0, dwWidth, dwHeight );
AdjustWindowRectEx( &rc, GetWindowStyle(hWnd), GetMenu(hWnd) != NULL,GetWindowExStyle(hWnd) );
SetWindowPos( hWnd, NULL, 0, 0, rc.right-rc.left, rc.bottom-rc.top,SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE );
SetWindowPos( hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE );
SystemParametersInfo( SPI_GETWORKAREA, 0, &rcWork, 0 );
GetWindowRect( hWnd, &rc );
if( rc.left < rcWork.left ) rc.left = rcWork.left;
if( rc.top < rcWork.top ) rc.top = rcWork.top;
SetWindowPos( hWnd, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
CDDRAW_INITSTRUCT(ddsd);
ddsd.dwFlags = DDSD_CAPS;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
if( FAILED( lpdd7->CreateSurface( &ddsd, &lpddsprimary, NULL ) ) )
return E_FAIL;
// Create the backbuffer surface
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE;
ddsd.dwWidth = dwWidth;
ddsd.dwHeight = dwHeight;
if( FAILED( hr = lpdd7->CreateSurface( &ddsd, &lpddsback, NULL ) ) )
return E_FAIL;
m_hWnd = hWnd;
UpdateBounds();
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Name : HRESULT CDDraw::SwitchingWindowScreen(HWND hWnd,int Width,int Height,int Bpp)
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::SwitchingWindowScreen(HWND hWnd,int Width,int Height,int Bpp)
{
DestoryCDDraw();
if( m_bWindowed )
{
if(FAILED(CreateWindowedScreen(hWnd,Width,Height)))
return E_FAIL;
DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION;
SetWindowLong( hWnd, GWL_STYLE, dwStyle );
ShowWindow( hWnd, SW_SHOW );
UpdateWindow( hWnd );
}
else
{
DWORD dwStyle = WS_POPUP & ~WS_CAPTION;
SetWindowLong( hWnd, GWL_STYLE, dwStyle );
ShowWindow( hWnd, SW_SHOW );
UpdateWindow( hWnd );
if(FAILED(CreateFullScreen(hWnd,Width,Height,Bpp)))
return E_FAIL;
}
m_bWindowed = !m_bWindowed;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Name : HRESULT CDDraw::DestoryCDDraw()
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DestoryCDDraw()
{
CDDRAW_SAFERELEASE(lpddclipper);
CDDRAW_SAFERELEASE(lpddsback);
CDDRAW_SAFERELEASE(lpddsprimary);
if( lpdd7 )
lpdd7->SetCooperativeLevel( m_hWnd, DDSCL_NORMAL );
CDDRAW_SAFERELEASE(lpdd7);
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Name : HRESULT CDDraw::UpdateBounds()
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::UpdateBounds()
{
if( m_bWindowed )
{
GetClientRect( m_hWnd, &m_rcWindow );
ClientToScreen( m_hWnd, (POINT*)&m_rcWindow );
ClientToScreen( m_hWnd, (POINT*)&m_rcWindow+1 );
}
else
{
SetRect( &m_rcWindow, 0, 0, GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN) );
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Name : UCHAR* CDDraw::DDraw_Lock_Surface(LPDIRECTDRAWSURFACE7 lpdds, int *lpitch)
// Desc : locks the sent surface and returns a pointer to it
/////////////////////////////////////////////////////////////////////////////
UCHAR* CDDraw::DDraw_Lock_Surface(LPDIRECTDRAWSURFACE7 lpdds, int *lpitch)
{
if (!lpdds)
return(NULL);
CDDRAW_INITSTRUCT(ddsd);
lpdds->Lock(NULL,&ddsd,DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR,NULL);
if (lpitch)
*lpitch = ddsd.lPitch;
return((UCHAR *)ddsd.lpSurface);
} // end DDraw_Lock_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : *DDraw_Lock_Primary_Surface
// Desc : locks the priamary surface and returns a pointer to it
/////////////////////////////////////////////////////////////////////////////
UCHAR* CDDraw::DDraw_Lock_Primary_Surface(void)
{
if (primary_buffer)
return(primary_buffer);
CDDRAW_INITSTRUCT(ddsd);
lpddsprimary->Lock(NULL,&ddsd,DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR,NULL);
primary_buffer = (UCHAR *)ddsd.lpSurface;
primary_lpitch = ddsd.lPitch;
return(primary_buffer);
} // end DDraw_Lock_Primary_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : *DDraw_Lock_Back_Surface
// Desc : locks the secondary back surface and returns a pointer to it
/////////////////////////////////////////////////////////////////////////////
UCHAR* CDDraw::DDraw_Lock_Back_Surface(void)
{
if (back_buffer)
return(back_buffer);
CDDRAW_INITSTRUCT(ddsd);
lpddsback->Lock(NULL,&ddsd,DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR,NULL);
back_buffer = (UCHAR *)ddsd.lpSurface;
back_lpitch = ddsd.lPitch;
return(back_buffer);
} // end DDraw_Lock_Back_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Unlock_Surface
// Desc : unlocks a general surface
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DDraw_Unlock_Surface(LPDIRECTDRAWSURFACE7 lpdds)
{
if (!lpdds)
return E_FAIL;
lpdds->Unlock(NULL);
return S_OK;
} // end DDraw_Unlock_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Unlock_Primary_Surface
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DDraw_Unlock_Primary_Surface(void)
{
if (!primary_buffer)
return E_FAIL;
lpddsprimary->Unlock(NULL);
primary_buffer = NULL;
primary_lpitch = 0;
return S_OK;
} // end DDraw_Unlock_Primary_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Unlock_Back_Surface
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DDraw_Unlock_Back_Surface(void)
{
if (!back_buffer)
return E_FAIL;
lpddsback->Unlock(NULL);
back_buffer = NULL;
back_lpitch = 0;
return S_OK;
} // end DDraw_Unlock_Back_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Attach_Clipper
// Desc : creates a clipper from the sent clip list
/////////////////////////////////////////////////////////////////////////////
LPDIRECTDRAWCLIPPER CDDraw::DDraw_Attach_Clipper(LPDIRECTDRAWSURFACE7 lpdds,int num_rects,LPRECT clip_list)
{
int index; // looping var
LPDIRECTDRAWCLIPPER lpddclipper; // pointer to the newly created dd clipper
LPRGNDATA region_data; // pointer to the region data that contains
if (FAILED(lpdd7->CreateClipper(0,&lpddclipper,NULL)))
return(NULL);
region_data = (LPRGNDATA)malloc(sizeof(RGNDATAHEADER)+num_rects*sizeof(RECT));
memcpy(region_data->Buffer, clip_list, sizeof(RECT)*num_rects);
region_data->rdh.dwSize = sizeof(RGNDATAHEADER);
region_data->rdh.iType = RDH_RECTANGLES;
region_data->rdh.nCount = num_rects;
region_data->rdh.nRgnSize = num_rects*sizeof(RECT);
region_data->rdh.rcBound.left = 64000;
region_data->rdh.rcBound.top = 64000;
region_data->rdh.rcBound.right = -64000;
region_data->rdh.rcBound.bottom = -64000;
for (index=0; index<num_rects; index++)
{
if (clip_list[index].left < region_data->rdh.rcBound.left)
region_data->rdh.rcBound.left = clip_list[index].left;
if (clip_list[index].right > region_data->rdh.rcBound.right)
region_data->rdh.rcBound.right = clip_list[index].right;
if (clip_list[index].top < region_data->rdh.rcBound.top)
region_data->rdh.rcBound.top = clip_list[index].top;
if (clip_list[index].bottom > region_data->rdh.rcBound.bottom)
region_data->rdh.rcBound.bottom = clip_list[index].bottom;
} // end for index
if (FAILED(lpddclipper->SetClipList(region_data, 0)))
{
free(region_data);
return(NULL);
} // end if
if (FAILED(lpdds->SetClipper(lpddclipper)))
{
free(region_data);
return(NULL);
} // end if
free(region_data);
return(lpddclipper);
} // end DDraw_Attach_Clipper
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Wait_For_Vsync
// Desc : waits for a vertical blank to begin
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DDraw_Wait_For_Vsync(void)
{
lpdd7->WaitForVerticalBlank(DDWAITVB_BLOCKBEGIN,0);
return S_OK;
} // end DDraw_Wait_For_Vsync
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Fill_Surface
// Desc : Fill the object Surface with color
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DDraw_Fill_Surface(HWND m_hWnd, LPDIRECTDRAWSURFACE7 lpdds,int color)
{
CDDRAW_INITSTRUCT(ddbltfx);
ddbltfx.dwFillColor = color;
lpdds->Blt(NULL,NULL,NULL,DDBLT_COLORFILL|DDBLT_WAIT,&ddbltfx);
/*
GetWindowRect(m_hWnd,&m_rcWindow);
DWORD dwFrameWidth = GetSystemMetrics( SM_CXSIZEFRAME );
DWORD dwFrameHeight = GetSystemMetrics( SM_CYSIZEFRAME );
DWORD dwCaptionHeight = GetSystemMetrics( SM_CYCAPTION );
m_rcWindow.left = m_rcWindow.left + dwFrameWidth;
m_rcWindow.top = m_rcWindow.top + dwFrameHeight + dwCaptionHeight;
m_rcWindow.right = m_rcWindow.right - dwFrameWidth;
m_rcWindow.bottom = m_rcWindow.bottom - dwFrameHeight;
if(m_bWindowed)
{
lpdds->Blt(NULL,NULL,NULL,DDBLT_COLORFILL|DDBLT_WAIT,&ddbltfx);
}
else
{
lpdds->Blt(NULL,NULL,NULL,DDBLT_COLORFILL|DDBLT_WAIT,&ddbltfx);
}
*/
return S_OK;
} // end DDraw_Fill_Surface
/////////////////////////////////////////////////////////////////////////////
// Name : DDraw_Flip()
// Desc :
/////////////////////////////////////////////////////////////////////////////
HRESULT CDDraw::DDraw_Flip(void)
{
if (primary_buffer || back_buffer)
return E_FAIL;
if (m_bWindowed)
{
while(FAILED(lpddsprimary->Flip(NULL, DDFLIP_WAIT)));
}
else
{
GetWindowRect(m_hWnd,&m_rcWindow);
DWORD dwFrameWidth = GetSystemMetrics( SM_CXSIZEFRAME );
DWORD dwFrameHeight = GetSystemMetrics( SM_CYSIZEFRAME );
DWORD dwCaptionHeight = GetSystemMetrics( SM_CYCAPTION );
m_rcWindow.left = m_rcWindow.left + dwFrameWidth;
m_rcWindow.top = m_rcWindow.top + dwFrameHeight + dwCaptionHeight;
m_rcWindow.right = m_rcWindow.right - dwFrameWidth;
m_rcWindow.bottom = m_rcWindow.bottom - dwFrameHeight;
lpddsprimary->Blt(&m_rcWindow,lpddsback,NULL, DDBLT_WAIT,NULL);
}
DDraw_Fill_Surface(m_hWnd,lpddsback,0);
// CDDRAW_INITSTRUCT(ddbltfx);
// ddbltfx.dwFillColor = 0;
// lpddsback->Blt(NULL,NULL,NULL,DDBLT_COLORFILL|DDBLT_WAIT,&ddbltfx);
return S_OK;
} // end DDraw_Flip
/////////////////////////////////////////////////////////////////////////////
// Name : LPDIRECTDRAWSURFACE7 CDDraw::CreateOffSurface(int Width, int Height, int MemFlag)
// Desc :
/////////////////////////////////////////////////////////////////////////////
LPDIRECTDRAWSURFACE7 CDDraw::CreateOffSurface(int Width, int Height, int MemFlag)
{
LPDIRECTDRAWSURFACE7 lpdds;
CDDRAW_INITSTRUCT(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.dwWidth = Width;
ddsd.dwHeight = Height;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | MemFlag;
if (FAILED(lpdd7->CreateSurface(&ddsd,&lpdds,NULL)))
return (0);
DDCOLORKEY color_key;
color_key.dwColorSpaceLowValue = RGB(0,0,0);
color_key.dwColorSpaceHighValue = RGB(0,0,0);
lpdds->SetColorKey(DDCKEY_SRCBLT, &color_key);
return(lpdds);
}
| 32.431412 | 117 | 0.513456 | [
"object"
] |
d97b48fc963ecd63b3792e617b7093dd70a6dbda | 4,932 | cpp | C++ | tests/data_structures/semistatic_map.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | tests/data_structures/semistatic_map.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | tests/data_structures/semistatic_map.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | // expect-success
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define IN_FRUIT_CPP_FILE
#include <fruit/impl/data_structures/semistatic_map.h>
#include <fruit/impl/data_structures/semistatic_map.templates.h>
#include "../test_macros.h"
#include <vector>
using namespace std;
using namespace fruit::impl;
void test_empty() {
vector<pair<int, std::string>> values{};
SemistaticMap<int, std::string> map(values.begin(), values.size());
Assert(map.find(0) == nullptr);
Assert(map.find(2) == nullptr);
Assert(map.find(5) == nullptr);
}
void test_1_elem() {
vector<pair<int, std::string>> values{{2, "foo"}};
SemistaticMap<int, std::string> map(values.begin(), values.size());
Assert(map.find(0) == nullptr);
Assert(map.find(2) != nullptr);
Assert(map.at(2) == "foo");
Assert(map.find(5) == nullptr);
}
void test_1_inserted_elem() {
vector<pair<int, std::string>> values{};
SemistaticMap<int, std::string> old_map(values.begin(), values.size());
vector<pair<int, std::string>> new_values{{2, "bar"}};
SemistaticMap<int, std::string> map(old_map, std::move(new_values));
Assert(map.find(0) == nullptr);
Assert(map.find(2) != nullptr);
Assert(map.at(2) == "bar");
Assert(map.find(5) == nullptr);
}
void test_3_elem() {
vector<pair<int, std::string>> values{{1, "foo"}, {3, "bar"}, {4, "baz"}};
SemistaticMap<int, std::string> map(values.begin(), values.size());
Assert(map.find(0) == nullptr);
Assert(map.find(1) != nullptr);
Assert(map.at(1) == "foo");
Assert(map.find(2) == nullptr);
Assert(map.find(3) != nullptr);
Assert(map.at(3) == "bar");
Assert(map.find(4) != nullptr);
Assert(map.at(4) == "baz");
Assert(map.find(5) == nullptr);
}
void test_1_elem_2_inserted() {
vector<pair<int, std::string>> values{{1, "foo"}};
SemistaticMap<int, std::string> old_map(values.begin(), values.size());
vector<pair<int, std::string>> new_values{{3, "bar"}, {4, "baz"}};
SemistaticMap<int, std::string> map(old_map, std::move(new_values));
Assert(map.find(0) == nullptr);
Assert(map.find(1) != nullptr);
Assert(map.at(1) == "foo");
Assert(map.find(2) == nullptr);
Assert(map.find(3) != nullptr);
Assert(map.at(3) == "bar");
Assert(map.find(4) != nullptr);
Assert(map.at(4) == "baz");
Assert(map.find(5) == nullptr);
}
void test_3_elem_3_inserted() {
vector<pair<int, std::string>> values{{1, "1"}, {3, "3"}, {5, "5"}};
SemistaticMap<int, std::string> old_map(values.begin(), values.size());
vector<pair<int, std::string>> new_values{{2, "2"}, {4, "4"}, {16, "16"}};
SemistaticMap<int, std::string> map(old_map, std::move(new_values));
Assert(map.find(0) == nullptr);
Assert(map.find(1) != nullptr);
Assert(map.at(1) == "1");
Assert(map.find(2) != nullptr);
Assert(map.at(2) == "2");
Assert(map.find(3) != nullptr);
Assert(map.at(3) == "3");
Assert(map.find(4) != nullptr);
Assert(map.at(4) == "4");
Assert(map.find(5) != nullptr);
Assert(map.at(5) == "5");
Assert(map.find(6) == nullptr);
Assert(map.find(16) != nullptr);
Assert(map.at(16) == "16");
}
void test_move_constructor() {
vector<pair<int, std::string>> values{{1, "foo"}, {3, "bar"}, {4, "baz"}};
SemistaticMap<int, std::string> map1(values.begin(), values.size());
SemistaticMap<int, std::string> map = std::move(map1);
Assert(map.find(0) == nullptr);
Assert(map.find(1) != nullptr);
Assert(map.at(1) == "foo");
Assert(map.find(2) == nullptr);
Assert(map.find(3) != nullptr);
Assert(map.at(3) == "bar");
Assert(map.find(4) != nullptr);
Assert(map.at(4) == "baz");
Assert(map.find(5) == nullptr);
}
void test_move_assignment() {
vector<pair<int, std::string>> values{{1, "foo"}, {3, "bar"}, {4, "baz"}};
SemistaticMap<int, std::string> map1(values.begin(), values.size());
SemistaticMap<int, std::string> map;
map = std::move(map1);
Assert(map.find(0) == nullptr);
Assert(map.find(1) != nullptr);
Assert(map.at(1) == "foo");
Assert(map.find(2) == nullptr);
Assert(map.find(3) != nullptr);
Assert(map.at(3) == "bar");
Assert(map.find(4) != nullptr);
Assert(map.at(4) == "baz");
Assert(map.find(5) == nullptr);
}
int main() {
test_empty();
test_1_elem();
test_1_inserted_elem();
test_3_elem();
test_1_elem_2_inserted();
test_3_elem_3_inserted();
test_move_constructor();
test_move_assignment();
return 0;
}
| 32.447368 | 76 | 0.642539 | [
"vector"
] |
d97d5670c984f9874a81edeab1548899dfa8ceee | 17,977 | cc | C++ | anc/stim_src_v1.3/src/circuit/circuit.test.cc | Strilanc/stim-paper | be41a2087f8adeff25ce28b67d3e3fa6d097aa36 | [
"Apache-2.0"
] | 1 | 2021-09-18T00:56:25.000Z | 2021-09-18T00:56:25.000Z | anc/stim_src_v1.3/src/circuit/circuit.test.cc | Strilanc/stim-paper | be41a2087f8adeff25ce28b67d3e3fa6d097aa36 | [
"Apache-2.0"
] | 4 | 2021-03-08T16:31:24.000Z | 2021-05-11T18:25:06.000Z | anc/stim_src_v1.3/src/circuit/circuit.test.cc | Strilanc/stim-paper | be41a2087f8adeff25ce28b67d3e3fa6d097aa36 | [
"Apache-2.0"
] | null | null | null | // 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
//
// 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 "circuit.test.h"
#include <gtest/gtest.h>
OpDat::OpDat(uint32_t target) : targets({target}) {
}
OpDat::OpDat(std::vector<uint32_t> targets) : targets(std::move(targets)) {
}
OpDat OpDat::flipped(size_t target) {
return OpDat(target | TARGET_INVERTED_BIT);
}
OpDat::operator OperationData() {
return {0, targets};
}
TEST(circuit, from_text) {
Circuit expected;
const auto &f = Circuit::from_text;
ASSERT_EQ(f("# not an operation"), expected);
expected.clear();
expected.append_op("H", {0});
ASSERT_EQ(f("H 0"), expected);
ASSERT_EQ(f("h 0"), expected);
ASSERT_EQ(f("H 0 "), expected);
ASSERT_EQ(f(" H 0 "), expected);
ASSERT_EQ(f("\tH 0\t\t"), expected);
ASSERT_EQ(f("H 0 # comment"), expected);
expected.clear();
expected.append_op("H", {23});
ASSERT_EQ(f("H 23"), expected);
expected.clear();
expected.append_op("DEPOLARIZE1", {4, 5}, 0.125);
ASSERT_EQ(f("DEPOLARIZE1(0.125) 4 5 # comment"), expected);
expected.clear();
expected.append_op("ZCX", {5, 6});
ASSERT_EQ(f(" \t Cnot 5 6 # comment "), expected);
ASSERT_THROW({ f("H a"); }, std::out_of_range);
ASSERT_THROW({ f("H(1)"); }, std::out_of_range);
ASSERT_THROW({ f("X_ERROR 1"); }, std::out_of_range);
ASSERT_THROW({ f("H 9999999999999999999999999999999999999999999"); }, std::out_of_range);
ASSERT_THROW({ f("H -1"); }, std::out_of_range);
ASSERT_THROW({ f("CNOT 0 a"); }, std::out_of_range);
ASSERT_THROW({ f("CNOT 0 99999999999999999999999999999999"); }, std::out_of_range);
ASSERT_THROW({ f("CNOT 0 -1"); }, std::out_of_range);
ASSERT_THROW({ f("DETECTOR 1 2"); }, std::out_of_range);
ASSERT_THROW({ f("CX 1 1"); }, std::out_of_range);
ASSERT_THROW({ f("SWAP 1 1"); }, std::out_of_range);
ASSERT_THROW({ f("DEPOLARIZE2(1) 1 1"); }, std::out_of_range);
ASSERT_THROW({ f("DETEstdCTOR rec[-1]"); }, std::out_of_range);
ASSERT_THROW({ f("DETECTOR rec[0]"); }, std::out_of_range);
ASSERT_THROW({ f("DETECTOR rec[1]"); }, std::out_of_range);
ASSERT_THROW({ f("DETECTOR rec[-999999999999]"); }, std::out_of_range);
ASSERT_THROW({ f("DETECTOR(2) rec[-1]"); }, std::out_of_range);
ASSERT_THROW({ f("OBSERVABLE_INCLUDE rec[-1]"); }, std::out_of_range);
ASSERT_THROW({ f("OBSERVABLE_INCLUDE(-1) rec[-1]"); }, std::out_of_range);
ASSERT_THROW({ f("CORRELATED_ERROR(1) B1"); }, std::out_of_range);
ASSERT_THROW({ f("CORRELATED_ERROR(1) X 1"); }, std::out_of_range);
ASSERT_THROW({ f("CORRELATED_ERROR(1) X\n"); }, std::out_of_range);
ASSERT_THROW({ f("CORRELATED_ERROR(1) 1"); }, std::out_of_range);
ASSERT_THROW({ f("ELSE_CORRELATED_ERROR(1) 1 2"); }, std::out_of_range);
ASSERT_THROW({ f("CORRELATED_ERROR(1) 1 2"); }, std::out_of_range);
ASSERT_THROW({ f("CORRELATED_ERROR(1) A"); }, std::out_of_range);
ASSERT_THROW({ f("CNOT 0\nCNOT 1"); }, std::out_of_range);
expected.clear();
ASSERT_EQ(f(""), expected);
ASSERT_EQ(f("# Comment\n\n\n# More"), expected);
expected.clear();
expected.append_op("H_XZ", {0});
ASSERT_EQ(f("H 0"), expected);
expected.clear();
expected.append_op("H_XZ", {0, 1});
ASSERT_EQ(f("H 0 \n H 1"), expected);
expected.clear();
expected.append_op("H_XZ", {1});
ASSERT_EQ(f("H 1"), expected);
expected.clear();
expected.append_op("H", {0});
expected.append_op("ZCX", {0, 1});
ASSERT_EQ(
f("# EPR\n"
"H 0\n"
"CNOT 0 1"),
expected);
expected.clear();
expected.append_op("M", {0, 0 | TARGET_INVERTED_BIT, 1, 1 | TARGET_INVERTED_BIT});
ASSERT_EQ(f("M 0 !0 1 !1"), expected);
// Measurement fusion.
expected.clear();
expected.append_op("H", {0});
expected.append_op("M", {0, 1, 2});
expected.append_op("SWAP", {0, 1});
expected.append_op("M", {0, 10});
ASSERT_EQ(
f(R"CIRCUIT(
H 0
M 0
M 1
M 2
SWAP 0 1
M 0
M 10
)CIRCUIT"),
expected);
expected.clear();
expected.append_op("X", {0});
expected += Circuit::from_text("Y 1 2") * 2;
ASSERT_EQ(
f(R"CIRCUIT(
X 0
REPEAT 2 {
Y 1
Y 2 #####"
} #####"
)CIRCUIT"),
expected);
expected.clear();
expected.append_op("DETECTOR", {5 | TARGET_RECORD_BIT});
ASSERT_EQ(f("DETECTOR rec[-5]"), expected);
expected.clear();
expected.append_op("DETECTOR", {6 | TARGET_RECORD_BIT});
ASSERT_EQ(f("DETECTOR rec[-6]"), expected);
Circuit parsed =
f("M 0\n"
"REPEAT 5 {\n"
" M 1 2\n"
" M 3\n"
"} #####");
ASSERT_EQ(parsed.operations.size(), 2);
ASSERT_EQ(parsed.blocks.size(), 1);
ASSERT_EQ(parsed.blocks[0].operations.size(), 1);
ASSERT_EQ(parsed.blocks[0].operations[0].target_data.targets.size(), 3);
expected.clear();
expected.append_op(
"CORRELATED_ERROR",
{90 | TARGET_PAULI_X_BIT, 91 | TARGET_PAULI_X_BIT | TARGET_PAULI_Z_BIT, 92 | TARGET_PAULI_Z_BIT,
93 | TARGET_PAULI_X_BIT},
0.125);
ASSERT_EQ(
f(R"circuit(
CORRELATED_ERROR(0.125) X90 Y91 Z92 X93
)circuit"),
expected);
}
TEST(circuit, append_circuit) {
Circuit c1;
c1.append_op("X", {0, 1});
c1.append_op("M", {0, 1, 2, 4});
Circuit c2;
c2.append_op("M", {7});
Circuit expected;
expected.append_op("X", {0, 1});
expected.append_op("M", {0, 1, 2, 4});
expected.append_op("M", {7});
Circuit actual = c1;
actual += c2;
ASSERT_EQ(actual.operations.size(), 3);
actual = Circuit::from_text(actual.str().data());
ASSERT_EQ(actual.operations.size(), 2);
ASSERT_EQ(actual, expected);
actual *= 4;
ASSERT_EQ(actual.str(), R"CIRCUIT(REPEAT 4 {
X 0 1
M 0 1 2 4 7
})CIRCUIT");
}
TEST(circuit, append_op_fuse) {
Circuit expected;
Circuit actual;
expected.append_op("H", {1, 2, 3});
actual.append_op("H", {1}, 0);
actual.append_op("H", {2, 3}, 0);
ASSERT_EQ(actual, expected);
actual.append_op("R", {0}, 0);
expected.append_op("R", {0});
ASSERT_EQ(actual, expected);
actual.append_op("DETECTOR", {0, 0}, 0);
actual.append_op("DETECTOR", {1, 1}, 0);
expected.append_op("DETECTOR", {0, 0});
expected.append_op("DETECTOR", {1, 1});
ASSERT_EQ(actual, expected);
actual.append_op("M", {0, 1}, 0);
actual.append_op("M", {2, 3}, 0);
expected.append_op("M", {0, 1, 2, 3});
ASSERT_EQ(actual, expected);
ASSERT_THROW({ actual.append_op("CNOT", {0}); }, std::out_of_range);
ASSERT_THROW({ actual.append_op("X", {0}, 0.5); }, std::out_of_range);
}
TEST(circuit, str) {
Circuit c;
c.append_op("tick", {});
c.append_op("CNOT", {2, 3});
c.append_op("CNOT", {5 | TARGET_RECORD_BIT, 3});
c.append_op("M", {1, 3, 2});
c.append_op("DETECTOR", {7 | TARGET_RECORD_BIT});
c.append_op("OBSERVABLE_INCLUDE", {11 | TARGET_RECORD_BIT, 1 | TARGET_RECORD_BIT}, 17);
c.append_op("X_ERROR", {19}, 0.5);
c.append_op(
"CORRELATED_ERROR",
{
23 | TARGET_PAULI_X_BIT,
27 | TARGET_PAULI_Z_BIT,
29 | TARGET_PAULI_X_BIT | TARGET_PAULI_Z_BIT,
},
0.25);
ASSERT_EQ(c.str(), R"circuit(TICK
CX 2 3 rec[-5] 3
M 1 3 2
DETECTOR rec[-7]
OBSERVABLE_INCLUDE(17) rec[-11] rec[-1]
X_ERROR(0.5) 19
E(0.25) X23 Z27 Y29)circuit");
}
TEST(circuit, append_op_validation) {
Circuit c;
ASSERT_THROW({ c.append_op("CNOT", {0}); }, std::out_of_range);
c.append_op("CNOT", {0, 1});
ASSERT_THROW({ c.append_op("REPEAT", {100}); }, std::out_of_range);
ASSERT_THROW({ c.append_op("X", {0 | TARGET_PAULI_X_BIT}); }, std::out_of_range);
ASSERT_THROW({ c.append_op("X", {0 | TARGET_PAULI_Z_BIT}); }, std::out_of_range);
ASSERT_THROW({ c.append_op("X", {0 | TARGET_INVERTED_BIT}); }, std::out_of_range);
ASSERT_THROW({ c.append_op("X", {0}, 0.5); }, std::out_of_range);
ASSERT_THROW({ c.append_op("M", {0 | TARGET_PAULI_X_BIT}); }, std::out_of_range);
ASSERT_THROW({ c.append_op("M", {0 | TARGET_PAULI_Z_BIT}); }, std::out_of_range);
c.append_op("M", {0 | TARGET_INVERTED_BIT});
ASSERT_THROW({ c.append_op("M", {0}, 0.5); }, std::out_of_range);
c.append_op("CORRELATED_ERROR", {0 | TARGET_PAULI_X_BIT});
c.append_op("CORRELATED_ERROR", {0 | TARGET_PAULI_Z_BIT});
ASSERT_THROW(
{ c.append_op("CORRELATED_ERROR", {0 | TARGET_PAULI_X_BIT | TARGET_INVERTED_BIT}); }, std::out_of_range);
c.append_op("X_ERROR", {0}, 0.5);
ASSERT_THROW({ c.append_op("CNOT", {0, 0}); }, std::out_of_range);
}
TEST(circuit, classical_controls) {
ASSERT_THROW(
{
Circuit::from_text(R"circuit(
M 0
XCX rec[-1] 1
)circuit");
},
std::out_of_range);
Circuit expected;
expected.append_op("CX", {0, 1, 1 | TARGET_RECORD_BIT, 1});
expected.append_op("CY", {2 | TARGET_RECORD_BIT, 1});
expected.append_op("CZ", {4 | TARGET_RECORD_BIT, 1});
ASSERT_EQ(
Circuit::from_text(R"circuit(ZCX 0 1
ZCX rec[-1] 1
ZCY rec[-2] 1
ZCZ rec[-4] 1)circuit"),
expected);
}
TEST(circuit, for_each_operation) {
Circuit c;
c.append_from_text(R"CIRCUIT(
H 0
M 0 1
REPEAT 2 {
X 1
REPEAT 3 {
Y 2
}
}
)CIRCUIT");
Circuit flat;
auto f = [&](const char *gate, const std::vector<uint32_t> &targets) {
flat.append_operation({&GATE_DATA.at(gate), {0, flat.jag_targets.take_copy(targets)}});
};
f("H", {0});
f("M", {0, 1});
f("X", {1});
f("Y", {2});
f("Y", {2});
f("Y", {2});
f("X", {1});
f("Y", {2});
f("Y", {2});
f("Y", {2});
std::vector<Operation> ops;
c.for_each_operation([&](const Operation &op) {
ops.push_back(op);
});
ASSERT_EQ(ops, flat.operations);
}
TEST(circuit, for_each_operation_reverse) {
Circuit c;
c.append_from_text(R"CIRCUIT(
H 0
M 0 1
REPEAT 2 {
X 1
REPEAT 3 {
Y 2
}
}
)CIRCUIT");
Circuit flat;
auto f = [&](const char *gate, const std::vector<uint32_t> &targets) {
flat.append_operation({&GATE_DATA.at(gate), {0, flat.jag_targets.take_copy(targets)}});
};
f("Y", {2});
f("Y", {2});
f("Y", {2});
f("X", {1});
f("Y", {2});
f("Y", {2});
f("Y", {2});
f("X", {1});
f("M", {0, 1});
f("H", {0});
std::vector<Operation> ops;
c.for_each_operation_reverse([&](const Operation &op) {
ops.push_back(op);
});
ASSERT_EQ(ops, flat.operations);
}
TEST(circuit, count_qubits) {
ASSERT_EQ(Circuit().count_qubits(), 0);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
H 0
M 0 1
REPEAT 2 {
X 1
REPEAT 3 {
Y 2
M 2
}
}
)CIRCUIT")
.count_qubits(),
3);
// Ensure not unrolling to compute.
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
H 0
M 0 1
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
X 1
REPEAT 999999 {
Y 2
M 2
}
}
}
}
}
)CIRCUIT")
.count_qubits(),
3);
}
TEST(circuit, count_detectors_and_observables) {
ASSERT_EQ(Circuit().count_detectors_and_observables(), 0);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
M 0 1 2
DETECTOR rec[-1]
OBSERVABLE_INCLUDE(5) rec[-1]
)CIRCUIT")
.count_detectors_and_observables(),
2);
// Ensure not unrolling to compute.
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
M 0 1
REPEAT 1000 {
REPEAT 1000 {
REPEAT 1000 {
REPEAT 1000 {
DETECTOR rec[-1]
}
}
}
}
)CIRCUIT")
.count_detectors_and_observables(),
1000000000000ULL);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
M 0 1
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
DETECTOR rec[-1]
}
}
}
}
}
}
}
}
}
}
}
}
}
)CIRCUIT")
.count_detectors_and_observables(),
UINT64_MAX);
}
TEST(circuit, max_lookback) {
ASSERT_EQ(Circuit().max_lookback(), 0);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
M 0 1 2 3 4 5 6
)CIRCUIT")
.max_lookback(),
0);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
M 0 1 2 3 4 5 6
REPEAT 2 {
CNOT rec[-4] 0
REPEAT 3 {
CNOT rec[-1] 0
}
}
)CIRCUIT")
.max_lookback(),
4);
// Ensure not unrolling to compute.
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
M 0 1 2 3 4 5
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
CNOT rec[-5] 0
}
}
}
}
}
)CIRCUIT")
.max_lookback(),
5);
}
TEST(circuit, count_measurements) {
ASSERT_EQ(Circuit().count_measurements(), 0);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
H 0
M 0 1
REPEAT 2 {
X 1
REPEAT 3 {
Y 2
M 2
}
}
)CIRCUIT")
.count_measurements(),
8);
// Ensure not unrolling to compute.
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
M 0
}
}
}
)CIRCUIT")
.count_measurements(),
999999ULL * 999999ULL * 999999ULL);
ASSERT_EQ(
Circuit::from_text(R"CIRCUIT(
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
REPEAT 999999 {
M 0
}
}
}
}
}
}
}
}
}
)CIRCUIT")
.count_measurements(),
UINT64_MAX);
}
TEST(circuit, preserves_repetition_blocks) {
Circuit c = Circuit::from_text(R"CIRCUIT(
H 0
M 0 1
REPEAT 2 {
X 1
REPEAT 3 {
Y 2
M 2
X 0
}
}
)CIRCUIT");
ASSERT_EQ(c.operations.size(), 3);
ASSERT_EQ(c.blocks.size(), 1);
ASSERT_EQ(c.blocks[0].operations.size(), 2);
ASSERT_EQ(c.blocks[0].blocks.size(), 1);
ASSERT_EQ(c.blocks[0].blocks[0].operations.size(), 3);
ASSERT_EQ(c.blocks[0].blocks[0].blocks.size(), 0);
}
TEST(circuit, multiplication_repeats) {
Circuit c = Circuit::from_text(R"CIRCUIT(
H 0
M 0 1
)CIRCUIT");
ASSERT_EQ((c * 2).str(), R"CIRCUIT(REPEAT 2 {
H 0
M 0 1
})CIRCUIT");
ASSERT_EQ(c * 0, Circuit());
ASSERT_EQ(c * 1, c);
Circuit copy = c;
c *= 1;
ASSERT_EQ(c, copy);
c *= 0;
ASSERT_EQ(c, Circuit());
}
TEST(circuit, self_addition) {
Circuit c = Circuit::from_text(R"CIRCUIT(
X 0
)CIRCUIT");
c += c;
ASSERT_EQ(c.operations.size(), 2);
ASSERT_EQ(c.blocks.size(), 0);
ASSERT_EQ(c.operations[0], c.operations[1]);
c = Circuit::from_text(R"CIRCUIT(
X 0
REPEAT 2 {
Y 0
}
)CIRCUIT");
c += c;
ASSERT_EQ(c.operations.size(), 4);
ASSERT_EQ(c.blocks.size(), 1);
ASSERT_EQ(c.operations[0], c.operations[2]);
ASSERT_EQ(c.operations[1], c.operations[3]);
}
TEST(circuit, addition_shares_blocks) {
Circuit c1 = Circuit::from_text(R"CIRCUIT(
X 0
REPEAT 2 {
X 1
}
)CIRCUIT");
Circuit c2 = Circuit::from_text(R"CIRCUIT(
X 2
REPEAT 2 {
X 3
}
)CIRCUIT");
Circuit c3 = Circuit::from_text(R"CIRCUIT(
X 0
REPEAT 2 {
X 1
}
X 2
REPEAT 2 {
X 3
}
)CIRCUIT");
ASSERT_EQ(c1 + c2, c3);
c1 += c2;
ASSERT_EQ(c1, c3);
}
| 26.87145 | 113 | 0.522723 | [
"vector"
] |
d97f823f8a69f96525a052f8e8446925ad3772de | 7,638 | cpp | C++ | gas.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 57 | 2015-02-16T06:43:24.000Z | 2022-03-16T06:21:36.000Z | gas.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 4 | 2016-03-08T09:51:09.000Z | 2021-03-29T10:18:55.000Z | gas.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 27 | 2015-03-28T19:55:34.000Z | 2022-01-09T15:03:15.000Z |
#include "opencv2/ml.hpp"
using namespace std;
using namespace cv;
class CV_EXPORTS NeuralGas : public CvStatModel {
typedef float GasType;
typedef vector<GasType> GasVec;
public:
struct CV_EXPORTS GasNode {
int id;
int rank;
GasVec ref_vector;
double distance;
};
//NeuralGas();
virtual ~NeuralGas();
// values taken from http://de.wikipedia.org/wiki/Neural_Gas
NeuralGas( const Mat _distr, int _total_nodes, int _max_iterations, float _lambda0=1, float lambdaT=0.01f, float _epsilon0=.5f, float _epsilonT=0.001f );
bool init();
Mat cluster();
bool train();
bool train_auto();
void clear();
void get_nodes(std::vector<GasNode>& nodes) const;
int get_iteration() const;
int get_max_iterations() const;
GasNode get_bmu() const;
GasNode get_smu() const;
GasNode get_wmu() const;
//Scalar get_input() const;
int get_total_nodes() const;
// The networks settings are public so that should be changed dynamically depending the problem.
float lambda0;
float lambdaT;
float epsilon0;
float epsilonT;
protected:
std::vector<GasNode> nodes;
GasNode bmu;
GasNode smu;
GasNode wmu;
int total_nodes;
int iteration, max_iterations;
// Scalar input;
Mat distribution;
RNG rng;
private:
// Static method used for sorting the nodes.
static bool Compare( const GasNode & node1, const GasNode & node2 ) {
return ( node1.distance < node2.distance );
}
};
//---8<-------------------------------------------------------------------------------------------------
//NeuralGas::NeuralGas() {
//}
NeuralGas::NeuralGas( Mat _distr, int _total_nodes, int _max_iterations, float _lambda0, float _lambdaT, float _epsilon0, float _epsilonT ) {
default_model_name = "neural_gas";
distribution = _distr;
total_nodes = _total_nodes;
max_iterations = _max_iterations;
iteration = 0;
lambda0 = _lambda0 ? _lambda0 : _max_iterations/2;
lambdaT = _lambdaT;
epsilon0 = _epsilon0;
epsilonT = _epsilonT;
// input = DBL_MAX;
init();
}
NeuralGas::~NeuralGas() {
clear( );
}
bool NeuralGas::init() {
bool ok = true;
int x = 0;
int y = 0;
// Create nodes.
for( int i=0; i<total_nodes; i++ ) {
NeuralGas::GasNode node;
//x = rng.next() % (distribution.cols - 1);
//y = rng.next() % (distribution.rows - 1);
y = rng.next() % (distribution.rows - 1);
GasVec tmp_vector( distribution.row(y) );
node.id = i;
node.rank = 0;
node.ref_vector = tmp_vector;
node.distance = 0.0;
nodes.push_back( node );
}
return ok;
}
bool NeuralGas::train_auto() {
while( iteration < max_iterations ) {
if( train() == false )
return false;
}
return true;
}
// bool NeuralGas::train( Scalar _input ) {
bool NeuralGas::train() {
//if( _input[0] != DBL_MAX ) {
// input = _input;
//} else {
// peak random
//int x = rng.next() % (distribution.cols - 1);
int y = rng.next() % (distribution.rows - 1);
// input = Scalar::all( distribution.at<float>(y,x) );
GasVec input = distribution.row(y);
//}
// Calculate the distance of each node`s reference vector from the projected input vector.
double temp = 0.0;
double val = 0.0;
for( int i=0; i<total_nodes; i++ ) {
NeuralGas::GasNode & curr = nodes.at( i );
curr.distance = 0.0;
GasVec & ref_vector = curr.ref_vector;
for( size_t x=0; x<ref_vector.size(); x++ ) {
val = input[x] - ref_vector[x];
//temp += pow( val, 2.0 );
temp += val * val;
}
curr.distance = sqrt( temp );
temp = 0.0;
val = 0.0;
}
//Sort the nodes based on their distance.
std::sort( nodes.begin(), nodes.end(), Compare);
//Fetch the bmu/smu/wmu.
bmu = nodes.at( 0 );
smu = nodes.at( 1 );
wmu = nodes.at( total_nodes - 1 );
// Adapt the nodes.
double epsilon_t = epsilon0 * pow( ( epsilonT / epsilon0 ), (float)iteration/max_iterations );
double sqr_sigma = lambda0 * pow( ( lambdaT / lambda0 ), (float)iteration/max_iterations );
for( int i=0; i<total_nodes; i++ ) {
NeuralGas::GasNode & curr = nodes.at( i );
curr.rank = -i;
double h = exp( ((double)curr.rank) / sqr_sigma );
GasVec & ref_vector = curr.ref_vector;
for(size_t x=0; x<ref_vector.size(); x++){
double delta = (input[x] - ref_vector[x]) * h * epsilon_t;
ref_vector[x] += delta;
}
}
iteration++;
return true;
}
Mat NeuralGas::cluster() {
Mat g;//(0,nodes[0].ref_vector.size(),CV_32F);
for ( size_t n=0; n<nodes.size(); n++ ) {
for ( size_t v=0; v<nodes[n].ref_vector.size(); v++ ) {
g.push_back(nodes[n].ref_vector[v]);
}
}
return g.reshape(1,nodes.size());
}
void NeuralGas::clear() {
nodes.clear();
distribution.release();
}
void NeuralGas::get_nodes(std::vector<GasNode>& _nodes) const {
_nodes = nodes;
}
int NeuralGas::get_iteration() const {
return iteration;
}
int NeuralGas::get_max_iterations() const {
return max_iterations;
}
NeuralGas::GasNode NeuralGas::get_bmu() const {
return bmu;
}
NeuralGas::GasNode NeuralGas::get_smu() const {
return smu;
}
NeuralGas::GasNode NeuralGas::get_wmu() const {
return wmu;
}
//Scalar NeuralGas::get_input() const {
// return input;
//}
int NeuralGas::get_total_nodes() const {
return total_nodes;
}
//---8<-------------------------------------------------------------------------------------------------
#include "opencv2/highgui.hpp"
#include "time.h"
Mat draw(const Mat& dist) {
Mat img(200,200,CV_8UC3);
for ( int i=0; i<dist.rows; i++ ) {
circle(img,Point2f(dist.at<float>(i,0),dist.at<float>(i,1)),2,Scalar(255),2);
}
return img;
}
int main()
{
// whaa, having an empty constructor is probably a bad idea
Mat dist(100,2,CV_32F);
time_t now;
time(&now);
RNG rng(now);
rng.fill(dist, RNG::UNIFORM,Scalar(),Scalar::all(200));
NeuralGas gas(dist,9,200);
imshow("pre",draw(dist));
waitKey();
for ( int i=0; i<200; i++ ) {
if (! gas.train() )
break;
Mat dist2 = gas.cluster();
imshow("post",draw(dist2));
waitKey(40);
}
// so far, so well. and now ?
// what do i train it on ?
// shouldn't ther be some kind of 'prediction' as well ?
waitKey();
return 0;
}
| 26.337931 | 162 | 0.501047 | [
"vector"
] |
d984063a1c34c96109b5483108470fa58e398965 | 808 | cpp | C++ | connectors/w3dscene.cpp | snejanochka/RCA | a75df3747ee4e1a8996701be9262decc6c3bc9b2 | [
"Apache-2.0"
] | null | null | null | connectors/w3dscene.cpp | snejanochka/RCA | a75df3747ee4e1a8996701be9262decc6c3bc9b2 | [
"Apache-2.0"
] | 1 | 2018-11-21T14:32:12.000Z | 2018-11-21T14:32:12.000Z | connectors/w3dscene.cpp | snejanochka/RCA_snejana | a75df3747ee4e1a8996701be9262decc6c3bc9b2 | [
"Apache-2.0"
] | null | null | null | #include "connectors/w3dscene.h"
//при инициализации подключается к 3d scene
W3dscene::W3dscene(){
connection = false;
}
W3dscene::~W3dscene(){
}
// 3Dscene is disconnected
void W3dscene::sockDisc(){
qDebug()<<"Disconnect";
socket->deleteLater();
connection = false;
}
void W3dscene::sendto3dscene(QByteArray msg){
msg.prepend("{");
msg.append("}");
socket->write(msg);
qDebug()<<"sent JSON to 3dscene: "<<msg; //sent JSON to 3dscene, soket1 from class w3dscene
}
W3dscene::W3dscene(int port){
qDebug()<<"Connect to 3DScene";
socket = new QTcpSocket(this);
Port = port;
connect(socket, &QTcpSocket::disconnected, this, &W3dscene::sockDisc);
socket->connectToHost("127.0.0.1", 6666); //connect to 3Dscene
connection = true;
}
| 23.085714 | 95 | 0.649752 | [
"3d"
] |
d9842e2058fe29934a3ebe932042e2774ea43b29 | 16,162 | cc | C++ | chromium/chrome/browser/chromeos/resource_reporter/resource_reporter.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/chromeos/resource_reporter/resource_reporter.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/chromeos/resource_reporter/resource_reporter.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/resource_reporter/resource_reporter.h"
#include <cstdint>
#include <queue>
#include <utility>
#include "base/bind.h"
#include "base/rand_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/task_management/task_manager_interface.h"
#include "components/rappor/rappor_service.h"
#include "content/public/browser/browser_thread.h"
namespace chromeos {
namespace {
#define GET_ENUM_VAL(enum_entry) static_cast<int>(enum_entry)
// The task manager refresh interval, currently at 1 minute.
const int64_t kRefreshIntervalSeconds = 60;
// Various memory usage sizes in bytes.
const int64_t kMemory1GB = 1024 * 1024 * 1024;
const int64_t kMemory800MB = 800 * 1024 * 1024;
const int64_t kMemory600MB = 600 * 1024 * 1024;
const int64_t kMemory400MB = 400 * 1024 * 1024;
const int64_t kMemory200MB = 200 * 1024 * 1024;
// The name of the Rappor metric to report the CPU usage.
const char kCpuRapporMetric[] = "ResourceReporter.Cpu";
// The name of the Rappor metric to report the memory usage.
const char kMemoryRapporMetric[] = "ResourceReporter.Memory";
// The name of the string field of the Rappor metrics in which we'll record the
// task's Rappor sample name.
const char kRapporTaskStringField[] = "task";
// The name of the flags field of the Rappor metrics in which we'll store the
// priority of the process on which the task is running.
const char kRapporPriorityFlagsField[] = "priority";
// The name of the flags field of the CPU usage Rappor metrics in which we'll
// record the number of cores in the current system.
const char kRapporNumCoresRangeFlagsField[] = "num_cores_range";
// The name of the flags field of the Rappor metrics in which we'll store the
// CPU / memory usage ranges.
const char kRapporUsageRangeFlagsField[] = "usage_range";
// Currently set to be one day.
const int kMinimumTimeBetweenReportsInMs = 1 * 24 * 60 * 60 * 1000;
// A functor to sort the TaskRecords by their |cpu|.
struct TaskRecordCpuLessThan {
bool operator()(ResourceReporter::TaskRecord* const& lhs,
ResourceReporter::TaskRecord* const& rhs) const {
if (lhs->cpu_percent == rhs->cpu_percent)
return lhs->id < rhs->id;
return lhs->cpu_percent < rhs->cpu_percent;
}
};
// A functor to sort the TaskRecords by their |memory|.
struct TaskRecordMemoryLessThan {
bool operator()(ResourceReporter::TaskRecord* const& lhs,
ResourceReporter::TaskRecord* const& rhs) const {
if (lhs->memory_bytes == rhs->memory_bytes)
return lhs->id < rhs->id;
return lhs->memory_bytes < rhs->memory_bytes;
}
};
} // namespace
ResourceReporter::TaskRecord::TaskRecord(task_management::TaskId task_id)
: id(task_id), cpu_percent(0.0), memory_bytes(0), is_background(false) {
}
ResourceReporter::TaskRecord::TaskRecord(task_management::TaskId the_id,
const std::string& task_name,
double cpu_percent,
int64_t memory_bytes,
bool background)
: id(the_id),
task_name_for_rappor(task_name),
cpu_percent(cpu_percent),
memory_bytes(memory_bytes),
is_background(background) {
}
ResourceReporter::~ResourceReporter() {
}
// static
ResourceReporter* ResourceReporter::GetInstance() {
return base::Singleton<ResourceReporter>::get();
}
void ResourceReporter::StartMonitoring() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (is_monitoring_)
return;
is_monitoring_ = true;
task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this);
memory_pressure_listener_.reset(new base::MemoryPressureListener(
base::Bind(&ResourceReporter::OnMemoryPressure, base::Unretained(this))));
}
void ResourceReporter::StopMonitoring() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!is_monitoring_)
return;
is_monitoring_ = false;
memory_pressure_listener_.reset();
task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(this);
}
void ResourceReporter::OnTaskAdded(task_management::TaskId id) {
// Ignore this event.
}
void ResourceReporter::OnTaskToBeRemoved(task_management::TaskId id) {
auto it = task_records_.find(id);
if (it == task_records_.end())
return;
// Must be erased from the sorted set first.
// Note: this could mean that the sorted records are now less than
// |kTopConsumerCount| with other records in |task_records_| that can be
// added now. That's ok, we ignore this case.
auto cpu_it = std::find(task_records_by_cpu_.begin(),
task_records_by_cpu_.end(),
it->second.get());
if (cpu_it != task_records_by_cpu_.end())
task_records_by_cpu_.erase(cpu_it);
auto memory_it = std::find(task_records_by_memory_.begin(),
task_records_by_memory_.end(),
it->second.get());
if (memory_it != task_records_by_memory_.end())
task_records_by_memory_.erase(memory_it);
task_records_.erase(it);
}
void ResourceReporter::OnTasksRefreshed(
const task_management::TaskIdList& task_ids) {
have_seen_first_task_manager_refresh_ = true;
// A priority queue to sort the task records by their |cpu|. Greatest |cpu|
// first.
std::priority_queue<TaskRecord*,
std::vector<TaskRecord*>,
TaskRecordCpuLessThan> records_by_cpu_queue;
// A priority queue to sort the task records by their |memory|. Greatest
// |memory| first.
std::priority_queue<TaskRecord*,
std::vector<TaskRecord*>,
TaskRecordMemoryLessThan> records_by_memory_queue;
task_records_by_cpu_.clear();
task_records_by_cpu_.reserve(kTopConsumersCount);
task_records_by_memory_.clear();
task_records_by_memory_.reserve(kTopConsumersCount);
for (const auto& id : task_ids) {
const double cpu_usage = observed_task_manager()->GetCpuUsage(id);
const int64_t memory_usage =
observed_task_manager()->GetPhysicalMemoryUsage(id);
// Browser and GPU processes are reported later using UMA histograms as they
// don't have any privacy issues.
const auto task_type = observed_task_manager()->GetType(id);
switch (task_type) {
case task_management::Task::UNKNOWN:
case task_management::Task::ZYGOTE:
break;
case task_management::Task::BROWSER:
last_browser_process_cpu_ = cpu_usage;
last_browser_process_memory_ = memory_usage >= 0 ? memory_usage : 0;
break;
case task_management::Task::GPU:
last_gpu_process_cpu_ = cpu_usage;
last_gpu_process_memory_ = memory_usage >= 0 ? memory_usage : 0;
break;
default:
// Other tasks types will be reported using Rappor.
TaskRecord* task_data = nullptr;
auto itr = task_records_.find(id);
if (itr == task_records_.end()) {
task_data = new TaskRecord(id);
task_records_[id] = make_scoped_ptr(task_data);
} else {
task_data = itr->second.get();
}
DCHECK_EQ(task_data->id, id);
task_data->task_name_for_rappor =
observed_task_manager()->GetTaskNameForRappor(id);
task_data->cpu_percent = cpu_usage;
task_data->memory_bytes = memory_usage;
task_data->is_background =
observed_task_manager()->IsTaskOnBackgroundedProcess(id);
// Push only valid or useful data to both priority queues. They might
// end up having more records than |kTopConsumerCount|, that's fine.
// We'll take care of that next.
if (task_data->cpu_percent > 0)
records_by_cpu_queue.push(task_data);
if (task_data->memory_bytes > 0)
records_by_memory_queue.push(task_data);
}
}
// Sort the |kTopConsumersCount| task records by their CPU and memory usage.
while (!records_by_cpu_queue.empty() &&
task_records_by_cpu_.size() < kTopConsumersCount) {
task_records_by_cpu_.push_back(records_by_cpu_queue.top());
records_by_cpu_queue.pop();
}
while (!records_by_memory_queue.empty() &&
task_records_by_memory_.size() < kTopConsumersCount) {
task_records_by_memory_.push_back(records_by_memory_queue.top());
records_by_memory_queue.pop();
}
}
// static
const size_t ResourceReporter::kTopConsumersCount = 10U;
ResourceReporter::ResourceReporter()
: TaskManagerObserver(base::TimeDelta::FromSeconds(kRefreshIntervalSeconds),
task_management::REFRESH_TYPE_CPU |
task_management::REFRESH_TYPE_MEMORY |
task_management::REFRESH_TYPE_PRIORITY),
system_cpu_cores_range_(GetCurrentSystemCpuCoresRange()) {
}
// static
scoped_ptr<rappor::Sample> ResourceReporter::CreateRapporSample(
rappor::RapporService* rappor_service,
const ResourceReporter::TaskRecord& task_record) {
scoped_ptr<rappor::Sample> sample(rappor_service->CreateSample(
rappor::UMA_RAPPOR_TYPE));
sample->SetStringField(kRapporTaskStringField,
task_record.task_name_for_rappor);
sample->SetFlagsField(kRapporPriorityFlagsField,
task_record.is_background ?
GET_ENUM_VAL(TaskProcessPriority::BACKGROUND) :
GET_ENUM_VAL(TaskProcessPriority::FOREGROUND),
GET_ENUM_VAL(TaskProcessPriority::NUM_PRIORITIES));
return sample;
}
// static
ResourceReporter::CpuUsageRange
ResourceReporter::GetCpuUsageRange(double cpu) {
if (cpu > 60.0)
return CpuUsageRange::RANGE_ABOVE_60_PERCENT;
if (cpu > 30.0)
return CpuUsageRange::RANGE_30_TO_60_PERCENT;
if (cpu > 10.0)
return CpuUsageRange::RANGE_10_TO_30_PERCENT;
return CpuUsageRange::RANGE_0_TO_10_PERCENT;
}
// static
ResourceReporter::MemoryUsageRange
ResourceReporter::GetMemoryUsageRange(int64_t memory_in_bytes) {
if (memory_in_bytes > kMemory1GB)
return MemoryUsageRange::RANGE_ABOVE_1_GB;
if (memory_in_bytes > kMemory800MB)
return MemoryUsageRange::RANGE_800_TO_1_GB;
if (memory_in_bytes > kMemory600MB)
return MemoryUsageRange::RANGE_600_TO_800_MB;
if (memory_in_bytes > kMemory400MB)
return MemoryUsageRange::RANGE_400_TO_600_MB;
if (memory_in_bytes > kMemory200MB)
return MemoryUsageRange::RANGE_200_TO_400_MB;
return MemoryUsageRange::RANGE_0_TO_200_MB;
}
// static
ResourceReporter::CpuCoresNumberRange
ResourceReporter::GetCurrentSystemCpuCoresRange() {
const int cpus = base::SysInfo::NumberOfProcessors();
if (cpus > 16)
return CpuCoresNumberRange::RANGE_ABOVE_16_CORES;
if (cpus > 8)
return CpuCoresNumberRange::RANGE_9_TO_16_CORES;
if (cpus > 4)
return CpuCoresNumberRange::RANGE_5_TO_8_CORES;
if (cpus > 2)
return CpuCoresNumberRange::RANGE_3_TO_4_CORES;
if (cpus == 2)
return CpuCoresNumberRange::RANGE_2_CORES;
if (cpus == 1)
return CpuCoresNumberRange::RANGE_1_CORE;
NOTREACHED();
return CpuCoresNumberRange::RANGE_NA;
}
const ResourceReporter::TaskRecord* ResourceReporter::SampleTaskByCpu() const {
// Perform a weighted random sampling taking the tasks' CPU usage as their
// weights to randomly select one of them to be reported by Rappor. The higher
// the CPU usage, the higher the chance that the task will be selected.
// See https://en.wikipedia.org/wiki/Reservoir_sampling.
TaskRecord* sampled_task = nullptr;
double cpu_weights_sum = 0;
for (const auto& task_data : task_records_by_cpu_) {
if ((base::RandDouble() * (cpu_weights_sum + task_data->cpu_percent)) >=
cpu_weights_sum) {
sampled_task = task_data;
}
cpu_weights_sum += task_data->cpu_percent;
}
return sampled_task;
}
const ResourceReporter::TaskRecord*
ResourceReporter::SampleTaskByMemory() const {
// Perform a weighted random sampling taking the tasks' memory usage as their
// weights to randomly select one of them to be reported by Rappor. The higher
// the memory usage, the higher the chance that the task will be selected.
// See https://en.wikipedia.org/wiki/Reservoir_sampling.
TaskRecord* sampled_task = nullptr;
int64_t memory_weights_sum = 0;
for (const auto& task_data : task_records_by_memory_) {
if ((base::RandDouble() * (memory_weights_sum + task_data->memory_bytes)) >=
memory_weights_sum) {
sampled_task = task_data;
}
memory_weights_sum += task_data->memory_bytes;
}
return sampled_task;
}
void ResourceReporter::OnMemoryPressure(
MemoryPressureLevel memory_pressure_level) {
if (have_seen_first_task_manager_refresh_ &&
memory_pressure_level >=
MemoryPressureLevel::MEMORY_PRESSURE_LEVEL_MODERATE) {
// Report browser and GPU processes usage using UMA histograms.
UMA_HISTOGRAM_ENUMERATION(
"ResourceReporter.BrowserProcess.CpuUsage",
GET_ENUM_VAL(GetCpuUsageRange(last_browser_process_cpu_)),
GET_ENUM_VAL(CpuUsageRange::NUM_RANGES));
UMA_HISTOGRAM_ENUMERATION(
"ResourceReporter.BrowserProcess.MemoryUsage",
GET_ENUM_VAL(GetMemoryUsageRange(last_browser_process_memory_)),
GET_ENUM_VAL(MemoryUsageRange::NUM_RANGES));
UMA_HISTOGRAM_ENUMERATION(
"ResourceReporter.GpuProcess.CpuUsage",
GET_ENUM_VAL(GetCpuUsageRange(last_gpu_process_cpu_)),
GET_ENUM_VAL(CpuUsageRange::NUM_RANGES));
UMA_HISTOGRAM_ENUMERATION(
"ResourceReporter.GpuProcess.MemoryUsage",
GET_ENUM_VAL(GetMemoryUsageRange(last_gpu_process_memory_)),
GET_ENUM_VAL(MemoryUsageRange::NUM_RANGES));
// For the rest of tasks, report them using Rappor.
auto rappor_service = g_browser_process->rappor_service();
if (!rappor_service)
return;
// We only record Rappor samples only if it's the first ever moderate or
// critical memory pressure event we receive, or it has been more than
// |kMinimumTimeBetweenReportsInMs| since the last time we recorded samples.
if (!have_seen_first_memory_pressure_event_) {
have_seen_first_memory_pressure_event_ = true;
} else if ((base::TimeTicks::Now() - last_memory_pressure_event_time_) <
base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenReportsInMs)) {
return;
}
last_memory_pressure_event_time_ = base::TimeTicks::Now();
// Use weighted random sampling to select a task to report in the CPU
// metric.
const TaskRecord* sampled_cpu_task = SampleTaskByCpu();
if (sampled_cpu_task) {
scoped_ptr<rappor::Sample> cpu_sample(
CreateRapporSample(rappor_service, *sampled_cpu_task));
cpu_sample->SetFlagsField(kRapporNumCoresRangeFlagsField,
GET_ENUM_VAL(system_cpu_cores_range_),
GET_ENUM_VAL(CpuCoresNumberRange::NUM_RANGES));
cpu_sample->SetFlagsField(
kRapporUsageRangeFlagsField,
GET_ENUM_VAL(GetCpuUsageRange(sampled_cpu_task->cpu_percent)),
GET_ENUM_VAL(CpuUsageRange::NUM_RANGES));
rappor_service->RecordSampleObj(kCpuRapporMetric, std::move(cpu_sample));
}
// Use weighted random sampling to select a task to report in the memory
// metric.
const TaskRecord* sampled_memory_task = SampleTaskByMemory();
if (sampled_memory_task) {
scoped_ptr<rappor::Sample> memory_sample(
CreateRapporSample(rappor_service, *sampled_memory_task));
memory_sample->SetFlagsField(
kRapporUsageRangeFlagsField,
GET_ENUM_VAL(GetMemoryUsageRange(sampled_memory_task->memory_bytes)),
GET_ENUM_VAL(MemoryUsageRange::NUM_RANGES));
rappor_service->RecordSampleObj(kMemoryRapporMetric,
std::move(memory_sample));
}
}
}
} // namespace chromeos
| 37.412037 | 80 | 0.707833 | [
"vector"
] |
d98b977c77c6ae02d4e1ee98def627fbf395b763 | 5,052 | cpp | C++ | escos/src/mmitss/mmitss-controller-daemon/mmitssServiceControl.cpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/mmitss/mmitss-controller-daemon/mmitssServiceControl.cpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/mmitss/mmitss-controller-daemon/mmitssServiceControl.cpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | /*
* serviceControl.cpp
*
* Created on: May 25, 2017
* Author: devel
*/
#include "mmitssServiceControl.hpp"
#include "stdheader.h"
#include "facilityLayer.hpp"
namespace WaveApp
{
namespace MmitssCtrl
{
static const std::string TRAJ_AWARE_SRV = "mmitss_trajectory_aware.service";
static const std::string PERF_OBSERVER_SRV = "mmitss_perf_observer.service";
static const std::string PRIO_REQ_SRV = "mmitss_prio_req.service";
static const std::string PRIO_SOLVER_SRV = "mmitss_prio_solver.service";
static const std::string TRAF_CTRL_SRV = "mmitss_traffic_control.service";
static const std::string ISIG_SRV = "mmitss_isig.service";
static const std::vector<std::pair<std::string, int>> MMITSS_SERVICES = {
std::make_pair(PRIO_SOLVER_SRV, Priority),
std::make_pair(TRAJ_AWARE_SRV, Passive | Priority | ISIG),
std::make_pair(PERF_OBSERVER_SRV, Passive | Priority | ISIG),
std::make_pair(PRIO_REQ_SRV, Priority), std::make_pair(TRAF_CTRL_SRV, Priority | ISIG),
std::make_pair(ISIG_SRV, ISIG)};
bool MmitssServiceControl::start(MmitssOperatingMode mode)
{
m_running = true;
m_completeStop = false;
ITSAPP_TRACE("start MMITSS services with mode:%d.", mode);
for (auto& s : MMITSS_SERVICES)
{
if (s.second & mode)
{
ITSAPP_TRACE("Start MMITSS service: %s", s.first.c_str());
if (!startService(s.first))
{
ITSAPP_WRN("MMITSS service: %s cannot be started", s.first.c_str());
stop();
m_running = false;
return m_running;
}
}
}
return m_running;
}
bool MmitssServiceControl::stop()
{
m_running = false;
for (const auto& s : MMITSS_SERVICES)
{
ITSAPP_TRACE("stop MMITSS service: %s", s.first.c_str());
bool ret = stopService(s.first);
if (!ret)
{
ITSAPP_WRN("Couldn't stop %s", s.first.c_str());
return false;
}
}
m_completeStop = true;
return true;
}
bool MmitssServiceControl::startService(const std::string& service)
{
return siekdbus::systemd_start_unit(service.c_str());
}
bool MmitssServiceControl::MmitssServiceControl::stopService(const std::string& service)
{
return siekdbus::systemd_stop_unit(service.c_str());
}
bool MmitssServiceControl::getUnit(const std::string& service, siekdbus::UnitInfo& unit) const
{
for (const auto& u : m_services)
{
if (u.id == service)
{
unit = u;
return true;
}
}
return false;
}
Poco::DynamicStruct MmitssServiceControl::getJsonStatus()
{
Poco::DynamicStruct status;
int numActive = 0;
if (readServiceState())
{
Poco::DynamicStruct services;
for (const auto& s : MMITSS_SERVICES)
{
siekdbus::UnitInfo unit;
if (getUnit(s.first, unit))
{
services[s.first] =
(unit.active_state != "active") ? "inactive" : unit.active_state;
if (unit.active_state == "active")
numActive++;
}
else
{
services[s.first] = "inactive";
ITSAPP_DBG("Couldn't get unit state for %s", s.c_str());
}
}
status["services"] = services;
}
status["running"] = m_running;
status["num_active"] = numActive;
status["num_inactive"] = MMITSS_SERVICES.size() - numActive;
return status;
}
SERVICE_STATE MmitssServiceControl::getStatus(MmitssOperatingMode mode, std::string& status)
{
SERVICE_STATE state = SERVICE_STATE::UNKNOWN;
int numActive = 0;
if (readServiceState())
{
std::string result;
for (const auto& s : MMITSS_SERVICES)
{
siekdbus::UnitInfo unit;
if (getUnit(s.first, unit))
{
status += s.first + std::string(":") + unit.active_state + std::string("\n");
if (unit.active_state == "active")
numActive++;
else if (m_running && (s.second & mode))
state = SERVICE_STATE::CRITICAL;
}
}
if (m_running && (state == SERVICE_STATE::UNKNOWN))
state = SERVICE_STATE::OK;
}
if (state == SERVICE_STATE::UNKNOWN)
{
status += std::string("Disabled");
}
else if (state == SERVICE_STATE::CRITICAL)
{
status += std::string("Error: ") + std::to_string(MMITSS_SERVICES.size() - numActive) +
std::string(" services inactive");
}
else
{
status += std::string("OK ") + std::to_string(numActive) + std::string(" services running");
}
m_state = state;
return m_state;
}
bool MmitssServiceControl::readServiceState()
{
m_services.clear();
if (!siekdbus::systemd_list_units(m_services))
{
ITSAPP_WRN("Failed to read unit status!");
return false;
}
return true;
}
} // namespace MmitssCtrl
} // namespace WaveApp
| 28.704545 | 100 | 0.595606 | [
"vector"
] |
d99095e4bd8e2f8a27e048e19316f87a3591ddbc | 3,673 | cpp | C++ | Practice/2019.2.6/UOJ349.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2019.2.6/UOJ349.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2019.2.6/UOJ349.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include "rts.h"
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<iostream>
using namespace std;
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=303000;
const int maxM=maxN<<1;
const double alpha=0.8;
const int inf=1000000000;
int n,frt=1;
int edgecnt=-1,Head[maxN],Next[maxM],V[maxM];
int Dsz[maxN],Sz[maxN],Mx[maxN],root,top,Bp[maxN];
bool vis[maxN],use[maxN];
map<int,int> Son[maxN];
vector<int> Dt[maxN];
int Seq[maxN],Sk[maxN+maxN];
void Add_Edge(int u,int v);
void Solve(int u,int q);
void dfs_mark(int u);
void dfs_root(int u,int fa,int size);
void Divide(int u,int size);
void play(int _n, int T, int dataType)
{
mem(Head,-1);
n=_n;
use[1]=1;
Mx[0]=inf;
vis[1]=use[1]=1;
for (int i=1; i<=n; i++) Seq[i]=i;
for (int i=1; i<=n; i++) {
int u=rand()%n+1,v=rand()%n+1;
swap(Seq[u],Seq[v]);
}
if (dataType==3) {
int left=maxN,right=maxN;
Sk[left]=1;
for (int ti=1; ti<=n; ti++)
if (vis[Seq[ti]]==0) {
int t=Seq[ti];
int r=explore(Sk[left],t);
if (r==Sk[left+1]) {
do {
r=explore(Sk[right],t);
Sk[++right]=r;
vis[r]=1;
} while (r!=t);
} else {
Sk[--left]=r;
vis[r]=1;
while (r!=t) {
r=explore(Sk[left],t);
Sk[--left]=r;
vis[r]=1;
}
}
}
return;
}
for (int ti=1; ti<=n; ++ti)
if (use[Seq[ti]]==0) {
int t=Seq[ti];
top=0;
Solve(frt,t);
for (int i=1; i<top; i++)
if (Dsz[Bp[i]]*alpha<Dsz[Bp[i+1]]) {
int u=Bp[i];
dfs_mark(u);
root=0;
dfs_root(u,u,Dsz[u]);
if (i!=1) {
for (map<int,int>::iterator it=Son[Bp[i-1]].begin(); it!=Son[Bp[i-1]].end(); ++it)
if ((*it).second==u) {
int ut=(*it).first;
Son[Bp[i-1]][ut]=root;
break;
}
for (int j=0,sz=Dt[Bp[i-1]].size(); j<sz; j++)
if (Dt[Bp[i-1]][j]==u) {
Dt[Bp[i-1]][j]=root;
break;
}
}
//cout<<"nrt:"<<root<<endl;
if (u==frt) frt=root;
Divide(root,Dsz[u]);
break;
}
}
return;
}
void Add_Edge(int u,int v)
{
Next[++edgecnt]=Head[u];
Head[u]=edgecnt;
V[edgecnt]=v;
Next[++edgecnt]=Head[v];
Head[v]=edgecnt;
V[edgecnt]=u;
return;
}
void Solve(int u,int q)
{
//cout<<"Solve:"<<u<<" "<<q<<endl;
int r=explore(u,q);
Bp[++top]=u;
if (r==q) {
Bp[++top]=q;
Add_Edge(u,q);
Dsz[q]=1;
++Dsz[u];
Son[u][q]=q;
Dt[u].push_back(q);
use[q]=vis[q]=1;
} else if (Son[u].count(r)) {
Dsz[u]-=Dsz[Son[u][r]];
Solve(Son[u][r],q);
Dsz[u]+=Dsz[Son[u][r]];
} else {
Son[u][r]=r;
use[r]=vis[r]=1;
Add_Edge(u,r);
Dsz[r]=1;
Dt[u].push_back(r);
Solve(r,q);
Dsz[u]+=Dsz[r];
}
}
void dfs_mark(int u)
{
vis[u]=0;
Son[u].clear();
for (int i=0,sz=Dt[u].size(); i<sz; i++) dfs_mark(Dt[u][i]);
Dt[u].clear();
return;
}
void dfs_root(int u,int fa,int size)
{
Sz[u]=1;
Mx[u]=0;
//cout<<"dfsroot:"<<u<<" "<<fa<<endl;
for (int i=Head[u]; i!=-1; i=Next[i])
if (V[i]!=fa&&vis[V[i]]==0) {
dfs_root(V[i],u,size);
Sz[u]+=Sz[V[i]];
Mx[u]=max(Mx[u],Sz[V[i]]);
}
Mx[u]=max(Mx[u],size-Sz[u]);
if (Mx[u]<Mx[root]) root=u;
return;
}
void Divide(int u,int size)
{
//cout<<"Divide:"<<u<<" "<<size<<endl;
Dsz[u]=size;
vis[u]=1;
Son[u].clear();
for (int i=Head[u]; i!=-1; i=Next[i])
if (vis[V[i]]==0) {
int s=(Sz[V[i]]>Sz[u])?size-Sz[u]:Sz[V[i]];
root=0;
dfs_root(V[i],V[i],s);
//cout<<u<<"->"<<root<<endl;
Son[u][V[i]]=root;
Dt[u].push_back(root);
Divide(root,s);
}
return;
} | 20.869318 | 89 | 0.496869 | [
"vector"
] |
d995b073b7301a2780ec6c4e0a3acf6147049a17 | 9,348 | cpp | C++ | kidnapped-vehicle/src/particle_filter.cpp | mithi/particle-filter-prototype | b1ded3c72bb71664bb6fe85be08400b94bdbfb88 | [
"MIT"
] | 40 | 2017-12-06T15:19:11.000Z | 2022-02-07T15:14:33.000Z | kidnapped-vehicle/src/particle_filter.cpp | mithi/particle-filter-prototype | b1ded3c72bb71664bb6fe85be08400b94bdbfb88 | [
"MIT"
] | null | null | null | kidnapped-vehicle/src/particle_filter.cpp | mithi/particle-filter-prototype | b1ded3c72bb71664bb6fe85be08400b94bdbfb88 | [
"MIT"
] | 18 | 2018-08-09T07:03:37.000Z | 2022-03-08T10:11:19.000Z | #include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include "particle_filter.h"
using namespace std;
const int NUMBER_OF_PARTICLES = 300;
const double INITIAL_WEIGHT = 1.0;
/*
* NOTE(s):
* GAUSSIAN NOISE
* - http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* - http://www.cplusplus.com/reference/random/default_random_engine/
* MULTIVARIATE NORMAL DISTRIBUTIONS
* - https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* TRANSFORMING FROM MAP TO VEHICLE COORDINATE
* - https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* The map's y-axis actually points downwards.
* - http://planning.cs.uiuc.edu/node99.html
* DISCRETE_DISTRIBUTION
* - http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
* A Mersenne Twister pseudo-random generator of 32-bit numbers with a state size of 19937 bits.
* - http://www.cplusplus.com/reference/random/default_random_engine/
*/
/***************************************************************
* Set the number of particles. Initialize all particles to first position
* (based on estimates of x, y, theta and their uncertainties from GPS) and all weights to 1.
* random gaussian noise is added to each particle
***************************************************************/
void ParticleFilter::init(double x, double y, double theta, double std[]) {
this->num_particles = NUMBER_OF_PARTICLES;
random_device random_device;
mt19937 gen(random_device());
normal_distribution<> particle_x(x, std[0]);
normal_distribution<> particle_y(y, std[1]);
normal_distribution<> particle_theta(theta, std[2]);
for (int i = 0; i < NUMBER_OF_PARTICLES; i++) {
Particle p = {
i,
particle_x(gen),
particle_y(gen),
particle_theta(gen),
INITIAL_WEIGHT
};
this->weights.push_back(INITIAL_WEIGHT);
this->particles.push_back(p);
}
this->is_initialized = true;
}
/***************************************************************
* Add measurements to each particle and add random Gaussian noise.
***************************************************************/
void ParticleFilter::prediction(double delta_t, double std[], double velocity, double yaw_rate) {
const double THRESH = 0.001;
random_device random_device;
mt19937 gen(random_device());
normal_distribution<> noise_x(0.0, std[0]);
normal_distribution<> noise_y(0.0, std[1]);
normal_distribution<> noise_theta(0.0, std[2]);
for (int i = 0; i < NUMBER_OF_PARTICLES; i++) {
double d = velocity * delta_t;
double theta = this->particles[i].theta;
if (fabs(yaw_rate) < THRESH) { //moving straight
this->particles[i].x += d * cos(theta) + noise_x(gen);
this->particles[i].y += d * sin(theta) + noise_y(gen);
this->particles[i].theta += noise_theta(gen);
} else {
double delta_theta = yaw_rate * delta_t;
double phi = theta + delta_theta;
double k = velocity / yaw_rate;
this->particles[i].x += k * (sin(phi) - sin(theta)) + noise_x(gen);
this->particles[i].y += k * (cos(theta) - cos(phi)) + noise_y(gen);
this->particles[i].theta = phi + noise_theta(gen);
}
}
}
/**************************************************************
* Find the predicted measurement that is closest to each observed measurement
* and assign the observed measurement to this particular landmark.
***************************************************************/
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations){
const double BIG_NUMBER = 1.0e99;
for (int i = 0; i < observations.size(); i++) {
int current_j;
double current_smallest_error = BIG_NUMBER;
for (int j = 0; j < observations.size(); j++) {
double dx = predicted[j].x - observations[i].x;
double dy = predicted[j].y - observations[i].y;
double error = dx * dx + dy * dy;
if (error < current_smallest_error) {
current_j = j;
current_smallest_error = error;
}
}
observations[i].id = current_j;
}
}
/***************************************************************
* Update the weights of each particle using a mult-variate Gaussian distribution.
* NOTE: The observations are given in the VEHICLE'S coordinate system. Particles are located
* according to the MAP'S coordinate system. So transformation is done.
* For each particle:
* 1. transform observations from vehicle to map coordinates assuming it's the particle observing
* 2. find landmarks within the particle's range
* 3. find which landmark is likely being observed based on nearest neighbor method
* 4. determine the weights based difference particle's observation and actual observation
***************************************************************/
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], std::vector<LandmarkObs> observations, Map map_landmarks) {
for (int i = 0; i < NUMBER_OF_PARTICLES; i++) {
double px = this->particles[i].x;
double py = this->particles[i].y;
double ptheta = this->particles[i].theta;
vector<LandmarkObs> landmarks_in_range;
vector<LandmarkObs> map_observations;
/**************************************************************
* STEP 1:
* transform each observations to map coordinates
* assume observations are made in the particle's perspective
**************************************************************/
for (int j = 0; j < observations.size(); j++){
int oid = observations[j].id;
double ox = observations[j].x;
double oy = observations[j].y;
double transformed_x = px + ox * cos(ptheta) - oy * sin(ptheta);
double transformed_y = py + oy * cos(ptheta) + ox * sin(ptheta);
LandmarkObs observation = {
oid,
transformed_x,
transformed_y
};
map_observations.push_back(observation);
}
/**************************************************************
* STEP 2:
* Find map landmarks within the sensor range
**************************************************************/
for (int j = 0; j < map_landmarks.landmark_list.size(); j++) {
int mid = map_landmarks.landmark_list[j].id_i;
double mx = map_landmarks.landmark_list[j].x_f;
double my = map_landmarks.landmark_list[j].y_f;
double dx = mx - px;
double dy = my - py;
double error = sqrt(dx * dx + dy * dy);
if (error < sensor_range) {
LandmarkObs landmark_in_range = {
mid,
mx,
my
};
landmarks_in_range.push_back(landmark_in_range);
}
}
/**************************************************************
* STEP 3:
* Associate landmark in range (id) to landmark observations
* this function modifies std::vector<LandmarkObs> observations
* NOTE: - all landmarks are in map coordinates
* - all observations are in map coordinates
**************************************************************/
dataAssociation(landmarks_in_range, map_observations);
/**************************************************************
* STEP 4:
* Compare each observation (by actual vehicle) to corresponding
* observation by the particle (landmark_in_range)
* update the particle weight based on this
**************************************************************/
double w = INITIAL_WEIGHT;
double varx = std_landmark[0];
double vary = std_landmark[1];
for (int j = 0; j < map_observations.size(); j++){
int oid = map_observations[j].id;
double ox = map_observations[j].x;
double oy = map_observations[j].y;
double predicted_x = landmarks_in_range[oid].x;
double predicted_y = landmarks_in_range[oid].y;
double dx = ox - predicted_x;
double dy = oy - predicted_y;
double a = dx * dx / (2.0 * varx * varx);
double b = dy * dy / (2.0 * vary * vary);
double d = sqrt( 2.0 * M_PI * varx * vary);
double r = exp(-(a + b)) / d;
w *= r;
}
this->particles[i].weight = w;
this->weights[i] = w;
}
}
/**************************************************************
* Resample particles with replacement with probability proportional to their weight.
***************************************************************/
void ParticleFilter::resample(){
vector<Particle> resampled_particles;
random_device random_device;
mt19937 gen(random_device());
discrete_distribution<int> index(this->weights.begin(), this->weights.end());
for (int c = 0; c < NUMBER_OF_PARTICLES; c++) {
int i = index(gen);
Particle p {
i,
this->particles[i].x,
this->particles[i].y,
this->particles[i].theta,
INITIAL_WEIGHT
};
resampled_particles.push_back(p);
}
this->particles = resampled_particles
}
void ParticleFilter::write(std::string filename) {
// You don't need to modify this file.
std::ofstream dataFile;
dataFile.open(filename, std::ios::app);
for (int i = 0; i < this->num_particles; ++i) {
dataFile << this->particles[i].x << " " << this->particles[i].y << " " << this->particles[i].theta << "\n";
}
dataFile.close();
}
| 32.685315 | 138 | 0.581301 | [
"vector",
"transform"
] |
d996b58eee3a0e569898dd5581b4c6c358881cf0 | 13,471 | cpp | C++ | platforms/cpp/modules/dust/DplStl/DplStlData.cpp | MondoAurora/MiNDForge | 88a3f5ea27f1970f766714d1303c11929888c176 | [
"Apache-2.0"
] | 1 | 2020-05-16T21:06:38.000Z | 2020-05-16T21:06:38.000Z | platforms/cpp/modules/dust/DplStl/DplStlData.cpp | MondoAurora/MiNDForge | 88a3f5ea27f1970f766714d1303c11929888c176 | [
"Apache-2.0"
] | null | null | null | platforms/cpp/modules/dust/DplStl/DplStlData.cpp | MondoAurora/MiNDForge | 88a3f5ea27f1970f766714d1303c11929888c176 | [
"Apache-2.0"
] | null | null | null | #include "DplStl.h"
#include <iostream>
using namespace std;
DplStlDataValue::DplStlDataValue()
:key(DUST_ENTITY_APPEND), valTarget(DUST_ENTITY_INVALID) // valPtrRef(NULL)
{}
DplStlDataValue::DplStlDataValue(const DplStlDataValue &src, DplStlDataVariant *pVar)
{
key = src.key;
switch ( pVar->pTokenInfo->valType )
{
case DUST_VAL_INTEGER:
valLong = src.valLong;
break;
case DUST_VAL_REAL:
valDouble = src.valDouble;
break;
case DUST_VAL_REF:
valTarget = src.valTarget;
break;
default:
break;
}
}
DplStlDataValue::~DplStlDataValue()
{
}
bool DplStlDataValue::match(DustValType vT, DustAccessData &ad)
{
if ( key != ad.key )
{
return false;
}
switch ( vT )
{
case DUST_VAL_INTEGER:
return ad.valLong == valLong;
case DUST_VAL_REAL:
return ad.valDouble == valDouble;
case DUST_VAL_REF:
return ad.valLong == valTarget;
default:
return false;
}
}
bool DplStlDataValue::loadFrom(DustValType vT, DustAccessData &ad)
{
key = ad.key;
switch ( vT )
{
case DUST_VAL_INTEGER:
valLong = ad.valLong;
return true;
case DUST_VAL_REAL:
valDouble = ad.valDouble;
return true;
case DUST_VAL_REF:
valTarget = ad.valLong;
return true;
default:
DustUtils::log(DUST_EVENT_ERROR) << "Improper valType ";
return false;
}
}
bool DplStlDataValue::writeTo(DustValType vT, DustAccessData &ad)
{
ad.key = key;
switch ( vT )
{
case DUST_VAL_INTEGER:
ad.valLong = valLong;
return true;
case DUST_VAL_REAL:
ad.valDouble = valDouble;
return true;
case DUST_VAL_REF:
ad.valLong = valTarget;
return true;
default:
return false;
}
}
void DplStlDataValue::visit(DustValType vT, DplStlDataVisit *pVisit)
{
DustAccessData *pAd = pVisit->getAccData();
writeTo(vT, *pAd);
pVisit->send(DUST_VISIT_VALUE);
if ( DUST_VAL_REF == vT )
{
pVisit->optAdd(valTarget);
}
pAd->valLong = 0;
pAd->valDouble = 0.0;
}
DplStlDataVariant::DplStlDataVariant(DplStlTokenInfo *pTI)
:pTokenInfo(pTI), pColl(0)
{
}
DplStlDataVariant::DplStlDataVariant(const DplStlDataVariant &src)
: pTokenInfo(src.pTokenInfo), value(src.value, this), pColl(0)
{
int s = src.pColl ? src.pColl->size() : 0;
if ( s )
{
pColl = new vector<DplStlDataValue*>();
pColl->resize(s);
for ( int i = 0; i < s; ++i )
{
pColl->push_back(new DplStlDataValue((*src.pColl->at(i)), this));
}
}
}
DplStlDataVariant::~DplStlDataVariant()
{
if ( pColl )
{
for ( int i = pColl->size(); i-->0; )
{
delete pColl->at(i);
}
pColl->clear();
delete pColl;
}
};
bool DplStlDataVariant::matchValue(DustValType vt, DustCollType ct, DustAccessData &ad, DplStlDataValue* pVal)
{
switch ( ct )
{
case DUST_COLL_SET:
return pVal->match(vt, ad);
case DUST_COLL_MAP:
return pVal->key == ad.key;
default:
return false;
}
}
DplStlDataValue* DplStlDataVariant::locateForOverride(DustAccessData &ad)
{
DplStlDataValue* ret = &value;
DustCollType ct = pTokenInfo->collType;
if ( DUST_COLL_SINGLE != ct )
{
DustValType vt = pTokenInfo->valType;
if ( pColl )
{
int s = pColl->size();
DplStlDataValue* pv;
switch ( ct )
{
case DUST_COLL_ARR:
return ((0 <= ad.key) && (ad.key < s)) ? pColl->at(ad.key) : NULL;
case DUST_COLL_SET:
if ((0 <= ad.key) && (ad.key < s))
{
return pColl->at(ad.key);
}
// no break
case DUST_COLL_MAP:
for ( int i = 0; i < s; ++i )
{
pv = pColl->at(i);
if ( matchValue(vt, ct, ad, pv))
{
return pv;
}
}
ret = NULL;
break;
default:
break;
}
}
else
{
if ( (0 == ad.key) && ((DUST_COLL_ARR == ct) || (DUST_COLL_SET == ct)) )
{
return ret;
}
if ( !matchValue(vt, ct, ad, ret))
{
ret = NULL;
}
}
}
return ret;
}
bool DplStlDataVariant::setValue(DustValType vt, DustAccessData &ad, DplStlDataValue * pVal)
{
return pVal->loadFrom(vt, ad);
}
DplStlDataValue * DplStlDataVariant::add(DustValType vt, DustAccessData &ad)
{
if ( !pColl )
{
pColl = new vector<DplStlDataValue*>();
pColl->push_back(new DplStlDataValue(value, this));
}
DplStlDataValue *pv = new DplStlDataValue();
setValue(vt, ad, pv);
pColl->push_back(pv);
return pv;
}
bool DplStlDataVariant::access(DustAccessData &ad)
{
bool ret = false;
DustValType vt = pTokenInfo->valType;
DplStlDataValue *pVal = locateForOverride(ad);
switch ( ad.access )
{
case DUST_ACCESS_GET:
ret = pVal ? pVal->writeTo(vt, ad) : false;
break;
case DUST_ACCESS_SET:
if ( pVal )
{
if ( !pVal->match(vt, ad))
{
ret = setValue(vt, ad, pVal);
}
}
else
{
add(vt, ad);
ret = true;
}
break;
case DUST_ACCESS_REMOVE:
break;
default:
break;
}
return ret;
}
void DplStlDataVariant::visit(DplStlDataVisit *pVisit)
{
if ( DUST_COLL_SINGLE == pTokenInfo->collType )
{
value.visit(pTokenInfo->valType, pVisit);
}
else
{
DustResultType res = pVisit->send(DUST_VISIT_BEGIN);
if ( DUST_RESULT_REJECT != res )
{
if ( pColl )
{
for ( int i = pColl->size(); i-->0; )
{
pColl->at(i)->visit(pTokenInfo->valType, pVisit);
}
}
else
{
value.visit(pTokenInfo->valType, pVisit);
}
}
pVisit->send(DUST_VISIT_END);
}
}
DplStlDataEntity::DplStlDataEntity(long id_, DustEntity primaryType_)
:id(id_), primaryType(primaryType_), pNative(NULL)
{
DustAccessData ad(id_, DUST_BOOT_INT_ID, id_);
access(ad);
ad.token = DUST_BOOT_REF_PRIMARYTYPE;
ad.valLong = primaryType_;
access(ad);
}
DplStlDataEntity::DplStlDataEntity(DplStlDataEntity &src)
:id(src.id), primaryType(src.primaryType), pNative(NULL)
{
for (VarPtrIterator it = src.model.begin(); it != src.model.end(); ++it)
{
model[it->first] = new DplStlDataVariant(*(it->second));
}
}
DplStlDataEntity::~DplStlDataEntity()
{
for (VarPtrIterator it = model.begin(); it != model.end(); ++it)
{
delete it->second;
}
if ( pNative )
{
DplStlRuntime* pRT = DplStlRuntime::getRuntime();
for (PtrIterator it = pNative->begin(); it != pNative->end(); ++it)
{
pRT->deleteNative(it->first, it->second);
}
delete pNative;
}
};
DplStlDataVariant *DplStlDataEntity::getVariant(DustEntity token)
{
DplStlDataVariant *pVar = mapOptGet(model, token);
return pVar;
}
void DplStlDataEntity::deleteVariant(DustEntity token, DplStlDataVariant *pVar)
{
delete pVar;
model.erase(token);
}
void *DplStlDataEntity::getNative(DustEntity token)
{
return pNative ? mapOptGet((*pNative), token) : NULL;
}
void* DplStlDataEntity::setNative(DustEntity token, void *ptr)
{
void *pOrig = NULL;
if (!pNative)
{
pNative = new map<DustEntity, void*>();
}
else
{
pOrig = mapOptGet((*pNative), token);
}
(*pNative)[token] = ptr;
return pOrig;
}
bool DplStlDataEntity::access(DustAccessData &ad)
{
bool ret = false;
DplStlDataVariant *pVar = getVariant(ad.token);
if ( pVar )
{
bool single = ( DUST_COLL_SINGLE == pVar->pTokenInfo->collType );
switch ( ad.access )
{
case DUST_ACCESS_CLEAR:
deleteVariant(ad.token, pVar);
ret = true;
break;
case DUST_ACCESS_REMOVE:
if ( single )
{
deleteVariant(ad.token, pVar);
ret = true;
}
else
{
ret = pVar->access(ad);
if ( ret && pVar->pColl && pVar->pColl->empty() )
{
deleteVariant(ad.token, pVar);
}
}
break;
default:
ret = pVar->access(ad);
}
}
else if ( DUST_ACCESS_SET == ad.access )
{
DplStlTokenInfo *pTI = DplStlRuntime::getCurrentThread()->getApp()->getTokenInfo(ad.token);
pVar = new DplStlDataVariant(pTI);
model[ad.token] = pVar;
ret = pVar->setValue(pTI->valType, ad, &pVar->value);
}
return ret;
}
void DplStlDataEntity::visit(DplStlDataVisit *pVisit)
{
DustResultType res = pVisit->send(DUST_VISIT_BEGIN);
DustAccessData *pAd = pVisit->getAccData();
pAd->entity = id;
if ( DUST_RESULT_REJECT != res )
{
if ( pAd->token )
{
DplStlDataVariant *pVar = getVariant(pAd->token);
if ( pVar )
{
pVar->visit(pVisit);
}
}
else
{
for (VarPtrIterator it = model.begin(); it != model.end(); ++it)
{
pAd->token = it->first;
it->second->visit(pVisit);
}
pAd->token = DUST_ENTITY_INVALID;
}
}
pVisit->send(DUST_VISIT_END);
}
void DplStlDataEntity::setType(DustAccessData &ad, DplStlDataEntity *pSrc)
{
// copy type content
}
DplStlDataStore::DplStlDataStore(DplStlDataStore *pParent_)
:pParent(pParent_), nextId(pParent_ ? pParent_->nextId + 1 : DUST_LAST_CONST_RUNTIME)
{
}
DplStlDataStore::~DplStlDataStore()
{
for ( EntityPtrIterator it = entities.begin(); it != entities.end(); ++it)
{
delete it->second;
}
entities.clear();
}
void DplStlDataStore::overwrite(DustEntity id, DplStlDataEntity *pE)
{
DplStlDataEntity *pOrig = mapOptGet(entities, id);
if ( pOrig )
{
delete pOrig;
}
entities[id] = pE;
}
DplStlDataEntity* DplStlDataStore::getEntity(long id, DustEntity primaryType)
{
DplStlDataEntity *pEntity = 0;
if ( DUST_ENTITY_APPEND == id )
{
id = ++nextId;
}
else
{
pEntity = findEntity(entities, id);
if ( pParent && !pEntity )
{
pEntity = pParent->getEntity(id, primaryType);
}
}
if ( !pEntity )
{
pEntity = new DplStlDataEntity(id, primaryType);
entities[id] = pEntity;
}
return pEntity;
}
void DplStlDataStore::init(DplStlDataStore *pParent_)
{
entities.clear();
pParent = pParent_;
}
void DplStlDataStore::loadAll(DplStlDataVisit *pVisit)
{
for ( EntityPtrIterator it = entities.begin(); it != entities.end(); ++it)
{
pVisit->optAdd(it->first);
}
}
void DplStlDataStore::commit()
{
if ( pParent )
{
for ( EntityPtrIterator it = entities.begin(); it != entities.end(); ++it )
{
pParent->overwrite(it->first, it->second);
}
entities.clear();
}
}
void DplStlDataStore::rollback()
{
if ( pParent )
{
}
};
DplStlDataVisit::DplStlDataVisit(DplStlRuntime *pR, DustAccessData &da, DustDiscoveryVisitor v, void* h)
:pRuntime(pR), pAd(&da), visitor(v), pHint(h), ret(DUST_RESULT_NOTIMPLEMENTED)
{
}
DplStlDataVisit::~DplStlDataVisit()
{
if ( DUST_RESULT_NOTIMPLEMENTED != ret )
{
send(DUST_VISIT_CLOSE);
}
}
DustResultType DplStlDataVisit::execute()
{
send(DUST_VISIT_OPEN);
if ( pAd->entity )
{
toVisit.insert(pAd->entity);
}
else
{
pRuntime->getCurrentThread()->getDialog()->store.loadAll(this);
}
for ( VisitIterator vi = toVisit.begin(); vi != toVisit.end(); vi = toVisit.begin())
{
DustEntity target = *vi;
DplStlDataEntity *pE = pRuntime->resolveEntity(target);
pE->visit(this);
visited.insert(target);
toVisit.erase(target);
}
return ret;
}
DustResultType DplStlDataVisit::send(DustVisitState vs)
{
ret = visitor(vs, *pAd, pHint);
return ret;
}
void DplStlDataVisit::optAdd(DustEntity entity)
{
if ( visited.find(entity) == visited.end() )
{
toVisit.insert(entity);
}
}
| 23.02735 | 111 | 0.527281 | [
"vector",
"model"
] |
d9976dd57c52ba6a38f164239ad3a3082f50a688 | 496 | cpp | C++ | LeetCode/Practice/Two_Sum.cpp | aldew5/Competitve-Programming | eb0b93a35af3bd5e806aedc44b835830af01d496 | [
"MIT"
] | 2 | 2020-05-09T15:54:18.000Z | 2021-01-23T22:32:53.000Z | LeetCode/Practice/Two_Sum.cpp | aldew5/Competitive-Programming | fc93723fae739d0b06bcf2dbe3b9274584a79a66 | [
"MIT"
] | null | null | null | LeetCode/Practice/Two_Sum.cpp | aldew5/Competitive-Programming | fc93723fae739d0b06bcf2dbe3b9274584a79a66 | [
"MIT"
] | null | null | null | // Aldew
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
bool run = true;
for (int i = 0; i < nums.size(); i++){
for (int j = i + 1; j < nums.size(); j++){
if (nums[i] + nums[j] == target){
ans = {i, j};
run = false;
break;
}
}
if (!run) break;
}
return ans;
}
};
| 22.545455 | 55 | 0.354839 | [
"vector"
] |
d99a1721f3a30d8125fe7582d2978c21e848ead7 | 13,022 | cpp | C++ | media_driver/linux/ult/ult_app/test_data_decode.cpp | ashakhno/media-driver | 79c20b78a539afdb55b5fd0006e959f92c12fa64 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | 660 | 2017-11-21T15:55:52.000Z | 2022-03-31T06:31:00.000Z | media_driver/linux/ult/ult_app/test_data_decode.cpp | ashakhno/media-driver | 79c20b78a539afdb55b5fd0006e959f92c12fa64 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | 1,070 | 2017-12-01T00:26:10.000Z | 2022-03-31T17:55:26.000Z | media_driver/linux/ult/ult_app/test_data_decode.cpp | ashakhno/media-driver | 79c20b78a539afdb55b5fd0006e959f92c12fa64 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | 309 | 2017-11-30T08:34:09.000Z | 2022-03-30T18:52:07.000Z | /*
* Copyright (c) 2018, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "test_data_decode.h"
using namespace std;
DecBufHEVC::DecBufHEVC()
{
m_pps = make_shared<VAPictureParameterBufferHEVC>();
memset(m_pps.get(), 0, sizeof(VAPictureParameterBufferHEVC));
for (auto i = 0; i < 15; i++)
{
m_pps->ReferenceFrames[i].picture_id = 0xffffffff;
m_pps->ReferenceFrames[i].flags = 0x1;
}
m_pps->pic_width_in_luma_samples = 0x40;
m_pps->pic_height_in_luma_samples = 0x40;
m_pps->pic_fields.value = 0x20441;
m_pps->sps_max_dec_pic_buffering_minus1 = 0x3;
m_pps->pcm_sample_bit_depth_luma_minus1 = 0xff;
m_pps->pcm_sample_bit_depth_chroma_minus1 = 0xff;
m_pps->log2_diff_max_min_luma_coding_block_size = 0x2;
m_pps->log2_diff_max_min_transform_block_size = 0x3;
m_pps->log2_min_pcm_luma_coding_block_size_minus3 = 0xfd;
m_pps->max_transform_hierarchy_depth_intra = 0x2;
m_pps->max_transform_hierarchy_depth_inter = 0x2;
m_pps->slice_parsing_fields.value = 0x3907;
m_pps->log2_max_pic_order_cnt_lsb_minus4 = 0x2;
m_pps->num_short_term_ref_pic_sets = 0x4;
m_pps->num_ref_idx_l0_default_active_minus1 = 0x2;
m_slc = make_shared<VASliceParameterBufferHEVC>();
memset(m_slc.get(), 0, sizeof(VASliceParameterBufferHEVC));
m_slc->slice_data_size = 0x10;
m_slc->slice_data_byte_offset = 0x7;
for (auto i = 0; i < 15; i++)
{
m_slc->RefPicList[0][i] = 0xff;
m_slc->RefPicList[1][i] = 0xff;
}
m_slc->LongSliceFlags.value = 0x1009;
m_slc->collocated_ref_idx = 0xff;
m_slc->num_ref_idx_l0_active_minus1 = 0xff;
m_slc->num_ref_idx_l1_active_minus1 = 0xff;
m_slc->five_minus_max_num_merge_cand = 0x5;
m_bitstream.assign({
0x00, 0x00, 0x01, 0x26, 0x01, 0xaf, 0x1d, 0x80, 0xa3, 0xf3, 0xe6, 0x0b, 0x57, 0xd0, 0x9f, 0xf9});
}
DecBufAVC::DecBufAVC()
{
m_pps = make_shared<VAPictureParameterBufferH264>();
memset(m_pps.get(), 0, sizeof(VAPictureParameterBufferH264));
m_pps->CurrPic.flags = 0x8;
for (auto i = 0; i < 16; i++)
{
m_pps->ReferenceFrames[i].picture_id = 0xffffffff;
m_pps->ReferenceFrames[i].flags = 0x1;
}
m_pps->picture_width_in_mbs_minus1 = 0x27;
m_pps->picture_height_in_mbs_minus1 = 0x1d;
m_pps->num_ref_frames = 0x2;
m_pps->seq_fields.value = 0x451;
m_pps->pic_fields.value = 0x519;
m_slc = make_shared<VASliceParameterBufferH264>();
memset(m_slc.get(), 0, sizeof(VASliceParameterBufferH264));
m_slc->slice_data_size = 0x10;
m_slc->slice_data_bit_offset = 0x24;
m_slc->slice_type = 0x2;
for (auto i = 0; i < 32; i++)
{
m_slc->RefPicList0[i].picture_id = 0xffffffff;
m_slc->RefPicList0[i].flags = 0x1;
m_slc->RefPicList1[i].picture_id = 0xffffffff;
m_slc->RefPicList1[i].flags = 0x1;
}
m_bitstream.assign({
0x00, 0x00, 0x01, 0x02, 0x01, 0xd0, 0x11, 0xff, 0xd4, 0x43, 0x02, 0x0e, 0x40, 0x92, 0xf9, 0x84});
}
DecTestDataHEVC::DecTestDataHEVC(FeatureID testFeatureID, bool bInShortFormat)
{
m_bShortFormat = bInShortFormat;
m_picWidth = 64;
m_picHeight = 64;
m_surfacesNum = 32;
m_featureId = testFeatureID;
m_confAttrib.resize(1);
m_confAttrib[0].type = VAConfigAttribDecSliceMode;
m_confAttrib[0].value = (m_bShortFormat) ? VA_DEC_SLICE_MODE_BASE:VA_DEC_SLICE_MODE_NORMAL;
m_resources.resize(m_surfacesNum);
InitCompBuffers();
vector<DecFrameDataHEVC> ¤tArray = (m_bShortFormat) ? m_frameArray : m_frameArrayLong;
m_num_frames = currentArray.size();
m_compBufs.resize(m_num_frames);
for (uint32_t i = 0; i < m_num_frames; i++) // Set for each frame
{
m_compBufs[i].resize(3);
// Need one Picture Parameters for all the slices.
m_compBufs[i][0] = { VAPictureParameterBufferType, (uint32_t)currentArray[i].picParam.size(), ¤tArray[i].picParam[0], 0 };
// Due to driver limiation, we just send all the slice data in one buffer.
m_compBufs[i][1] = { VASliceParameterBufferType , (uint32_t)currentArray[i].slcParam.size(), ¤tArray[i].slcParam[0], 0 };
m_compBufs[i][2] = { VASliceDataBufferType , (uint32_t)currentArray[i].bsData.size() , ¤tArray[i].bsData[0] , 0 };
}
}
DecTestDataAVC::DecTestDataAVC(FeatureID testFeatureID, bool bInShortFormat)
{
m_bShortFormat = bInShortFormat;
m_picWidth = 64;
m_picHeight = 64;
m_surfacesNum = 32;
m_featureId = testFeatureID;
m_confAttrib.resize(1);
m_confAttrib[0].type = VAConfigAttribDecSliceMode;
m_confAttrib[0].value = (m_bShortFormat) ? VA_DEC_SLICE_MODE_BASE:VA_DEC_SLICE_MODE_NORMAL;
m_resources.resize(m_surfacesNum);
InitCompBuffers();
vector<DecFrameDataAVC> ¤tArray = m_bShortFormat ? m_frameArray : m_frameArrayLong;
m_num_frames = currentArray.size();
m_compBufs.resize(m_num_frames);
for (uint32_t i = 0; i < m_num_frames; i++) // Set for each frame
{
m_compBufs[i].resize(3);
// Need one Picture Parameters for all the slices.
m_compBufs[i][0] = { VAPictureParameterBufferType, (uint32_t)currentArray[i].picParam.size(), ¤tArray[i].picParam[0], 0 };
// Due to driver limiation, we just send all the slice data in one buffer.
m_compBufs[i][1] = { VASliceParameterBufferType , (uint32_t)currentArray[i].slcParam.size(), ¤tArray[i].slcParam[0], 0 };
m_compBufs[i][2] = { VASliceDataBufferType , (uint32_t)currentArray[i].bsData.size() , ¤tArray[i].bsData[0] , 0 };
}
}
void DecTestDataHEVC::InitCompBuffers()
{
m_frameArrayLong.resize(DEC_FRAME_NUM);
m_pBufs = make_shared<DecBufHEVC>();
for (auto i = 0; i < DEC_FRAME_NUM; i++)
{
m_frameArrayLong[i].picParam.assign((char*)m_pBufs->GetPpsBuf(), (char*)m_pBufs->GetPpsBuf() + m_pBufs->GetPpsSize());
m_frameArrayLong[i].slcParam.assign((char*)m_pBufs->GetSlcBuf(), (char*)m_pBufs->GetSlcBuf() + m_pBufs->GetSlcSize());
m_frameArrayLong[i].bsData.assign((char*)m_pBufs->GetBsBuf() , (char*)m_pBufs->GetBsBuf() + m_pBufs->GetBsSize());
}
}
void DecTestDataAVC::InitCompBuffers()
{
m_frameArrayLong.resize(DEC_FRAME_NUM);
m_pBufs = make_shared<DecBufAVC>();
for (auto i = 0; i < DEC_FRAME_NUM; i++)
{
m_frameArrayLong[i].picParam.assign((char*)m_pBufs->GetPpsBuf(), (char*)m_pBufs->GetPpsBuf() + m_pBufs->GetPpsSize());
m_frameArrayLong[i].slcParam.assign((char*)m_pBufs->GetSlcBuf(), (char*)m_pBufs->GetSlcBuf() + m_pBufs->GetSlcSize());
m_frameArrayLong[i].bsData.assign((char*)m_pBufs->GetBsBuf() , (char*)m_pBufs->GetBsBuf() + m_pBufs->GetBsSize());
}
}
void DecTestDataHEVC::UpdateCompBuffers(int frameId)
{
auto ¤tArray = (m_bShortFormat) ? m_frameArray : m_frameArrayLong;
auto *pps = (VAPictureParameterBufferHEVC *)¤tArray[frameId].picParam[0];
auto *slc = (VASliceParameterBufferHEVC *)¤tArray[frameId].slcParam[0];
auto &bitstream = currentArray[frameId].bsData;
pps->CurrPic.picture_id = m_resources[frameId];
switch (frameId)
{
case 1:
pps->ReferenceFrames[0].picture_id = m_resources[0];
pps->CurrPic.pic_order_cnt = 0x2;
pps->ReferenceFrames[0].flags = 0x10;
pps->slice_parsing_fields.value = 0x107;
pps->st_rps_bits = 0x9;
slc->slice_data_byte_offset = 0x9;
slc->RefPicList[0][0] = 0;
slc->RefPicList[1][0] = 0;
slc->LongSliceFlags.value = 0x1401;
slc->collocated_ref_idx = 0;
slc->num_ref_idx_l0_active_minus1 = 0;
slc->num_ref_idx_l1_active_minus1 = 0;
slc->five_minus_max_num_merge_cand = 0;
bitstream.assign({
0x00, 0x00, 0x01, 0x02, 0x01, 0xd0, 0x09, 0x7e, 0x10, 0xc2, 0x0e, 0xc0, 0xfd, 0xb5, 0xce, 0x30});
break;
case 2:
pps->ReferenceFrames[0].picture_id = m_resources[0];
pps->ReferenceFrames[1].picture_id = m_resources[1];
pps->CurrPic.pic_order_cnt = 0x1;
pps->ReferenceFrames[0].flags = 0x10;
pps->slice_parsing_fields.value = 0x107;
pps->st_rps_bits = 0xa;
pps->ReferenceFrames[1].pic_order_cnt = 0x2;
pps->ReferenceFrames[1].flags = 0x20;
slc->slice_data_byte_offset = 0xa;
slc->RefPicList[0][0] = 0;
slc->RefPicList[1][0] = 0x1;
slc->LongSliceFlags.value = 0x1401;
slc->collocated_ref_idx = 0;
slc->num_ref_idx_l0_active_minus1 = 0;
slc->num_ref_idx_l1_active_minus1 = 0;
slc->five_minus_max_num_merge_cand = 0;
bitstream.assign({
0x00, 0x00, 0x01, 0x02, 0x01, 0xd0, 0x11, 0xff, 0xd4, 0x43, 0x02, 0x0e, 0x40, 0x92, 0xf9, 0x84});
break;
default:
break;
}
}
void DecTestDataAVC::UpdateCompBuffers(int frameId)
{
auto ¤tArray = m_bShortFormat ? m_frameArray : m_frameArrayLong;
auto *pps = (VAPictureParameterBufferH264 *)¤tArray[frameId].picParam[0];
auto *slc = (VASliceParameterBufferH264 *)¤tArray[frameId].slcParam[0];
pps->CurrPic.picture_id = m_resources[frameId];
switch (frameId)
{
case 1:
pps->ReferenceFrames[0].picture_id = m_resources[0];
slc->RefPicList0[0].picture_id = m_resources[0];
slc->RefPicList1[0].picture_id = m_resources[0];
pps->CurrPic.frame_idx = 0x1;
pps->CurrPic.TopFieldOrderCnt = 0x6;
pps->CurrPic.BottomFieldOrderCnt = 0x6;
pps->ReferenceFrames[0].flags = 0x8;
pps->frame_num = 0x1;
slc->slice_data_bit_offset = 0x23;
slc->slice_type = 0;
slc->RefPicList0[0].flags = 0x8;
break;
case 2:
pps->ReferenceFrames[0].picture_id = m_resources[0];
pps->ReferenceFrames[1].picture_id = m_resources[1];
slc->RefPicList0[0].picture_id = m_resources[0];
slc->RefPicList1[0].picture_id = m_resources[1];
pps->CurrPic.frame_idx = 0x2;
pps->CurrPic.flags = 0;
pps->CurrPic.TopFieldOrderCnt = 0x2;
pps->CurrPic.BottomFieldOrderCnt = 0x2;
pps->ReferenceFrames[1].frame_idx = 0x1;
pps->ReferenceFrames[1].flags = 0x8;
pps->ReferenceFrames[1].TopFieldOrderCnt = 0x6;
pps->ReferenceFrames[1].BottomFieldOrderCnt = 0x6;
pps->pic_fields.value = 0x119;
pps->frame_num = 0x2;
slc->slice_data_bit_offset = 0x24;
slc->slice_type = 0x1;
slc->direct_spatial_mv_pred_flag = 0x1;
slc->RefPicList0[0].flags = 0x8;
slc->RefPicList1[0].frame_idx = 0x1;
slc->RefPicList1[0].flags = 0x8;
slc->RefPicList1[0].TopFieldOrderCnt = 0x6;
slc->RefPicList1[0].BottomFieldOrderCnt = 0x6;
break;
default:
break;
}
}
| 44.443686 | 136 | 0.617493 | [
"vector"
] |
d99e88737efcc240e7c2516e1bed1b05f9486e2d | 8,756 | cc | C++ | examples/NUCLEO-F429ZI/udp-server/Core/Src/main.cc | PetroShevchenko/libcoapcpp | ab5fdadd01f25e1c1f132fdeb96bb47ffa8119ad | [
"Apache-2.0"
] | null | null | null | examples/NUCLEO-F429ZI/udp-server/Core/Src/main.cc | PetroShevchenko/libcoapcpp | ab5fdadd01f25e1c1f132fdeb96bb47ffa8119ad | [
"Apache-2.0"
] | null | null | null | examples/NUCLEO-F429ZI/udp-server/Core/Src/main.cc | PetroShevchenko/libcoapcpp | ab5fdadd01f25e1c1f132fdeb96bb47ffa8119ad | [
"Apache-2.0"
] | null | null | null | #include <string.h>
#include "main.h"
#include "cmsis_os.h"
#include "log.h"
#include "lwip.h"
#include "dhcp.h"
#include "udp_server.hh"
#include "command.hh"
#ifndef DHCP_STATE_BOUND
#define DHCP_STATE_BOUND 10
#endif
#define UDP_PORT_NUM 5555UL
using namespace std;
void Error_Handler(void);
int main(void);
osThreadAttr_t IpAssignerTask_attributes;
osThreadAttr_t UdpServerTask_attributes;
RTC_HandleTypeDef hrtc;
UART_HandleTypeDef huart3;
PCD_HandleTypeDef hpcd_USB_OTG_FS;
osThreadId_t IpAssignerTaskHandle;
osThreadId_t UdpServerTaskHandle;
void SystemClock_Config(void);
void StartIpAssignerTask(void *argument);
void StartUdpServerTask(void *argument);
static void GPIO_Init(void);
static void USART3_UART_Init(void);
static void USB_OTG_FS_PCD_Init(void);
static void RTC_Init(void);
static void SetThreadAttributes(
osThreadAttr_t * attr,
const char *name,
uint32_t stack_size,
osPriority_t prio
);
static void GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, LD1_Pin|LD3_Pin|LD2_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(USB_PowerSwitchOn_GPIO_Port, USB_PowerSwitchOn_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : USER_Btn_Pin */
GPIO_InitStruct.Pin = USER_Btn_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(USER_Btn_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : LD1_Pin LD3_Pin LD2_Pin */
GPIO_InitStruct.Pin = LD1_Pin|LD3_Pin|LD2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : USB_PowerSwitchOn_Pin */
GPIO_InitStruct.Pin = USB_PowerSwitchOn_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(USB_PowerSwitchOn_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : USB_OverCurrent_Pin */
GPIO_InitStruct.Pin = USB_OverCurrent_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(USB_OverCurrent_GPIO_Port, &GPIO_InitStruct);
}
static void USART3_UART_Init(void)
{
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
}
static void USB_OTG_FS_PCD_Init(void)
{
hpcd_USB_OTG_FS.Instance = USB_OTG_FS;
hpcd_USB_OTG_FS.Init.dev_endpoints = 4;
hpcd_USB_OTG_FS.Init.speed = PCD_SPEED_FULL;
hpcd_USB_OTG_FS.Init.dma_enable = DISABLE;
hpcd_USB_OTG_FS.Init.phy_itface = PCD_PHY_EMBEDDED;
hpcd_USB_OTG_FS.Init.Sof_enable = ENABLE;
hpcd_USB_OTG_FS.Init.low_power_enable = DISABLE;
hpcd_USB_OTG_FS.Init.lpm_enable = DISABLE;
hpcd_USB_OTG_FS.Init.vbus_sensing_enable = ENABLE;
hpcd_USB_OTG_FS.Init.use_dedicated_ep1 = DISABLE;
if (HAL_PCD_Init(&hpcd_USB_OTG_FS) != HAL_OK)
{
Error_Handler();
}
}
static void RTC_Init(void)
{
RTC_TimeTypeDef sTime = {0};
RTC_DateTypeDef sDate = {0};
hrtc.Instance = RTC;
hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
hrtc.Init.AsynchPrediv = 127;
hrtc.Init.SynchPrediv = 255;
hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
sTime.Hours = 0;
sTime.Minutes = 0;
sTime.Seconds = 0;
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
sDate.WeekDay = RTC_WEEKDAY_MONDAY;
sDate.Month = RTC_MONTH_JANUARY;
sDate.Date = 1;
sDate.Year = 0;
if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
}
static void SetThreadAttributes(
osThreadAttr_t * attr,
const char *name,
uint32_t stack_size,
osPriority_t prio
)
{
memset(attr, 0, sizeof(osThreadAttr_t));
attr->name = name;
attr->stack_size = stack_size;
attr->priority = prio;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
GPIO_Init();
USART3_UART_Init();
USB_OTG_FS_PCD_Init();
RTC_Init();
LWIP_Init();
NVIC_SetPriorityGrouping(0);
osKernelInitialize();
SetThreadAttributes(
&IpAssignerTask_attributes,
"IpAssignerTask",
128 * 4,
osPriorityNormal
);
SetThreadAttributes(
&UdpServerTask_attributes,
"UdpServerTask",
1024 * 4,
osPriorityLow
);
init_log();
IpAssignerTaskHandle = osThreadNew(StartIpAssignerTask, NULL, &IpAssignerTask_attributes);
UdpServerTaskHandle = osThreadNew(StartUdpServerTask, NULL, &UdpServerTask_attributes);
osStatus_t status = osKernelStart();
if ( status != osOK)
{
LOG("osKernelStart() returned error %d", status);
}
while(1) ;
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 4;
RCC_OscInitStruct.PLL.PLLN = 168;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
}
void StartIpAssignerTask(void *argument)
{
struct dhcp *dhcp;
char msg[16];
bool dhcp_bound_flag = false;
uint32_t offered_ip = 0;
(void)argument;
for(;;)
{
dhcp = netif_dhcp_data(lwip_get_netif());
if (dhcp->state == DHCP_STATE_BOUND && !dhcp_bound_flag)
{
dhcp_bound_flag = true;
offered_ip = ip4_addr_get_u32(&dhcp->offered_ip_addr);
snprintf(msg, sizeof(msg), "%03lu.%03lu.%03lu.%03lu",
(offered_ip)&0xFF, (offered_ip >> 8)&0xFF, (offered_ip >> 16)&0xFF, (offered_ip >> 24)&0xFF);
LOG("IP address assigned by DHCP: %s",msg);
}
osDelay(1000);
}
}
void StartUdpServerTask(void *argument)
{
(void)argument;
error_code ec;
static UdpServer server(UDP_PORT_NUM, ec, true);
if (ec.value())
{
LOG("Cannot create UdpServer object: %s", ec.message().c_str());
}
osDelay(5000);
LOG("server object created");
server.init(ec);
if (ec.value())
{
LOG("server.init() error: %s", ec.message().c_str());
}
LOG("set_received_packed_handler_callback");
server.set_received_packed_handler_callback(static_cast<ReceivedPacketHandlerCallback>(command_handler));
LOG("start");
server.start();
LOG("process2");
server.process2();
while(true)
{
osDelay(1);
}
}
void Error_Handler(void)
{
__disable_irq();
LOG("Error_Handler");
while (1) ;
}
extern "C" int __io_putchar(int ch)
{
HAL_UART_Transmit(&huart3, (uint8_t *)&ch, sizeof(uint8_t), TRANSMIT_TIMEOUT);
return ch;
}
extern "C" void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM1) {
HAL_IncTick();
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
LOG("assert_failed");
}
#endif /* USE_FULL_ASSERT */
| 25.306358 | 106 | 0.752855 | [
"object"
] |
d26561cec5287f1bca38e378e46b05036e07d75a | 11,723 | cpp | C++ | src/lab_m1/Tema3/Tema3.cpp | elena0405/Survival-Maze-Game | a79da7a9d066906e263a6897638cc5c5f946cbc4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/lab_m1/Tema3/Tema3.cpp | elena0405/Survival-Maze-Game | a79da7a9d066906e263a6897638cc5c5f946cbc4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/lab_m1/Tema3/Tema3.cpp | elena0405/Survival-Maze-Game | a79da7a9d066906e263a6897638cc5c5f946cbc4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include "lab_m1/Tema3/Tema3.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
using namespace m1;
/*
* To find out more about `FrameStart`, `Update`, `FrameEnd`
* and the order in which they are called, see `world.cpp`.
*/
Tema3::Tema3()
{
}
Tema3::~Tema3()
{
}
void Tema3::Init()
{
generarePodea = false;
{
Mesh* mesh = new Mesh("box");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "box.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("sphere");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "sphere.obj");
meshes[mesh->GetMeshID()] = mesh;
}
// Create a shader program for drawing face polygon with the color of the normal
{
Shader *shader = new Shader("Tema3Shader");
shader->AddShader(PATH_JOIN(window->props.selfDir, SOURCE_PATH::M1, "Tema3", "shaders", "VertexShader.glsl"), GL_VERTEX_SHADER);
shader->AddShader(PATH_JOIN(window->props.selfDir, SOURCE_PATH::M1, "Tema3", "shaders", "FragmentShader.glsl"), GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
// Light & material properties
{
lightPosition = glm::vec3(0, 1, 1);
materialShininess = 30;
materialKd = 0.5;
materialKs = 0.5;
materialKe = 0.5;
}
}
void Tema3::FrameStart()
{
// Clears the color buffer (using the previously set color) and depth buffer
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::ivec2 resolution = window->GetResolution();
// Sets the screen area where to draw
glViewport(0, 0, resolution.x, resolution.y);
}
void Tema3::GenerarePodea() {
glm::vec3 pozitieCurenta = glm::vec3(-2.0f, 0.0f, -2.0f);
float coltStangaJosPodea = pozitieCurenta.z;
glm::vec3 culoare;
for (float i = 0; i < 8; i++) {
for (float j = 0; j < 8; j++) {
culoare = glm::vec3(rand() % 2, rand() % 2, rand() % 2);
if (culoare.x != 0 && culoare.y != 0 && culoare.z != 0) {
culoriPodea.push_back(culoare);
}
else {
while (culoare.x == 0 && culoare.y == 0 && culoare.z == 0) {
culoare = glm::vec3(rand() % 2, rand() % 2, rand() % 2);
}
culoriPodea.push_back(culoare);
}
pozitieCurenta = glm::vec3(pozitieCurenta.x, pozitieCurenta.y, coltStangaJosPodea + j * 0.5f);
pozitiiPodea.push_back(pozitieCurenta);
}
pozitieCurenta = glm::vec3(pozitieCurenta.x + 0.5f, pozitieCurenta.y, coltStangaJosPodea);
}
}
void Tema3::CrearePodea() {
for (int i = 0; i < pozitiiPodea.size(); i++) {
PodeaRing patrat = PodeaRing(pozitiiPodea[i].x, pozitiiPodea[i].y, pozitiiPodea[i].z, 1, 0, 1, glm::mat4(1));
patrat.modelMatrix *= glm::scale(patrat.modelMatrix, glm::vec3(patrat.scaleX, patrat.scaleY, patrat.scaleZ));
patrat.modelMatrix *= glm::translate(patrat.modelMatrix, glm::vec3(patrat.translateX + 0.25f, patrat.translateY, patrat.translateZ + 0.25f));
RenderSimpleMesh(meshes["box"], shaders["Tema3Shader"], patrat.modelMatrix, culoriPodea[i]);
}
}
void Tema3::GenerarePereteStang() {
glm::vec3 pozitieCurenta = glm::vec3(-1.0f, 0.0f, -1.0f);
float coltStangaJosPereteStang = pozitieCurenta.y;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 5; j++) {
pozitieCurenta = glm::vec3(pozitieCurenta.x, coltStangaJosPereteStang + j * 0.25f, pozitieCurenta.z);
pozitiiPereteStang.push_back(pozitieCurenta);
}
pozitieCurenta = glm::vec3(pozitieCurenta.x, coltStangaJosPereteStang, pozitieCurenta.z + 0.25f);
}
}
void Tema3::CrearePereteStang() {
for (int i = 0; i < pozitiiPereteStang.size(); i++) {
Perete perete = Perete(pozitiiPereteStang[i].x, pozitiiPereteStang[i].y, pozitiiPereteStang[i].z, 0, 1, 1, glm::mat4(1));
perete.modelMatrix *= glm::translate(perete.modelMatrix, glm::vec3(perete.translateX - 1, perete.translateY, perete.translateZ + 0.1f));
perete.modelMatrix *= glm::scale(perete.modelMatrix, glm::vec3(perete.scaleX, perete.scaleY, perete.scaleZ));
RenderSimpleMesh(meshes["box"], shaders["Tema3Shader"], perete.modelMatrix, glm::vec3(0, 0, 0));
}
}
void Tema3::GenerarePereteDrept() {
glm::vec3 pozitieCurenta = glm::vec3(3.0f, 0.0f, -1.0f);
float coltStangaJosPereteStang = pozitieCurenta.y;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 5; j++) {
pozitieCurenta = glm::vec3(pozitieCurenta.x, coltStangaJosPereteStang + j * 0.25f, pozitieCurenta.z);
pozitiiPereteDrept.push_back(pozitieCurenta);
}
pozitieCurenta = glm::vec3(pozitieCurenta.x, coltStangaJosPereteStang, pozitieCurenta.z + 0.25f);
}
}
void Tema3::CrearePereteDrept() {
for (int i = 0; i < pozitiiPereteDrept.size(); i++) {
Perete perete = Perete(pozitiiPereteDrept[i].x, pozitiiPereteDrept[i].y, pozitiiPereteDrept[i].z, 0, 1, 1, glm::mat4(1));
perete.modelMatrix *= glm::translate(perete.modelMatrix, glm::vec3(perete.translateX - 1, perete.translateY, perete.translateZ + 0.1f));
perete.modelMatrix *= glm::scale(perete.modelMatrix, glm::vec3(perete.scaleX, perete.scaleY, perete.scaleZ));
RenderSimpleMesh(meshes["box"], shaders["Tema3Shader"], perete.modelMatrix, glm::vec3(0, 0, 0));
}
}
void Tema3::GenerarePereteSpate() {
glm::vec3 pozitieCurenta = glm::vec3(-1.0f, 0.0f, -2.0f);
float coltStangaJosPereteStang = pozitieCurenta.y;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 5; j++) {
pozitieCurenta = glm::vec3(pozitieCurenta.x, coltStangaJosPereteStang + j * 0.25f, pozitieCurenta.z);
PozitiiPereteSpate.push_back(pozitieCurenta);
}
pozitieCurenta = glm::vec3(pozitieCurenta.x + 0.25f, coltStangaJosPereteStang, pozitieCurenta.z);
}
}
void Tema3::CrearePereteSpate() {
for (int i = 0; i < PozitiiPereteSpate.size(); i++) {
Perete perete = Perete(PozitiiPereteSpate[i].x, PozitiiPereteSpate[i].y, PozitiiPereteSpate[i].z, 1, 1, 0, glm::mat4(1));
perete.modelMatrix *= glm::translate(perete.modelMatrix, glm::vec3(perete.translateX + 0.12f, perete.translateY, perete.translateZ));
perete.modelMatrix *= glm::scale(perete.modelMatrix, glm::vec3(perete.scaleX, perete.scaleY, perete.scaleZ));
RenderSimpleMesh(meshes["box"], shaders["Tema3Shader"], perete.modelMatrix, glm::vec3(0, 0, 0));
}
}
void Tema3::Update(float deltaTimeSeconds)
{
// Render the point light in the scene
{
glm::mat4 modelMatrix = glm::mat4(1);
modelMatrix = glm::translate(modelMatrix, lightPosition);
modelMatrix = glm::scale(modelMatrix, glm::vec3(0.3f));
RenderMesh(meshes["sphere"], shaders["Simple"], modelMatrix);
}
if (generarePodea == false) {
GenerarePodea();
GenerarePereteStang();
GenerarePereteDrept();
GenerarePereteSpate();
generarePodea = true;
}
CrearePodea();
CrearePereteStang();
CrearePereteDrept();
CrearePereteSpate();
}
void Tema3::FrameEnd()
{
DrawCoordinateSystem();
}
void Tema3::RenderSimpleMesh(Mesh *mesh, Shader *shader, const glm::mat4 & modelMatrix, const glm::vec3 &color)
{
if (!mesh || !shader || !shader->GetProgramID())
return;
// Render an object using the specified shader and the specified position
glUseProgram(shader->program);
// Set shader uniforms for light & material properties
// Set light position uniform
GLint light_location = glGetUniformLocation(shader->program, "light_position");
glUniform3fv(light_location, 1, glm::value_ptr(lightPosition));
glm::vec3 eyePosition = GetSceneCamera()->m_transform->GetWorldPosition();
// Set eye position (camera position) uniform
GLint eye_location = glGetUniformLocation(shader->program, "eye_position");
glUniform3fv(eye_location, 1, glm::value_ptr(eyePosition));
// Set material property uniforms (shininess, kd, ks, object color)
// Set material shininess
GLint material_location = glGetUniformLocation(shader->program, "material_shininess");
glUniform1i(material_location, materialShininess);
// Set material_kd
GLint kd_location = glGetUniformLocation(shader->program, "material_kd");
glUniform1f(kd_location, materialKd);
// Set material_ks
GLint ks_location = glGetUniformLocation(shader->program, "material_ks");
glUniform1f(ks_location, materialKs);
// Set material_ke
GLint ke_location = glGetUniformLocation(shader->program, "material_ke");
glUniform1f(ke_location, materialKe);
// Set color
GLint color_location = glGetUniformLocation(shader->program, "object_color");
glUniform3fv(color_location, 1, glm::value_ptr(color));
// Bind model matrix
GLint loc_model_matrix = glGetUniformLocation(shader->program, "Model");
glUniformMatrix4fv(loc_model_matrix, 1, GL_FALSE, glm::value_ptr(modelMatrix));
// Bind view matrix
glm::mat4 viewMatrix = GetSceneCamera()->GetViewMatrix();
int loc_view_matrix = glGetUniformLocation(shader->program, "View");
glUniformMatrix4fv(loc_view_matrix, 1, GL_FALSE, glm::value_ptr(viewMatrix));
// Bind projection matrix
glm::mat4 projectionMatrix = GetSceneCamera()->GetProjectionMatrix();
int loc_projection_matrix = glGetUniformLocation(shader->program, "Projection");
glUniformMatrix4fv(loc_projection_matrix, 1, GL_FALSE, glm::value_ptr(projectionMatrix));
// Draw the object
glBindVertexArray(mesh->GetBuffers()->m_VAO);
glDrawElements(mesh->GetDrawMode(), static_cast<int>(mesh->indices.size()), GL_UNSIGNED_INT, 0);
}
/*
* These are callback functions. To find more about callbacks and
* how they behave, see `input_controller.h`.
*/
void Tema3::OnInputUpdate(float deltaTime, int mods)
{
float speed = 2;
if (!window->MouseHold(GLFW_MOUSE_BUTTON_RIGHT))
{
glm::vec3 up = glm::vec3(0, 1, 0);
glm::vec3 right = GetSceneCamera()->m_transform->GetLocalOXVector();
glm::vec3 forward = GetSceneCamera()->m_transform->GetLocalOZVector();
forward = glm::normalize(glm::vec3(forward.x, 0, forward.z));
// Control light position using on W, A, S, D, E, Q
if (window->KeyHold(GLFW_KEY_W)) lightPosition -= forward * deltaTime * speed;
if (window->KeyHold(GLFW_KEY_A)) lightPosition -= right * deltaTime * speed;
if (window->KeyHold(GLFW_KEY_S)) lightPosition += forward * deltaTime * speed;
if (window->KeyHold(GLFW_KEY_D)) lightPosition += right * deltaTime * speed;
if (window->KeyHold(GLFW_KEY_E)) lightPosition += up * deltaTime * speed;
if (window->KeyHold(GLFW_KEY_Q)) lightPosition -= up * deltaTime * speed;
}
}
void Tema3::OnKeyPress(int key, int mods)
{
// Add key press event
}
void Tema3::OnKeyRelease(int key, int mods)
{
// Add key release event
}
void Tema3::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// Add mouse move event
}
void Tema3::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button press event
}
void Tema3::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button release event
}
void Tema3::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
}
void Tema3::OnWindowResize(int width, int height)
{
}
| 34.581121 | 149 | 0.658364 | [
"mesh",
"render",
"object",
"vector",
"model"
] |
d26a293c5f9c3f5d85f13e32ce0b626b07644ae8 | 22,945 | cxx | C++ | main/desktop/source/deployment/registry/dp_registry.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/desktop/source/deployment/registry/dp_registry.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/desktop/source/deployment/registry/dp_registry.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_registry.hrc"
#include "dp_misc.h"
#include "dp_resource.h"
#include "dp_interact.h"
#include "dp_ucb.h"
#include "osl/diagnose.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/uri.hxx"
#include "cppuhelper/compbase2.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "comphelper/sequence.hxx"
#include "ucbhelper/content.hxx"
#include "com/sun/star/uno/DeploymentException.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/WrappedTargetRuntimeException.hpp"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include "com/sun/star/lang/XSingleServiceFactory.hpp"
#include "com/sun/star/util/XUpdatable.hpp"
#include "com/sun/star/container/XContentEnumerationAccess.hpp"
#include "com/sun/star/deployment/PackageRegistryBackend.hpp"
#include <hash_map>
#include <set>
#include <hash_set>
#include <memory>
using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;
namespace dp_registry {
namespace backend {
namespace bundle {
Reference<deployment::XPackageRegistry> create(
Reference<deployment::XPackageRegistry> const & xRootRegistry,
OUString const & context, OUString const & cachePath, bool readOnly,
Reference<XComponentContext> const & xComponentContext );
}
}
namespace {
typedef ::cppu::WeakComponentImplHelper2<
deployment::XPackageRegistry, util::XUpdatable > t_helper;
//==============================================================================
class PackageRegistryImpl : private MutexHolder, public t_helper
{
struct ci_string_hash {
::std::size_t operator () ( OUString const & str ) const {
return str.toAsciiLowerCase().hashCode();
}
};
struct ci_string_equals {
bool operator () ( OUString const & str1, OUString const & str2 ) const{
return str1.equalsIgnoreAsciiCase( str2 );
}
};
typedef ::std::hash_map<
OUString, Reference<deployment::XPackageRegistry>,
ci_string_hash, ci_string_equals > t_string2registry;
typedef ::std::hash_map<
OUString, OUString,
ci_string_hash, ci_string_equals > t_string2string;
typedef ::std::set<
Reference<deployment::XPackageRegistry> > t_registryset;
t_string2registry m_mediaType2backend;
t_string2string m_filter2mediaType;
t_registryset m_ambiguousBackends;
t_registryset m_allBackends;
::std::vector< Reference<deployment::XPackageTypeInfo> > m_typesInfos;
void insertBackend(
Reference<deployment::XPackageRegistry> const & xBackend );
protected:
inline void check();
virtual void SAL_CALL disposing();
virtual ~PackageRegistryImpl();
PackageRegistryImpl() : t_helper( getMutex() ) {}
public:
static Reference<deployment::XPackageRegistry> create(
OUString const & context,
OUString const & cachePath, bool readOnly,
Reference<XComponentContext> const & xComponentContext );
// XUpdatable
virtual void SAL_CALL update() throw (RuntimeException);
// XPackageRegistry
virtual Reference<deployment::XPackage> SAL_CALL bindPackage(
OUString const & url, OUString const & mediaType, sal_Bool bRemoved,
OUString const & identifier, Reference<XCommandEnvironment> const & xCmdEnv )
throw (deployment::DeploymentException,
deployment::InvalidRemovedParameterException,
CommandFailedException,
lang::IllegalArgumentException, RuntimeException);
virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
getSupportedPackageTypes() throw (RuntimeException);
virtual void SAL_CALL packageRemoved(OUString const & url, OUString const & mediaType)
throw (deployment::DeploymentException,
RuntimeException);
};
//______________________________________________________________________________
inline void PackageRegistryImpl::check()
{
::osl::MutexGuard guard( getMutex() );
if (rBHelper.bInDispose || rBHelper.bDisposed) {
throw lang::DisposedException(
OUSTR("PackageRegistry instance has already been disposed!"),
static_cast<OWeakObject *>(this) );
}
}
//______________________________________________________________________________
void PackageRegistryImpl::disposing()
{
// dispose all backends:
t_registryset::const_iterator iPos( m_allBackends.begin() );
t_registryset::const_iterator const iEnd( m_allBackends.end() );
for ( ; iPos != iEnd; ++iPos ) {
try_dispose( *iPos );
}
m_mediaType2backend = t_string2registry();
m_ambiguousBackends = t_registryset();
m_allBackends = t_registryset();
t_helper::disposing();
}
//______________________________________________________________________________
PackageRegistryImpl::~PackageRegistryImpl()
{
}
//______________________________________________________________________________
OUString normalizeMediaType( OUString const & mediaType )
{
::rtl::OUStringBuffer buf;
sal_Int32 index = 0;
for (;;) {
buf.append( mediaType.getToken( 0, '/', index ).trim() );
if (index < 0)
break;
buf.append( static_cast< sal_Unicode >('/') );
}
return buf.makeStringAndClear();
}
//______________________________________________________________________________
void PackageRegistryImpl::packageRemoved(
::rtl::OUString const & url, ::rtl::OUString const & mediaType)
throw (css::deployment::DeploymentException,
css::uno::RuntimeException)
{
const t_string2registry::const_iterator i =
m_mediaType2backend.find(mediaType);
if (i != m_mediaType2backend.end())
{
i->second->packageRemoved(url, mediaType);
}
}
void PackageRegistryImpl::insertBackend(
Reference<deployment::XPackageRegistry> const & xBackend )
{
m_allBackends.insert( xBackend );
typedef ::std::hash_set<OUString, ::rtl::OUStringHash> t_stringset;
t_stringset ambiguousFilters;
const Sequence< Reference<deployment::XPackageTypeInfo> > packageTypes(
xBackend->getSupportedPackageTypes() );
for ( sal_Int32 pos = 0; pos < packageTypes.getLength(); ++pos )
{
Reference<deployment::XPackageTypeInfo> const & xPackageType =
packageTypes[ pos ];
m_typesInfos.push_back( xPackageType );
const OUString mediaType( normalizeMediaType(
xPackageType->getMediaType() ) );
::std::pair<t_string2registry::iterator, bool> mb_insertion(
m_mediaType2backend.insert( t_string2registry::value_type(
mediaType, xBackend ) ) );
if (mb_insertion.second)
{
// add parameterless media-type, too:
sal_Int32 semi = mediaType.indexOf( ';' );
if (semi >= 0) {
m_mediaType2backend.insert(
t_string2registry::value_type(
mediaType.copy( 0, semi ), xBackend ) );
}
const OUString fileFilter( xPackageType->getFileFilter() );
//The package backend shall also be called to determine the mediatype
//(XPackageRegistry.bindPackage) when the URL points to a directory.
const bool bExtension = mediaType.equals(OUSTR("application/vnd.sun.star.package-bundle"));
if (fileFilter.getLength() == 0 ||
fileFilter.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("*.*") ) ||
fileFilter.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("*") ) ||
bExtension)
{
m_ambiguousBackends.insert( xBackend );
}
else
{
sal_Int32 nIndex = 0;
do {
OUString token( fileFilter.getToken( 0, ';', nIndex ) );
if (token.matchAsciiL( RTL_CONSTASCII_STRINGPARAM("*.") ))
token = token.copy( 1 );
if (token.getLength() == 0)
continue;
// mark any further wildcards ambig:
bool ambig = (token.indexOf('*') >= 0 ||
token.indexOf('?') >= 0);
if (! ambig) {
::std::pair<t_string2string::iterator, bool> ins(
m_filter2mediaType.insert(
t_string2string::value_type(
token, mediaType ) ) );
ambig = !ins.second;
if (ambig) {
// filter has already been in: add previously
// added backend to ambig set
const t_string2registry::const_iterator iFind(
m_mediaType2backend.find(
/* media-type of pr. added backend */
ins.first->second ) );
OSL_ASSERT(
iFind != m_mediaType2backend.end() );
if (iFind != m_mediaType2backend.end())
m_ambiguousBackends.insert( iFind->second );
}
}
if (ambig) {
m_ambiguousBackends.insert( xBackend );
// mark filter to be removed later from filters map:
ambiguousFilters.insert( token );
}
}
while (nIndex >= 0);
}
}
#if OSL_DEBUG_LEVEL > 0
else {
::rtl::OUStringBuffer buf;
buf.appendAscii(
RTL_CONSTASCII_STRINGPARAM(
"more than one PackageRegistryBackend for "
"media-type=\"") );
buf.append( mediaType );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\" => ") );
buf.append( Reference<lang::XServiceInfo>(
xBackend, UNO_QUERY_THROW )->
getImplementationName() );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\"!") );
OSL_ENSURE( 0, ::rtl::OUStringToOString(
buf.makeStringAndClear(),
RTL_TEXTENCODING_UTF8 ) );
}
#endif
}
// cut out ambiguous filters:
t_stringset::const_iterator iPos( ambiguousFilters.begin() );
const t_stringset::const_iterator iEnd( ambiguousFilters.end() );
for ( ; iPos != iEnd; ++iPos ) {
m_filter2mediaType.erase( *iPos );
}
}
//______________________________________________________________________________
Reference<deployment::XPackageRegistry> PackageRegistryImpl::create(
OUString const & context,
OUString const & cachePath, bool readOnly,
Reference<XComponentContext> const & xComponentContext )
{
PackageRegistryImpl * that = new PackageRegistryImpl;
Reference<deployment::XPackageRegistry> xRet(that);
// auto-detect all registered package registries:
Reference<container::XEnumeration> xEnum(
Reference<container::XContentEnumerationAccess>(
xComponentContext->getServiceManager(),
UNO_QUERY_THROW )->createContentEnumeration(
OUSTR("com.sun.star.deployment.PackageRegistryBackend") ) );
if (xEnum.is())
{
while (xEnum->hasMoreElements())
{
Any element( xEnum->nextElement() );
Sequence<Any> registryArgs(
cachePath.getLength() == 0 ? 1 : 3 );
registryArgs[ 0 ] <<= context;
if (cachePath.getLength() > 0)
{
Reference<lang::XServiceInfo> xServiceInfo(
element, UNO_QUERY_THROW );
OUString registryCachePath(
makeURL( cachePath,
::rtl::Uri::encode(
xServiceInfo->getImplementationName(),
rtl_UriCharClassPchar,
rtl_UriEncodeIgnoreEscapes,
RTL_TEXTENCODING_UTF8 ) ) );
registryArgs[ 1 ] <<= registryCachePath;
registryArgs[ 2 ] <<= readOnly;
if (! readOnly)
create_folder( 0, registryCachePath,
Reference<XCommandEnvironment>() );
}
Reference<deployment::XPackageRegistry> xBackend;
Reference<lang::XSingleComponentFactory> xFac( element, UNO_QUERY );
if (xFac.is()) {
xBackend.set(
xFac->createInstanceWithArgumentsAndContext(
registryArgs, xComponentContext ), UNO_QUERY );
}
else {
Reference<lang::XSingleServiceFactory> xSingleServiceFac(
element, UNO_QUERY_THROW );
xBackend.set(
xSingleServiceFac->createInstanceWithArguments(
registryArgs ), UNO_QUERY );
}
if (! xBackend.is()) {
throw DeploymentException(
OUSTR("cannot instantiate PackageRegistryBackend service: ")
+ Reference<lang::XServiceInfo>(
element, UNO_QUERY_THROW )->getImplementationName(),
static_cast<OWeakObject *>(that) );
}
that->insertBackend( xBackend );
}
}
// Insert bundle back-end.
// Always register as last, because we want to add extensions also as folders
// and as a default we accept every folder, which was not recognized by the other
// backends.
Reference<deployment::XPackageRegistry> extensionBackend =
::dp_registry::backend::bundle::create(
that, context, cachePath, readOnly, xComponentContext);
that->insertBackend(extensionBackend);
Reference<lang::XServiceInfo> xServiceInfo(
extensionBackend, UNO_QUERY_THROW );
OSL_ASSERT(xServiceInfo.is());
OUString registryCachePath(
makeURL( cachePath,
::rtl::Uri::encode(
xServiceInfo->getImplementationName(),
rtl_UriCharClassPchar,
rtl_UriEncodeIgnoreEscapes,
RTL_TEXTENCODING_UTF8 ) ) );
create_folder( 0, registryCachePath, Reference<XCommandEnvironment>());
#if OSL_DEBUG_LEVEL > 1
// dump tables:
{
t_registryset allBackends;
dp_misc::TRACE("> [dp_registry.cxx] media-type detection:\n\n" );
for ( t_string2string::const_iterator iPos(
that->m_filter2mediaType.begin() );
iPos != that->m_filter2mediaType.end(); ++iPos )
{
::rtl::OUStringBuffer buf;
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("extension \"") );
buf.append( iPos->first );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
"\" maps to media-type \"") );
buf.append( iPos->second );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
"\" maps to backend ") );
const Reference<deployment::XPackageRegistry> xBackend(
that->m_mediaType2backend.find( iPos->second )->second );
allBackends.insert( xBackend );
buf.append( Reference<lang::XServiceInfo>(
xBackend, UNO_QUERY_THROW )
->getImplementationName() );
dp_misc::writeConsole( buf.makeStringAndClear() + OUSTR("\n"));
}
dp_misc::TRACE( "> [dp_registry.cxx] ambiguous backends:\n\n" );
for ( t_registryset::const_iterator iPos(
that->m_ambiguousBackends.begin() );
iPos != that->m_ambiguousBackends.end(); ++iPos )
{
::rtl::OUStringBuffer buf;
buf.append(
Reference<lang::XServiceInfo>(
*iPos, UNO_QUERY_THROW )->getImplementationName() );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(": ") );
const Sequence< Reference<deployment::XPackageTypeInfo> > types(
(*iPos)->getSupportedPackageTypes() );
for ( sal_Int32 pos = 0; pos < types.getLength(); ++pos ) {
Reference<deployment::XPackageTypeInfo> const & xInfo =
types[ pos ];
buf.append( xInfo->getMediaType() );
const OUString filter( xInfo->getFileFilter() );
if (filter.getLength() > 0) {
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" (") );
buf.append( filter );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(")") );
}
if (pos < (types.getLength() - 1))
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
}
dp_misc::TRACE(buf.makeStringAndClear() + OUSTR("\n\n"));
}
allBackends.insert( that->m_ambiguousBackends.begin(),
that->m_ambiguousBackends.end() );
OSL_ASSERT( allBackends == that->m_allBackends );
}
#endif
return xRet;
}
// XUpdatable: broadcast to backends
//______________________________________________________________________________
void PackageRegistryImpl::update() throw (RuntimeException)
{
check();
t_registryset::const_iterator iPos( m_allBackends.begin() );
const t_registryset::const_iterator iEnd( m_allBackends.end() );
for ( ; iPos != iEnd; ++iPos ) {
const Reference<util::XUpdatable> xUpdatable( *iPos, UNO_QUERY );
if (xUpdatable.is())
xUpdatable->update();
}
}
// XPackageRegistry
//______________________________________________________________________________
Reference<deployment::XPackage> PackageRegistryImpl::bindPackage(
OUString const & url, OUString const & mediaType_, sal_Bool bRemoved,
OUString const & identifier, Reference<XCommandEnvironment> const & xCmdEnv )
throw (deployment::DeploymentException, deployment::InvalidRemovedParameterException,
CommandFailedException,
lang::IllegalArgumentException, RuntimeException)
{
check();
OUString mediaType(mediaType_);
if (mediaType.getLength() == 0)
{
::ucbhelper::Content ucbContent;
if (create_ucb_content(
&ucbContent, url, xCmdEnv, false /* no throw */ )
&& !ucbContent.isFolder())
{
OUString title( ucbContent.getPropertyValue(
StrTitle::get() ).get<OUString>() );
for (;;)
{
const t_string2string::const_iterator iFind(
m_filter2mediaType.find(title) );
if (iFind != m_filter2mediaType.end()) {
mediaType = iFind->second;
break;
}
sal_Int32 point = title.indexOf( '.', 1 /* consume . */ );
if (point < 0)
break;
title = title.copy(point);
}
}
}
if (mediaType.getLength() == 0)
{
// try ambiguous backends:
t_registryset::const_iterator iPos( m_ambiguousBackends.begin() );
const t_registryset::const_iterator iEnd( m_ambiguousBackends.end() );
for ( ; iPos != iEnd; ++iPos )
{
try {
return (*iPos)->bindPackage( url, mediaType, bRemoved,
identifier, xCmdEnv );
}
catch (lang::IllegalArgumentException &) {
}
}
throw lang::IllegalArgumentException(
getResourceString(RID_STR_CANNOT_DETECT_MEDIA_TYPE) + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
else
{
// get backend by media-type:
t_string2registry::const_iterator iFind(
m_mediaType2backend.find( normalizeMediaType(mediaType) ) );
if (iFind == m_mediaType2backend.end()) {
// xxx todo: more sophisticated media-type argument parsing...
sal_Int32 q = mediaType.indexOf( ';' );
if (q >= 0) {
iFind = m_mediaType2backend.find(
normalizeMediaType(
// cut parameters:
mediaType.copy( 0, q ) ) );
}
}
if (iFind == m_mediaType2backend.end()) {
throw lang::IllegalArgumentException(
getResourceString(RID_STR_UNSUPPORTED_MEDIA_TYPE) + mediaType,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
return iFind->second->bindPackage( url, mediaType, bRemoved,
identifier, xCmdEnv );
}
}
//______________________________________________________________________________
Sequence< Reference<deployment::XPackageTypeInfo> >
PackageRegistryImpl::getSupportedPackageTypes() throw (RuntimeException)
{
return comphelper::containerToSequence(m_typesInfos);
}
} // anon namespace
//==============================================================================
Reference<deployment::XPackageRegistry> SAL_CALL create(
OUString const & context,
OUString const & cachePath, bool readOnly,
Reference<XComponentContext> const & xComponentContext )
{
return PackageRegistryImpl::create(
context, cachePath, readOnly, xComponentContext );
}
} // namespace dp_registry
| 40.04363 | 103 | 0.591371 | [
"vector"
] |
d26c236dc895fdb9636e173ae22f7f47c9e197ea | 7,353 | cpp | C++ | AudioHub/DeviceList.cpp | 0bmxa/AudioHub | 767794985fd500951ac5f9acd0eb63e80e964a11 | [
"MIT"
] | 1 | 2016-12-21T16:36:40.000Z | 2016-12-21T16:36:40.000Z | AudioHub/DeviceList.cpp | 0bmxa/AudioHub | 767794985fd500951ac5f9acd0eb63e80e964a11 | [
"MIT"
] | null | null | null | AudioHub/DeviceList.cpp | 0bmxa/AudioHub | 767794985fd500951ac5f9acd0eb63e80e964a11 | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2015 Daniel Lindenfelser
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "DeviceList.h"
#include "CADispatchQueue.h"
#include "CACFArray.h"
#include "CACFNumber.h"
#include "CAException.h"
#include "PlugIn.h"
DeviceList::DeviceList()
: mDeviceListMutex(new CAMutex("Hub Device List")) {
}
DeviceList::~DeviceList() {
delete mDeviceListMutex;
mDeviceListMutex = nullptr;
}
void DeviceList::AddDevice(Device *inDevice) {
CAMutex::Locker theLocker(mDeviceListMutex);
if (inDevice != NULL) {
// add it to the object map
CAObjectMap::MapObject(inDevice->GetObjectID(), inDevice);
// Initialize an DeviceInfo to describe the new device
DeviceInfo theDeviceInfo(inDevice->GetObjectID(), inDevice->getDeviceUID());
// put the device info in the list
mDeviceInfoList.push_back(theDeviceInfo);
// activate the device
inDevice->Activate();
}
}
void DeviceList::RemoveDevice(Device *inDevice) {
CAMutex::Locker theLocker(mDeviceListMutex);
// find it in the device list and grab an iterator for it
if (inDevice != NULL) {
bool wasFound = false;
DeviceInfoList::iterator theDeviceIterator = mDeviceInfoList.begin();
while (!wasFound && (theDeviceIterator != mDeviceInfoList.end())) {
if (inDevice->GetObjectID() == theDeviceIterator->mDeviceObjectID) {
wasFound = true;
// deactivate the device
inDevice->Deactivate();
// remove the device from the list
theDeviceIterator->mDeviceObjectID = 0;
mDeviceInfoList.erase(theDeviceIterator);
// and release it
CAObjectMap::ReleaseObject(inDevice);
}
else {
++theDeviceIterator;
}
}
}
}
void DeviceList::RemoveAllDevices() {
CAMutex::Locker theLocker(mDeviceListMutex);
// spin through the device list
for (DeviceInfoList::iterator theDeviceIterator = mDeviceInfoList.begin(); theDeviceIterator != mDeviceInfoList.end(); ++theDeviceIterator) {
// remove the object from the list
AudioObjectID theDeadDeviceObjectID = theDeviceIterator->mDeviceObjectID;
theDeviceIterator->mDeviceObjectID = 0;
CADispatchQueue::GetGlobalSerialQueue().Dispatch(false, ^{
CATry;
// resolve the device ID to an object
CAObjectReleaser<Device> theDeadDevice(CAObjectMap::CopyObjectOfClassByObjectID<Device>(theDeadDeviceObjectID));
if (theDeadDevice.IsValid()) {
// deactivate the device
theDeadDevice->Deactivate();
// and release it
CAObjectMap::ReleaseObject(theDeadDevice);
}
CACatch;
});
}
mDeviceInfoList.clear();
}
AudioObjectID DeviceList::GetDeviceObjectID(UInt32 index) {
CAMutex::Locker theLocker(mDeviceListMutex);
if (index > mDeviceInfoList.size())
return kAudioObjectUnknown;
return mDeviceInfoList[index].mDeviceObjectID;
}
AudioObjectID DeviceList::GetDeviceObjectIDByUUID(CFStringRef uuid) {
CAMutex::Locker theLocker(mDeviceListMutex);
for (UInt32 theDeviceIndex = 0; theDeviceIndex < mDeviceInfoList.size(); ++theDeviceIndex) {
if (CFStringCompare(uuid, mDeviceInfoList[theDeviceIndex].mDeviceUUID, 0) == kCFCompareEqualTo) {
return mDeviceInfoList[theDeviceIndex].mDeviceObjectID;
}
}
return kAudioObjectUnknown;
}
CFPropertyListRef DeviceList::GetSettings() const {
CACFDictionary settings;
CACFArray settingsDevices;
for(const DeviceInfo &deviceInfo : mDeviceInfoList) {
CAObjectReleaser<Device> theDevice(CAObjectMap::CopyObjectOfClassByObjectID<Device>(deviceInfo.mDeviceObjectID));
ThrowIf(!theDevice.IsValid(), CAException(kAudioHardwareBadObjectError), "GetSettings: unknown device");
CACFDictionary deviceSettings;
deviceSettings.AddCFType(kAudioHubSettingsKeyDeviceName, theDevice->GetDeviceName());
deviceSettings.AddCFType(kAudioHubSettingsKeyDeviceUID, theDevice->getDeviceUID());
deviceSettings.AddUInt32(kAudioHubSettingsKeyDeviceChannels, theDevice->GetChannels());
settingsDevices.AppendDictionary(deviceSettings.CopyCFDictionary());
}
settings.AddArray(kAudioHubSettingsKeyDevices, settingsDevices.CopyCFArray());
return settings.CopyCFDictionary();
}
bool DeviceList::SetSettings(CFPropertyListRef propertyList) {
if (CFGetTypeID(propertyList) != CFDictionaryGetTypeID())
return false;
CACFDictionary settings((CFDictionaryRef)propertyList, false);
CACFArray settingsDevices;
settings.GetCACFArray(kAudioHubSettingsKeyDevices, settingsDevices);
if (!settingsDevices.IsValid())
return false;
RemoveAllDevices();
for (int i = 0; i < settingsDevices.GetNumberItems(); ++i) {
CACFDictionary device;
settingsDevices.GetCACFDictionary(i, device);
if (device.IsValid()) {
AddDevice(device.AsPropertyList());
}
}
return true;
}
bool DeviceList::AddDevice(CFPropertyListRef config) {
if (CFGetTypeID(config) != CFDictionaryGetTypeID())
return false;
CACFDictionary device((CFDictionaryRef)config, true);
CACFString deviceUUID;
device.GetCACFString(kAudioHubSettingsKeyDeviceUID, deviceUUID);
if (deviceUUID.IsValid()) {
CACFString deviceName;
device.GetCACFString(kAudioHubSettingsKeyDeviceName, deviceName);
if (deviceName.IsValid()) {
UInt32 deviceChannels = 0;
device.GetUInt32(kAudioHubSettingsKeyDeviceChannels, deviceChannels);
if (deviceChannels > 0 && deviceChannels < kAudioHubMaximumDeviceChannels) {
auto theDevice = new Device(CAObjectMap::GetNextObjectID(), (SInt16)deviceChannels);
theDevice->setDeviceName(deviceName.CopyCFString());
theDevice->setDeviceUID(deviceUUID.CopyCFString());
AddDevice(theDevice);
return true;
}
}
}
return false;
}
UInt32 DeviceList::NumDevices() {
return UInt32(mDeviceInfoList.size());
} | 37.707692 | 145 | 0.688154 | [
"object"
] |
d26ec0a83a73b7a798549d2c49e8618188dd8faa | 11,704 | cpp | C++ | src/modules/adc_readout/integration_test/AdcSimulator.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 8 | 2017-12-02T09:20:26.000Z | 2022-03-28T08:17:40.000Z | src/modules/adc_readout/integration_test/AdcSimulator.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 296 | 2017-10-24T09:06:10.000Z | 2022-03-31T07:31:06.000Z | src/modules/adc_readout/integration_test/AdcSimulator.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 8 | 2018-04-08T15:35:50.000Z | 2021-04-12T05:06:15.000Z | /** Copyright (C) 2018 European Spallation Source ERIC */
/** @file
*
* \brief Simple application for simulating chopper TDC and monitor event data
* production.
*/
#include "SamplingTimer.h"
#include "UdpConnection.h"
#include <CLI/CLI.hpp>
#include <csignal>
#include <iostream>
#include <atomic>
#ifndef ADCSIM_ONLY_CREATE_FIRST_GENERATOR
#define ADCSIM_ONLY_CREATE_FIRST_GENERATOR 0
#endif
static std::atomic_bool RunLoop {true};
void signalHandler(int signal) {
std::cout << "Got exit signal:" << signal << std::endl;
RunLoop = false;
static int SigIntCount = 0;
if (signal == SIGINT && SigIntCount++ == 3) {
std::cout << "many repeats of SIGINT, aborting." << std::endl;
abort();
}
}
enum class RunMode { SIMPLE, DELAY_LINE_TIME, DELAY_LINE_AMP, CONTINOUS };
struct SimSettings {
std::string EFUAddress{"localhost"};
std::uint16_t Port1{65535};
std::uint16_t Port2{65534};
bool SecondFPGA{false};
RunMode Mode{RunMode::SIMPLE};
double EventRate{1000};
double NoiseRate{0.5};
};
void addCLIOptions(CLI::App &Parser, SimSettings &Settings) {
Parser
.add_option("--efu_addr", Settings.EFUAddress,
"Address to which the data should be transmitted.")
->default_str("localhost");
Parser
.add_option(
"--port1", Settings.Port1,
"UDP port #1 (from FPGA 1) to which the data should be transmitted.")
->default_str("65535");
Parser
.add_option(
"--port2", Settings.Port1,
"UDP port #2 (from FPGA 2) to which the data should be transmitted.")
->default_str("65534");
Parser.add_flag("--two_fpgas", Settings.SecondFPGA,
"Simulate a second FPGA (data source).");
std::vector<std::pair<std::string, RunMode>> ModeMap{
{"simple", RunMode::SIMPLE},
{"delay_line_time", RunMode::DELAY_LINE_TIME},
{"delay_line_amp", RunMode::DELAY_LINE_AMP},
{"continous", RunMode::CONTINOUS},
};
Parser
.add_option("--mode", Settings.Mode,
"Set the simulation (data generation) mode.")
->transform(CLI::CheckedTransformer(ModeMap, CLI::ignore_case))
->default_str("continous");
Parser
.add_option("--event_rate", Settings.EventRate,
"Event rate when mode is set to delay-line time or "
"delay-line amplitude.")
->default_str("1000");
Parser
.add_option(
"--noise_rate", Settings.NoiseRate,
"Noise rate per channel. Applies to all modes except continous.")
->default_str("0.5");
}
bool ShouldCreateGenerator(SamplerType Type, UdpConnection *TargetAdcBox,
UdpConnection *AdcBox2, SimSettings UsedSettings) {
if (ADCSIM_ONLY_CREATE_FIRST_GENERATOR) {
static uint32_t callcount = 0;
if (callcount++ != 0) {
return false;
}
}
if (!UsedSettings.SecondFPGA && TargetAdcBox == AdcBox2)
return false;
if (UsedSettings.Mode == RunMode::SIMPLE or
UsedSettings.Mode == RunMode::DELAY_LINE_AMP or
UsedSettings.Mode == RunMode::DELAY_LINE_TIME) {
if (Type == SamplerType::PoissonDelay) {
return true;
}
}
if (UsedSettings.Mode == RunMode::DELAY_LINE_AMP and
Type == SamplerType::AmpEventDelay) {
return true;
}
if (UsedSettings.Mode == RunMode::CONTINOUS) {
if (Type == SamplerType::Continous) {
return true;
}
}
return false;
}
int main(const int argc, char *argv[]) {
SimSettings UsedSettings;
CLI::App CLIParser{"Detector simulator"};
addCLIOptions(CLIParser, UsedSettings);
try {
CLIParser.parse(argc, argv);
} catch (const CLI::ParseError &e) {
CLIParser.exit(e);
return 0;
}
const std::vector<int> ActiveChannels{0, 1, 2, 3};
std::signal(SIGINT, signalHandler);
UdpConnection AdcBox1(UsedSettings.EFUAddress, UsedSettings.Port1, RunLoop);
UdpConnection AdcBox2(UsedSettings.EFUAddress, UsedSettings.Port2, RunLoop);
std::vector<UdpConnection *> UdpConnections = {&AdcBox1};
if (UsedSettings.SecondFPGA) {
UdpConnections.push_back(&AdcBox2);
}
std::vector<TimePointNano> TriggerTime_UdpHeartBeat;
TriggerTime_UdpHeartBeat.resize(UdpConnections.size());
std::vector<PoissonDelay> PoissionGenerators;
std::vector<TimePointNano> TriggerTime_Poisson;
std::vector<AmpEventDelay> AmpDelayGenerators;
std::vector<TimePointNano> TriggerTime_AmpDelay;
std::vector<ContinousSamplingTimer> ContinousGenerators;
std::vector<TimePointNano> TriggerTime_Continous;
// Box 1 timers
{
UdpConnection *CurAdc = &AdcBox1;
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 0, 0,
{{"rate", UsedSettings.NoiseRate},
{"offset", 1.0},
{"amplitude", 2000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 0, 1,
{{"rate", UsedSettings.NoiseRate},
{"offset", 10.0},
{"amplitude", 3000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 0, 2,
{{"rate", UsedSettings.NoiseRate},
{"offset", 100.0},
{"amplitude", 4000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 0, 3,
{{"rate", UsedSettings.NoiseRate},
{"offset", 1000.0},
{"amplitude", 5000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::Continous, CurAdc, &AdcBox2,
UsedSettings)) {
ContinousGenerators.emplace_back(ContinousSamplingTimer::Create(
CurAdc, 0, 0, {{"offset", 1000.0}, {"amplitude", 1000.0}}));
TriggerTime_Continous.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::AmpEventDelay, CurAdc, &AdcBox2,
UsedSettings)) {
AmpDelayGenerators.emplace_back(
AmpEventDelay::Create(CurAdc, 0, UsedSettings.EventRate));
TriggerTime_AmpDelay.emplace_back();
}
}
// Box 2 timers
{
UdpConnection *CurAdc = &AdcBox2;
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 1, 0,
{{"rate", UsedSettings.NoiseRate},
{"offset", 1.0},
{"amplitude", 2000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 1, 1,
{{"rate", UsedSettings.NoiseRate},
{"offset", 10.0},
{"amplitude", 3000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 1, 2,
{{"rate", UsedSettings.NoiseRate},
{"offset", 100.0},
{"amplitude", 4000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::PoissonDelay, CurAdc, &AdcBox2,
UsedSettings)) {
PoissionGenerators.emplace_back(
PoissonDelay::Create(CurAdc, 1, 3,
{{"rate", UsedSettings.NoiseRate},
{"offset", 1000.0},
{"amplitude", 5000.0}}));
TriggerTime_Poisson.emplace_back();
}
if (ShouldCreateGenerator(SamplerType::Continous, CurAdc, &AdcBox2,
UsedSettings)) {
ContinousGenerators.emplace_back(ContinousSamplingTimer::Create(
CurAdc, 1, 0, {{"offset", 1000.0}, {"amplitude", 500.0}}));
TriggerTime_Continous.emplace_back();
}
}
// Stats printer
auto PrintStats = [&AdcBox1, &AdcBox2]() {
std::cout << "Sampling runs generated by FPGA simulator 1: "
<< AdcBox1.getNrOfRuns();
std::cout << "\nSampling runs generated by FPGA simulator 2: "
<< AdcBox2.getNrOfRuns() << "\n";
};
TimeDurationNano PrintStatsInterval(5'000'000'000ull);
TimePointNano TriggerTime_PrintStats;
bool runTriggers = false;
while (RunLoop) {
auto TimeNow = std::chrono::high_resolution_clock::now();
TimeStamp TimeTS = MakeExternalTimeStampFromClock(TimeNow);
// Poission
for (int32_t i = 0, count = PoissionGenerators.size(); i < count; i++) {
auto &Self = PoissionGenerators[i];
auto &TriggerTime = TriggerTime_Poisson[i];
if (TriggerTime <= TimeNow) {
TriggerTime = TimeNow + Self.calcDelaTime();
if (runTriggers) {
Self.genSamplesAndQueueSend(TimeTS);
}
}
}
// AmpDelay
for (int32_t i = 0, count = AmpDelayGenerators.size(); i < count; i++) {
auto &Self = AmpDelayGenerators[i];
auto &TriggerTime = TriggerTime_AmpDelay[i];
if (TriggerTime <= TimeNow) {
TriggerTime = TimeNow + Self.calcDelaTime();
if (runTriggers) {
Self.genSamplesAndQueueSend(TimeTS);
}
}
}
// Continous
for (int32_t i = 0, count = ContinousGenerators.size(); i < count; i++) {
auto &Self = ContinousGenerators[i];
auto &TriggerTime = TriggerTime_Continous[i];
if (TriggerTime <= TimeNow) {
TriggerTime = TimeNow + Self.calcDelaTime();
if (runTriggers) {
Self.genSamplesAndQueueSend(TimeTS);
}
}
}
// PrintStats
{
auto &TriggerTime = TriggerTime_PrintStats;
if (TriggerTime <= TimeNow) {
TriggerTime = TimeNow + PrintStatsInterval;
if (runTriggers) {
PrintStats();
}
}
}
// UdpConnection HeatBeat
for (int32_t i = 0, count = UdpConnections.size(); i < count; i++) {
auto &Self = *UdpConnections[i];
auto &TriggerTime = TriggerTime_UdpHeartBeat[i];
if (TriggerTime <= TimeNow) {
TriggerTime = TimeNow + Self.HeartbeatInterval;
if (runTriggers) {
Self.transmitHeartbeat();
}
}
}
// UdpConnection FlushIdleData
for (int32_t i = 0, count = UdpConnections.size(); i < count; i++) {
auto &Self = *UdpConnections[i];
if (Self.shouldFlushIdleDataPacket(TimeNow)) {
if (runTriggers) {
Self.flushIdleDataPacket(TimeNow);
}
}
}
runTriggers = true;
}
std::cout << "Waiting for transmit thread(s) to exit" << std::endl;
return 0;
}
| 33.062147 | 79 | 0.593301 | [
"vector",
"transform"
] |
d26f0d6a297c6fc26f1f5dc110f3573a501c71e5 | 4,486 | cpp | C++ | MQ/src/QueueManagerPool.cpp | fbraem/mqweb | c030b300a0b7312c24948e0add4eb6a9b7f8a05b | [
"MIT"
] | 18 | 2015-01-12T20:17:27.000Z | 2022-02-11T17:40:54.000Z | MQ/src/QueueManagerPool.cpp | fbraem/mqweb | c030b300a0b7312c24948e0add4eb6a9b7f8a05b | [
"MIT"
] | 12 | 2015-01-20T12:47:01.000Z | 2019-03-13T07:10:19.000Z | MQ/src/QueueManagerPool.cpp | fbraem/mqweb | c030b300a0b7312c24948e0add4eb6a9b7f8a05b | [
"MIT"
] | 8 | 2015-01-13T13:52:29.000Z | 2021-12-10T12:07:29.000Z | /*
* Copyright 2017 - KBC Group NV - Franky Braem - The MIT license
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "MQ/QueueManagerPool.h"
namespace MQ
{
QueueManagerFactory::QueueManagerFactory(const std::string& qmgrName)
: _qmgrName(qmgrName)
{
}
QueueManagerFactory::QueueManagerFactory(const std::string& qmgrName, const Poco::Dynamic::Struct<std::string>& connectionInformation)
: _qmgrName(qmgrName)
, _connectionInformation(connectionInformation)
{
}
QueueManagerFactory::QueueManagerFactory(const QueueManagerFactory& copy)
: _qmgrName(copy._qmgrName)
, _connectionInformation(copy._connectionInformation)
{
}
QueueManagerFactory::~QueueManagerFactory()
{
}
QueueManager::Ptr QueueManagerFactory::createObject()
{
return new QueueManager(_qmgrName);
}
void QueueManagerFactory::activateObject(QueueManager::Ptr qmgr)
{
if ( !qmgr->connected() )
{
if ( _connectionInformation.size() == 0 )
{
qmgr->connect();
}
else
{
qmgr->connect(_connectionInformation);
}
}
}
bool QueueManagerFactory::validateObject(QueueManager::Ptr pObject)
{
return pObject->connected();
}
void QueueManagerFactory::deactivateObject(QueueManager::Ptr pObject)
{
}
void QueueManagerFactory::destroyObject(QueueManager::Ptr pObject)
{
try
{
pObject->disconnect();
}
catch(...)
{
}
}
QueueManagerPool::QueueManagerPool(Poco::SharedPtr<QueueManagerFactory> factory,
std::size_t capacity,
std::size_t peakCapacity,
int idleTime) :
_factory(factory),
_capacity(capacity),
_peakCapacity(peakCapacity),
_size(0),
_idleTime(idleTime),
_timerThreadPool(),
_janitorTimer(1000 * idleTime, 1000 * idleTime / 4)
{
poco_assert(capacity <= peakCapacity);
Poco::TimerCallback<QueueManagerPool> callback(*this, &QueueManagerPool::onJanitorTimer);
_janitorTimer.start(callback, _timerThreadPool);
}
QueueManagerPool::~QueueManagerPool()
{
for (std::vector<Poco::SharedPtr<TimedQueueManager> >::iterator it = _pool.begin(); it != _pool.end(); ++it)
{
_factory->destroyObject((*it)->value());
}
}
QueueManager::Ptr QueueManagerPool::borrowObject()
{
Poco::FastMutex::ScopedLock lock(_mutex);
if (!_pool.empty())
{
Poco::SharedPtr<TimedQueueManager> pObject = _pool.back();
_pool.pop_back();
return activateObject(pObject->value());
}
if (_size < _peakCapacity)
{
QueueManager::Ptr pObject = _factory->createObject();
activateObject(pObject);
_size++;
return pObject;
}
return 0;
}
void QueueManagerPool::returnObject(QueueManager::Ptr pObject)
{
Poco::FastMutex::ScopedLock lock(_mutex);
if (_factory->validateObject(pObject))
{
_factory->deactivateObject(pObject);
if (_pool.size() < _capacity)
{
Poco::SharedPtr<TimedQueueManager> timed = new TimedQueueManager(pObject);
_pool.push_back(timed);
}
else
{
_factory->destroyObject(pObject);
_size--;
}
}
else
{
_factory->destroyObject(pObject);
}
}
QueueManager::Ptr QueueManagerPool::activateObject(QueueManager::Ptr pObject)
{
try
{
_factory->activateObject(pObject);
}
catch (...)
{
_factory->destroyObject(pObject);
throw;
}
return pObject;
}
void QueueManagerPool::onJanitorTimer(Poco::Timer&)
{
Poco::FastMutex::ScopedLock lock(_mutex);
std::vector<Poco::SharedPtr<TimedQueueManager> >::iterator it = _pool.begin();
while(it != _pool.end())
{
if ( (*it)->idle() > _idleTime )
{
_factory->destroyObject((*it)->value());
_size--;
it = _pool.erase(it);
}
else ++it;
}
}
} // Namespace MQ
| 23.486911 | 134 | 0.736737 | [
"vector"
] |
d27f0990d2ffef7187b4ec83005a57baf448ae76 | 4,032 | cpp | C++ | Demos/src/OgreBulletGuiListener.cpp | bvigueras/ogrebullet-linux | 4ef7c8cb1cc9eb09ee3cd7f94033812a9964da4a | [
"MIT"
] | null | null | null | Demos/src/OgreBulletGuiListener.cpp | bvigueras/ogrebullet-linux | 4ef7c8cb1cc9eb09ee3cd7f94033812a9964da4a | [
"MIT"
] | null | null | null | Demos/src/OgreBulletGuiListener.cpp | bvigueras/ogrebullet-linux | 4ef7c8cb1cc9eb09ee3cd7f94033812a9964da4a | [
"MIT"
] | null | null | null | /***************************************************************************
This source file is part of OGREBULLET
(Object-oriented Graphics Rendering Engine Bullet Wrapper)
For the latest info, see http://www.ogre3d.org/phpBB2addons/viewforum.php?f=10
Copyright (c) 2007 tuan.kuranes@gmail.com (Use it Freely, even Statically, but have to contribute any changes)
This source file is not LGPL, it's public source code that you can reuse.
-----------------------------------------------------------------------------*/
#include "OgreBulletListener.h"
#include "OgreBulletGuiListener.h"
using namespace Ogre;
// -------------------------------------------------------------------------
OgreBulletGuiListener::OgreBulletGuiListener(OgreBulletListener *listener, Ogre::RenderWindow *win) :
mListener(listener),
mWindow(win),
mMouseOverlay(0),
mMousePanel(0)
{
/******************* CREATE Cursor Overlay ***************************/
mMouseOverlay = (Overlay*)OverlayManager::getSingleton().getByName("GuiOverlay");
if (mMouseOverlay)
{
mMousePanel = OverlayManager::getSingleton().getOverlayElement ("GUIMouse");
}
else
{
mMouseOverlay = OverlayManager::getSingletonPtr()->create("GuiOverlay");
mMouseOverlay->setZOrder(600);
mMousePanel = (Ogre::OverlayElement *)
OverlayManager::getSingletonPtr()->createOverlayElement("Panel", "GUIMouse");
mMousePanel->setMaterialName("OgreBulletDemos/TargetSights");
TexturePtr mouseTex = TextureManager::getSingleton().load("target.png", "Bullet");
mMousePanel->setWidth (mouseTex->getWidth() / (float)win->getWidth());
mMousePanel->setHeight (mouseTex->getHeight() / (float)win->getHeight());
Ogre::OverlayContainer *mouseContainer = (Ogre::OverlayContainer*)
OverlayManager::getSingletonPtr()->createOverlayElement("Panel", "GUIContainer");
mMouseOverlay->add2D(mouseContainer);
mouseContainer->addChild(mMousePanel);
}
mMouseOverlay->show();
TexturePtr mouseTex = TextureManager::getSingleton().load("target.png", "Bullet");
mMouseCursorHalfWidth = (Real(mouseTex->getWidth()) / mWindow->getWidth()) * 0.5;
mMouseCursorHalfHeight = (Real(mouseTex->getHeight()) / mWindow->getHeight ()) * 0.5;
/******************* CREATE GUI ***************************/
mGui = new BetaGUI::GUI("OgreBulletGui", "BlueHighway", 14, win);
OverlayContainer* mouseCursor = mGui->createMousePointer(Vector2(32, 32), "bgui.pointer");
mouseCursor->hide();
mGui->injectMouse(mWindow->getWidth() * 0.5, mWindow->getHeight() * 0.5, false);
}
// -------------------------------------------------------------------------
OgreBulletGuiListener::~OgreBulletGuiListener()
{
// other buttons and window managed by BETAGUI will be deleted by BETAGUI himself.
delete mGui;
}
// -------------------------------------------------------------------------
void OgreBulletGuiListener::addBool(BetaGUI::Window *window, bool* value, const String &label, Vector2 &pos)
{
window->createBoolButton(
Vector4(pos.x, pos.y, 7*label.size(), 24),
"bgui.button",
label,
BetaGUI::Callback(this),
value);
}
// -------------------------------------------------------------------------
void OgreBulletGuiListener::onButtonPress(BetaGUI::Button *ref, Ogre::uchar type)
{
//if(type == 1) // button down
//{
//
//}
}
// -------------------------------------------------------------------------
void OgreBulletGuiListener::hideMouse()
{
mMousePanel->hide();
}
// -------------------------------------------------------------------------
void OgreBulletGuiListener::showMouse()
{
mMousePanel->show();
}
// -------------------------------------------------------------------------
void OgreBulletGuiListener::setMousePosition(Ogre::Real x, Ogre::Real y)
{
mMousePanel->setPosition (x - mMouseCursorHalfWidth, y - mMouseCursorHalfHeight);
} | 39.920792 | 110 | 0.555804 | [
"object"
] |
d28099ebf24b0b681a575f6f39d1b139f68d5df1 | 4,006 | cpp | C++ | src/main.cpp | flyingpeakock/tuidoku | 032834bc187510b7021df854785d5624f7a0f653 | [
"MIT"
] | 3 | 2021-07-06T02:32:48.000Z | 2021-08-20T12:27:24.000Z | src/main.cpp | flyingpeakock/tuidoku | 032834bc187510b7021df854785d5624f7a0f653 | [
"MIT"
] | null | null | null | src/main.cpp | flyingpeakock/tuidoku | 032834bc187510b7021df854785d5624f7a0f653 | [
"MIT"
] | null | null | null | #include "Game.h"
#include "File.h"
#include "Arguments.h"
#include "Generator.h"
#include "config.h"
#include <fstream>
#include <sstream>
#include <iostream>
void generate(int, bool, std::string);
void solve(bool, std::string);
void play(bool, std::string, int, bool);
void startCurses();
void endCurses();
WINDOW * createWindow();
int main(int argc, char *argv[]) {
arguments args = arguments(argc, argv);
if (args.printHelp()) {
return 0;
}
if (args.shouldExit()) {
return 1;
}
switch(args.getFeature()) {
case feature::Generate:
generate(args.getArgInt(), args.fileArgSet(), args.getFileName());
break;
case feature::Solve:
solve(args.fileArgSet(), args.getFileName());
break;
case feature::Play:
play(args.fileArgSet(), args.getFileName(), args.getArgInt(), args.bigBoard());
break;
}
}
void startCurses() {
setlocale(LC_ALL, ""),
initscr();
}
void endCurses() {
endwin();
}
WINDOW * createWindow() {
int maxY, maxX;
getmaxyx(stdscr, maxY, maxX);
WINDOW * ret = newwin(maxY, maxX, 0, 0);
refresh();
return ret;
}
Board makeNotSimpleBoard(SimpleBoard &board) {
puzzle grid = board.getPlayGrid();
std::stringstream gridStringStream;
for (auto i = 0; i < grid.size(); i++) {
for (auto j = 0; j < grid[i].size(); j++) {
gridStringStream << grid[i][j];
}
}
return Generator{gridStringStream.str().c_str()}.createBoard();
}
Board selectBoard(std::vector<SimpleBoard> boards) {
if (boards.size() <= 1) {
return makeNotSimpleBoard(boards[0]);
}
int maxY, maxX;
getmaxyx(stdscr, maxY, maxX);
SelectionWindow *win = new SelectionWindow(boards, createWindow());
Selection game(win);
int index = game.mainLoop();
delete win;
return makeNotSimpleBoard(boards[index]);
}
void generate(int empty, bool file, std::string fileName) {
Generator gen = (empty) ? Generator(empty) : Generator();
if (file) {
std::ofstream fileStream;
fileStream.open(fileName);
gen.createBoard().printBoard(fileStream);
return;
}
gen.createBoard().printBoard();
return;
}
void solve(bool file, std::string fileName) {
if (file) {
selectBoard(file::getPuzzle(fileName.c_str())).printSolution();
return;
}
else if (fileName != "404" && !fileName.empty()) {
selectBoard(file::getStringPuzzle(fileName.c_str())).printSolution();
return;
}
std::ostringstream gridString;
for (auto i = 0; i < 81; i++) {
gridString << '0';
}
Board b = Generator(gridString.str().c_str()).createBoard();;
startCurses();
SolveWindow window = SolveWindow(&b, createWindow());
InteractiveSolver game(&window);
game.mainLoop();
endCurses();
std::cout << "Puzzle:\n";
b.printStart();
std::cout << "Solution:\n";
b.printSolution();
std::cout << std::endl;
return;
}
Board createBoard(bool file, std::string fileName, int empty) {
if (file) {
return selectBoard(file::getPuzzle(fileName.c_str()));
}
if (fileName != "404" && !fileName.empty()) {
// no file attempting to get string board from fileName
return selectBoard(file::getStringPuzzle(fileName.c_str()));
}
if (empty) {
return Generator(empty).createBoard();
}
return Generator().createBoard();
}
void play(bool file, std::string fileName, int empty, bool big) {
startCurses();
Board b = createBoard(file, fileName, empty);
Window *win = big ? new BigWindow(&b, createWindow()) : new Window(&b, createWindow());
Game game(win, big);
int playTime = game.mainLoop();
delete win;
endCurses();
std::cout << "Puzzle:\n";
b.printStart();
std::cout << "\nSolution:\n";
b.printSolution();
if (playTime > 0) {
std::cout << "\nSeconds played: " << playTime << std::endl;
}
} | 26.529801 | 91 | 0.604843 | [
"vector"
] |
d296c5506a3ce2963f829be72385538df7354f47 | 5,233 | cpp | C++ | src/GrainViewer/Ui/TestGui.cpp | eliemichel/GrainViewer | 91d4922b3185ada90508f0944f2691ba8eba45e3 | [
"MIT"
] | 8 | 2020-12-14T13:14:22.000Z | 2021-12-11T20:04:54.000Z | src/GrainViewer/Ui/TestGui.cpp | eliemichel/GrainViewer | 91d4922b3185ada90508f0944f2691ba8eba45e3 | [
"MIT"
] | null | null | null | src/GrainViewer/Ui/TestGui.cpp | eliemichel/GrainViewer | 91d4922b3185ada90508f0944f2691ba8eba45e3 | [
"MIT"
] | 2 | 2020-12-16T10:02:15.000Z | 2021-03-16T16:06:19.000Z | /**
* This file is part of GrainViewer, the reference implementation of:
*
* Michel, Élie and Boubekeur, Tamy (2020).
* Real Time Multiscale Rendering of Dense Dynamic Stackings,
* Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.
* https://doi.org/10.1111/cgf.14135
*
* Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <elie.michel@telecom-paris.fr>)
*
* 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 non-infringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising
* from, out of or in connection with the software or the use or other dealings
* in the Software.
*/
#include <OpenGL>
#include "Logger.h"
#include "TestGui.h"
#include "Window.h"
#include "Widgets.h"
#include <GLFW/glfw3.h>
#include <imgui.h>
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <iostream>
void TestGui::setupCallbacks()
{
if (auto window = m_window.lock()) {
glfwSetWindowUserPointer(window->glfw(), static_cast<void*>(this));
glfwSetKeyCallback(window->glfw(), [](GLFWwindow* window, int key, int scancode, int action, int mode) {
static_cast<TestGui*>(glfwGetWindowUserPointer(window))->onKey(key, scancode, action, mode);
});
glfwSetCursorPosCallback(window->glfw(), [](GLFWwindow* window, double x, double y) {
static_cast<TestGui*>(glfwGetWindowUserPointer(window))->onCursorPosition(x, y);
});
glfwSetMouseButtonCallback(window->glfw(), [](GLFWwindow* window, int button, int action, int mods) {
static_cast<TestGui*>(glfwGetWindowUserPointer(window))->onMouseButton(button, action, mods);
});
glfwSetWindowSizeCallback(window->glfw(), [](GLFWwindow* window, int width, int height) {
static_cast<TestGui*>(glfwGetWindowUserPointer(window))->onResize(width, height);
});
}
}
TestGui::TestGui(std::shared_ptr<Window> window)
: m_window(window)
{
setupCallbacks();
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui_ImplGlfw_InitForOpenGL(window->glfw(), true);
ImGui_ImplOpenGL3_Init("#version 150");
ImGui::GetStyle().WindowRounding = 0.0f;
int width, height;
glfwGetFramebufferSize(window->glfw(), &width, &height);
onResize(width, height);
}
TestGui::~TestGui() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void TestGui::updateProgress(float progress)
{
m_progress = progress;
render();
if (auto window = m_window.lock()) {
window->swapBuffers();
}
}
void TestGui::addMessage(const std::string & msg)
{
LOG << msg;
m_messages.push_back(msg);
}
void TestGui::render() {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowSize(ImVec2(m_windowWidth, m_windowHeight));
ImGui::SetNextWindowPos(ImVec2(0.f, 0.f));
ImGui::Begin("Progress", nullptr,
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoTitleBar);
ImGui::Spacing();
ImGui::Text("Test progress:");
const ImU32 col = ImGui::GetColorU32(ImGuiCol_ButtonHovered);
const ImU32 bg = ImGui::GetColorU32(ImGuiCol_Button);
ProgressBar("Progress", m_progress, ImVec2(m_windowWidth - 7, 6), bg, col);
ImGui::Dummy(ImVec2(0.0f, 10.0f));
ImGui::BeginChild("Messages", ImVec2(0, 0), false, ImGuiWindowFlags_NoTitleBar);
for (const auto & msg : m_messages) {
ImGui::Text(msg.c_str());
}
if (ImGui::GetScrollY() == ImGui::GetScrollMaxY()) {
ImGui::SetScrollHere();
}
ImGui::End();
ImGui::End();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void TestGui::onResize(int width, int height) {
m_windowWidth = static_cast<float>(width);
m_windowHeight = static_cast<float>(height);
if (auto window = m_window.lock()) {
int fbWidth, fbHeight;
glfwGetFramebufferSize(window->glfw(), &fbWidth, &fbHeight);
glViewport(0, 0, fbWidth, fbHeight);
}
}
void TestGui::onMouseButton(int button, int action, int mods) {
switch (button) {
case GLFW_MOUSE_BUTTON_LEFT:
if (action == GLFW_PRESS) {
}
break;
}
}
void TestGui::onCursorPosition(double x, double y) {
}
void TestGui::onKey(int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_ESCAPE:
if (auto window = m_window.lock()) {
glfwSetWindowShouldClose(window->glfw(), GL_TRUE);
}
break;
}
}
}
| 30.248555 | 106 | 0.725779 | [
"render"
] |
d2a09c047fe9a135b6218b1b611eb7d14197fe4e | 1,995 | cpp | C++ | OpenTESArena/src/World/VoxelGrid.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/VoxelGrid.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/World/VoxelGrid.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | #include <algorithm>
#include "VoxelGrid.h"
#include "components/debug/Debug.h"
VoxelGrid::VoxelGrid(NSInt width, int height, EWInt depth)
{
const int voxelCount = width * height * depth;
this->voxels = std::vector<uint16_t>(voxelCount, 0);
this->width = width;
this->height = height;
this->depth = depth;
// Add empty (air) voxel definition by default.
this->addVoxelDef(VoxelDefinition());
}
int VoxelGrid::getIndex(NSInt x, int y, EWInt z) const
{
DebugAssert(this->coordIsValid(x, y, z));
return x + (y * this->width) + (z * this->width * this->height);
}
NSInt VoxelGrid::getWidth() const
{
return this->width;
}
int VoxelGrid::getHeight() const
{
return this->height;
}
EWInt VoxelGrid::getDepth() const
{
return this->depth;
}
bool VoxelGrid::coordIsValid(NSInt x, int y, EWInt z) const
{
return (x >= 0) && (x < this->width) && (y >= 0) && (y < this->height) &&
(z >= 0) && (z < this->depth);
}
uint16_t VoxelGrid::getVoxel(NSInt x, int y, EWInt z) const
{
const int index = this->getIndex(x, y, z);
return this->voxels.data()[index];
}
VoxelDefinition &VoxelGrid::getVoxelDef(uint16_t id)
{
DebugAssertIndex(this->voxelDefs, id);
return this->voxelDefs[id];
}
const VoxelDefinition &VoxelGrid::getVoxelDef(uint16_t id) const
{
DebugAssertIndex(this->voxelDefs, id);
return this->voxelDefs[id];
}
std::optional<uint16_t> VoxelGrid::findVoxelDef(const VoxelDefPredicate &predicate) const
{
const auto iter = std::find_if(this->voxelDefs.begin(), this->voxelDefs.end(), predicate);
if (iter != this->voxelDefs.end())
{
return static_cast<uint16_t>(std::distance(this->voxelDefs.begin(), iter));
}
else
{
return std::nullopt;
}
}
uint16_t VoxelGrid::addVoxelDef(const VoxelDefinition &voxelDef)
{
this->voxelDefs.push_back(voxelDef);
return static_cast<uint16_t>(this->voxelDefs.size() - 1);
}
void VoxelGrid::setVoxel(NSInt x, int y, EWInt z, uint16_t id)
{
const int index = this->getIndex(x, y, z);
this->voxels.data()[index] = id;
}
| 22.166667 | 91 | 0.692732 | [
"vector"
] |
d2a0c6afb6ff66d7dcfd6982195e170085bcf6f0 | 6,115 | hpp | C++ | src/libraries/lagrangian/turbulence/submodels/Kinematic/DispersionModel/DispersionLESModel/DispersionLESModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/lagrangian/turbulence/submodels/Kinematic/DispersionModel/DispersionLESModel/DispersionLESModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/lagrangian/turbulence/submodels/Kinematic/DispersionModel/DispersionLESModel/DispersionLESModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
Copyright (C) 2015 Applied CCM
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::DispersionLESModel
Description
Base class for particle dispersion models based on LES turbulence.
\*---------------------------------------------------------------------------*/
#ifndef DispersionLESModel_H
#define DispersionLESModel_H
#include "DispersionModel.hpp"
#include "LESModel.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class DispersionLESModel Declaration
\*---------------------------------------------------------------------------*/
template<class CloudType>
class DispersionLESModel
:
public DispersionModel<CloudType>
{
protected:
// Protected data
//- Reference to the incompressible turbulence model
const incompressible::LESModel& turbulence_;
// Locally cached turbulence fields
//- Turbulence k
const volScalarField* kPtr_;
//- Take ownership of the k field
mutable bool ownK_;
//- Turbulence epsilon
const volScalarField* epsilonPtr_;
//- Take ownership of the epsilon field
mutable bool ownEpsilon_;
public:
//- Runtime type information
TypeName("dispersionLESModel");
// Constructors
//- Construct from components
DispersionLESModel(const dictionary& dict, CloudType& owner);
//- Construct copy
DispersionLESModel(const DispersionLESModel<CloudType>& dm);
//- Construct and return a clone
virtual autoPtr<DispersionModel<CloudType> > clone() const = 0;
//- Destructor
virtual ~DispersionLESModel();
// Member Functions
//- Update (disperse particles)
virtual vector update
(
const scalar dt,
const label celli,
const vector& U,
const vector& Uc,
vector& UTurb,
scalar& tTurb
) = 0;
//- Cache carrier fields
virtual void cacheFields(const bool store);
//- Return const access to the turbulence model
const incompressible::LESModel& turbulence() const
{
return turbulence_;
}
// I-O
//- Write
virtual void write(Ostream& os) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "demandDrivenData.hpp"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class CloudType>
CML::DispersionLESModel<CloudType>::DispersionLESModel
(
const dictionary&,
CloudType& owner
)
:
DispersionModel<CloudType>(owner),
turbulence_
(
owner.mesh().objectRegistry::template lookupObject
<
incompressible::LESModel
>
(
"LESProperties"
)
),
kPtr_(nullptr),
ownK_(false),
epsilonPtr_(nullptr),
ownEpsilon_(false)
{}
template<class CloudType>
CML::DispersionLESModel<CloudType>::DispersionLESModel
(
const DispersionLESModel<CloudType>& dm
)
:
DispersionModel<CloudType>(dm),
turbulence_(dm.turbulence_),
kPtr_(dm.kPtr_),
ownK_(dm.ownK_),
epsilonPtr_(dm.epsilonPtr_),
ownEpsilon_(dm.ownEpsilon_)
{
dm.ownK_ = false;
dm.ownEpsilon_ = false;
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template<class CloudType>
CML::DispersionLESModel<CloudType>::~DispersionLESModel()
{
cacheFields(false);
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class CloudType>
void CML::DispersionLESModel<CloudType>::cacheFields(const bool store)
{
if (store)
{
tmp<volScalarField> tk = this->turbulence().k();
if (tk.isTmp())
{
kPtr_ = tk.ptr();
ownK_ = true;
}
else
{
kPtr_ = tk.operator->();
ownK_ = false;
}
tmp<volScalarField> tepsilon = this->turbulence().epsilon();
if (tepsilon.isTmp())
{
epsilonPtr_ = tepsilon.ptr();
ownEpsilon_ = true;
}
else
{
epsilonPtr_ = tepsilon.operator->();
ownEpsilon_ = false;
}
}
else
{
if (ownK_ && kPtr_)
{
deleteDemandDrivenData(kPtr_);
ownK_ = false;
}
if (ownEpsilon_ && epsilonPtr_)
{
deleteDemandDrivenData(epsilonPtr_);
ownEpsilon_ = false;
}
}
}
template<class CloudType>
void CML::DispersionLESModel<CloudType>::write(Ostream& os) const
{
DispersionModel<CloudType>::write(os);
os.writeKeyword("ownK") << ownK_ << token::END_STATEMENT << endl;
os.writeKeyword("ownEpsilon") << ownEpsilon_ << token::END_STATEMENT
<< endl;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 24.46 | 79 | 0.516762 | [
"mesh",
"vector",
"model"
] |
d2b5f8ef73fd4d14e66f9b6c43a82c7fbbe7ab3c | 4,430 | cpp | C++ | tests/transport/test_barrier.cpp | fthaler/GHEX | ead3699e3ed3aa60c5f18225d4d6f8dcf3412cf9 | [
"BSD-3-Clause"
] | null | null | null | tests/transport/test_barrier.cpp | fthaler/GHEX | ead3699e3ed3aa60c5f18225d4d6f8dcf3412cf9 | [
"BSD-3-Clause"
] | null | null | null | tests/transport/test_barrier.cpp | fthaler/GHEX | ead3699e3ed3aa60c5f18225d4d6f8dcf3412cf9 | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2020, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <iostream>
#include <iomanip>
#include <thread>
#include <numeric>
#include <ghex/transport_layer/util/barrier.hpp>
#include <ghex/common/timer.hpp>
#include <gtest/gtest.h>
#ifdef GHEX_TEST_USE_UCX
#include <ghex/transport_layer/ucx/context.hpp>
using transport = gridtools::ghex::tl::ucx_tag;
#else
#include <ghex/transport_layer/mpi/context.hpp>
using transport = gridtools::ghex::tl::mpi_tag;
#endif
TEST(transport, rank_barrier) {
auto context_ptr = gridtools::ghex::tl::context_factory<transport>::create(MPI_COMM_WORLD);
auto& context = *context_ptr;
gridtools::ghex::tl::barrier_t barrier;
auto comm = context.get_communicator();
int rank = context.rank();
gridtools::ghex::timer timer;
timer.tic();
for(int i=0; i<20; i++) {
barrier.rank_barrier(comm);
}
const auto t = timer.stoc();
if(rank==0)
{
std::cout << "time: " << t/1000000 << "s\n";
}
}
namespace gridtools {
namespace ghex {
namespace tl {
struct test_barrier {
gridtools::ghex::tl::barrier_t& br;
test_barrier(gridtools::ghex::tl::barrier_t& br) : br{br} {}
template <typename Context>
void test_in_node1(Context &context) {
std::vector<int> innode1_out(br.size());
auto work = [&](int id) {
auto comm = context.get_communicator();
innode1_out[id] = br.in_node1(comm)?1:0;
};
std::vector<std::thread> ths;
for (int i = 0; i < br.size(); ++i) {
ths.push_back(std::thread{work, i});
}
for (int i = 0; i < br.size(); ++i) {
ths[i].join();
}
EXPECT_EQ(std::accumulate(innode1_out.begin(), innode1_out.end(), 0), 1);
}
};
}
}
}
TEST(transport, in_barrier_1) {
auto context_ptr = gridtools::ghex::tl::context_factory<transport>::create(MPI_COMM_WORLD);
auto& context = *context_ptr;
size_t n_threads = 4;
gridtools::ghex::tl::barrier_t barrier{n_threads};
gridtools::ghex::tl::test_barrier test(barrier);
test.test_in_node1(context);
}
TEST(transport, in_barrier) {
auto context_ptr = gridtools::ghex::tl::context_factory<transport>::create(MPI_COMM_WORLD);
auto& context = *context_ptr;
size_t n_threads = 4;
gridtools::ghex::tl::barrier_t barrier{n_threads};
auto work =
[&]()
{
auto comm = context.get_communicator();
int rank = context.rank();
gridtools::ghex::timer timer;
timer.tic();
for(int i=0; i<20; i++) {
comm.progress();
barrier.in_node(comm);
}
const auto t = timer.stoc();
if(rank==0)
{
std::cout << "time: " << t/1000000 << "s\n";
}
};
std::vector<std::thread> ths;
for (size_t i = 0; i < n_threads; ++i) {
ths.push_back(std::thread{work});
}
for (size_t i = 0; i < n_threads; ++i) {
ths[i].join();
}
}
TEST(transport, full_barrier) {
auto context_ptr = gridtools::ghex::tl::context_factory<transport>::create(MPI_COMM_WORLD);
auto& context = *context_ptr;
size_t n_threads = 4;
gridtools::ghex::tl::barrier_t barrier{n_threads};
auto work =
[&]()
{
auto comm = context.get_communicator();
int rank = context.rank();
gridtools::ghex::timer timer;
timer.tic();
for(int i=0; i<20; i++) {
barrier(comm);
}
const auto t = timer.stoc();
if(rank==0)
{
std::cout << "time: " << t/1000000 << "s\n";
}
};
std::vector<std::thread> ths;
for (size_t i = 0; i < n_threads; ++i) {
ths.push_back(std::thread{work});
}
for (size_t i = 0; i < n_threads; ++i) {
ths[i].join();
}
}
| 27.345679 | 95 | 0.521445 | [
"vector"
] |
d2b69202e995152b863a43ad176fd9d3a40fbed4 | 4,865 | cpp | C++ | ivs/src/v2/model/ExtentionRespDataByIdCardImage.cpp | huaweicloud/huaweicloud-sdk-cpp-v3 | d3b5e07b0ee8367d1c7f6dad17be0212166d959c | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ivs/src/v2/model/ExtentionRespDataByIdCardImage.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | null | null | null | ivs/src/v2/model/ExtentionRespDataByIdCardImage.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ivs/v2/model/ExtentionRespDataByIdCardImage.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ivs {
namespace V2 {
namespace Model {
ExtentionRespDataByIdCardImage::ExtentionRespDataByIdCardImage()
{
verificationResult_ = "";
verificationResultIsSet_ = false;
verificationMessage_ = "";
verificationMessageIsSet_ = false;
verificationCode_ = 0;
verificationCodeIsSet_ = false;
idcardResultIsSet_ = false;
}
ExtentionRespDataByIdCardImage::~ExtentionRespDataByIdCardImage() = default;
void ExtentionRespDataByIdCardImage::validate()
{
}
web::json::value ExtentionRespDataByIdCardImage::toJson() const
{
web::json::value val = web::json::value::object();
if(verificationResultIsSet_) {
val[utility::conversions::to_string_t("verification_result")] = ModelBase::toJson(verificationResult_);
}
if(verificationMessageIsSet_) {
val[utility::conversions::to_string_t("verification_message")] = ModelBase::toJson(verificationMessage_);
}
if(verificationCodeIsSet_) {
val[utility::conversions::to_string_t("verification_code")] = ModelBase::toJson(verificationCode_);
}
if(idcardResultIsSet_) {
val[utility::conversions::to_string_t("idcard_result")] = ModelBase::toJson(idcardResult_);
}
return val;
}
bool ExtentionRespDataByIdCardImage::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("verification_result"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("verification_result"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setVerificationResult(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("verification_message"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("verification_message"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setVerificationMessage(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("verification_code"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("verification_code"));
if(!fieldValue.is_null())
{
int32_t refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setVerificationCode(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("idcard_result"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("idcard_result"));
if(!fieldValue.is_null())
{
IdcardResult refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setIdcardResult(refVal);
}
}
return ok;
}
std::string ExtentionRespDataByIdCardImage::getVerificationResult() const
{
return verificationResult_;
}
void ExtentionRespDataByIdCardImage::setVerificationResult(const std::string& value)
{
verificationResult_ = value;
verificationResultIsSet_ = true;
}
bool ExtentionRespDataByIdCardImage::verificationResultIsSet() const
{
return verificationResultIsSet_;
}
void ExtentionRespDataByIdCardImage::unsetverificationResult()
{
verificationResultIsSet_ = false;
}
std::string ExtentionRespDataByIdCardImage::getVerificationMessage() const
{
return verificationMessage_;
}
void ExtentionRespDataByIdCardImage::setVerificationMessage(const std::string& value)
{
verificationMessage_ = value;
verificationMessageIsSet_ = true;
}
bool ExtentionRespDataByIdCardImage::verificationMessageIsSet() const
{
return verificationMessageIsSet_;
}
void ExtentionRespDataByIdCardImage::unsetverificationMessage()
{
verificationMessageIsSet_ = false;
}
int32_t ExtentionRespDataByIdCardImage::getVerificationCode() const
{
return verificationCode_;
}
void ExtentionRespDataByIdCardImage::setVerificationCode(int32_t value)
{
verificationCode_ = value;
verificationCodeIsSet_ = true;
}
bool ExtentionRespDataByIdCardImage::verificationCodeIsSet() const
{
return verificationCodeIsSet_;
}
void ExtentionRespDataByIdCardImage::unsetverificationCode()
{
verificationCodeIsSet_ = false;
}
IdcardResult ExtentionRespDataByIdCardImage::getIdcardResult() const
{
return idcardResult_;
}
void ExtentionRespDataByIdCardImage::setIdcardResult(const IdcardResult& value)
{
idcardResult_ = value;
idcardResultIsSet_ = true;
}
bool ExtentionRespDataByIdCardImage::idcardResultIsSet() const
{
return idcardResultIsSet_;
}
void ExtentionRespDataByIdCardImage::unsetidcardResult()
{
idcardResultIsSet_ = false;
}
}
}
}
}
}
| 26.155914 | 113 | 0.720041 | [
"object",
"model"
] |
d2b893c9e4e5791afc6a662255dbebb15f28b554 | 1,111 | hpp | C++ | .experimentals/include/timerapp-core/dataset/sound.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-12-10T02:12:49.000Z | 2019-12-10T02:12:49.000Z | .experimentals/include/timerapp-core/dataset/sound.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | .experimentals/include/timerapp-core/dataset/sound.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *
* Use of this source code is governed by a BSD-style license that *
* can be found in the LICENSE file. */
#ifndef __libscheduler__sound__hpp
#define __libscheduler__sound__hpp
struct sound
{
struct item
{
std::string title;
std::string filename;
};
struct group
{
std::string name;
std::vector<item> items;
std::string product; //!< ストア(プロダクトID)
auto begin() const noexcept { return items.begin(); }
auto end() const noexcept { return items.end(); }
};
std::vector<group> groups;
auto begin() const noexcept { return groups.begin(); }
auto end() const noexcept { return groups.end(); }
static bool has_sound();
static void initialize(std::string const& _configfile);
static sound const* get_instance();
static group const* find_group(std::string const& _group);
//! 指定した名前もしくはファイル名の画像を検索する
static item const* find_item(std::string const& _item);
//! すべてのアイテムを列挙して返す
static std::vector<std::pair<group const*, item const*>> enum_items();
};
#endif
| 22.673469 | 72 | 0.678668 | [
"vector"
] |
d2b8d783ea0183ba9f0cfd30b22747b3f0a556b0 | 9,715 | cpp | C++ | AVSCommon/Utils/test/TaskQueueTest.cpp | hsguron/alexa | 6bbe4a215e925874d2835a820fcec47147182a8b | [
"Apache-2.0"
] | 1 | 2022-01-09T21:26:04.000Z | 2022-01-09T21:26:04.000Z | AVSCommon/Utils/test/TaskQueueTest.cpp | hsguron/alexa | 6bbe4a215e925874d2835a820fcec47147182a8b | [
"Apache-2.0"
] | null | null | null | AVSCommon/Utils/test/TaskQueueTest.cpp | hsguron/alexa | 6bbe4a215e925874d2835a820fcec47147182a8b | [
"Apache-2.0"
] | 1 | 2018-10-12T07:58:44.000Z | 2018-10-12T07:58:44.000Z | /*
* TaskQueueTest.cpp
*
* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 <gtest/gtest.h>
#include "ExecutorTestUtils.h"
#include "AVSCommon/Utils/Threading/Executor.h"
#include "AVSCommon/Utils/Threading/TaskQueue.h"
namespace alexaClientSDK {
namespace avsCommon {
namespace utils {
namespace threading {
namespace test {
class TaskQueueTest : public ::testing::Test {
public:
/**
* Asserts that a call to pop on an empty queue is blocking, and will be awoken by a task being pushed onto
* the queue
*/
void testQueueBlocksWhenEmpty() {
// Have another thread blocked on the queue
auto future = std::async(std::launch::async, [=]() {
auto t = queue.pop();
return t->operator()();
});
// This is expected to timeout
auto failedStatus = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(failedStatus, std::future_status::timeout);
// Push a task to unblock the queue
auto pushFuture = queue.push(TASK, VALUE);
// This is expected to succeed
auto successStatus = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(successStatus, std::future_status::ready);
// Verify the pushed future behaved correctly
auto pushStatus = pushFuture.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(pushStatus, std::future_status::ready);
ASSERT_EQ(pushFuture.get(), VALUE);
}
TaskQueue queue;
};
TEST_F(TaskQueueTest, pushStdFunctionAndVerifyPopReturnsIt) {
std::function<void()> function([]() {});
auto future = queue.push(function);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushStdBindAndVerifyPopReturnsIt) {
auto future = queue.push(std::bind(exampleFunctionParams, 0));
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushLambdaAndVerifyPopReturnsIt) {
auto future = queue.push([]() {});
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushFunctionPointerAndVerifyPopReturnsIt) {
auto future = queue.push(&exampleFunction);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushFunctorAndVerifyPopReturnsIt) {
ExampleFunctor exampleFunctor;
auto future = queue.push(exampleFunctor);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushFunctionWithPrimitiveReturnTypeNoArgsAndVerifyPopReturnsIt) {
int value = VALUE;
auto future = queue.push([=]() { return value; });
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
ASSERT_EQ(future.get(), value);
}
TEST_F(TaskQueueTest, pushFunctionWithObjectReturnTypeNoArgsAndVerifyPopReturnsIt) {
SimpleObject value(VALUE);
auto future = queue.push([=]() { return value; });
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
ASSERT_EQ(future.get().getValue(), value.getValue());
}
TEST_F(TaskQueueTest, pushFunctionWithNoReturnTypePrimitiveArgsAndVerifyPopReturnsIt) {
int value = VALUE;
auto future = queue.push([](int number) {}, value);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushFunctionWithNoReturnTypeObjectArgsAndVerifyPopReturnsIt) {
SimpleObject arg(0);
auto future = queue.push([](SimpleObject object) {}, arg);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushFunctionWithPrimitiveReturnTypeObjectArgsAndVerifyPopReturnsIt) {
int value = VALUE;
SimpleObject arg(0);
auto future = queue.push([=](SimpleObject object) { return value; }, arg);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
ASSERT_EQ(future.get(), value);
}
TEST_F(TaskQueueTest, pushFunctionWithObjectReturnTypePrimitiveArgsAndVerifyPopReturnsIt) {
int arg = 0;
SimpleObject value(VALUE);
auto future = queue.push([=](int primitive) { return value; }, arg);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
ASSERT_EQ(future.get().getValue(), value.getValue());
}
TEST_F(TaskQueueTest, pushFunctionWithPrimitiveReturnTypePrimitiveArgsAndVerifyPopReturnsIt) {
int arg = 0;
int value = VALUE;
auto future = queue.push([=](int number) { return value; }, arg);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
ASSERT_EQ(future.get(), value);
}
TEST_F(TaskQueueTest, pushFunctionWithObjectReturnTypeObjectArgsAndVerifyPopReturnsIt) {
SimpleObject value(VALUE);
SimpleObject arg(0);
auto future = queue.push([=](SimpleObject object) { return value; }, arg);
auto task = queue.pop();
task->operator()();
auto future_status = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(future_status, std::future_status::ready);
ASSERT_EQ(future.get().getValue(), value.getValue());
}
TEST_F(TaskQueueTest, verifyFirstInFirstOutOrderIsMaintained) {
int argOne = 1;
int argTwo = 2;
int argThree = 3;
int argFour = 4;
auto futureOne = queue.push(TASK, argOne);
auto futureTwo = queue.push(TASK, argTwo);
auto futureThree = queue.push(TASK, argThree);
auto futureFour = queue.push(TASK, argFour);
auto taskOne = queue.pop();
auto taskTwo = queue.pop();
auto taskThree = queue.pop();
auto taskFour = queue.pop();
taskOne->operator()();
taskTwo->operator()();
taskThree->operator()();
taskFour->operator()();
auto futureStatusOne = futureOne.wait_for(SHORT_TIMEOUT_MS);
auto futureStatusTwo = futureTwo.wait_for(SHORT_TIMEOUT_MS);
auto futureStatusThree = futureThree.wait_for(SHORT_TIMEOUT_MS);
auto futureStatusFour = futureFour.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(futureStatusOne, std::future_status::ready);
ASSERT_EQ(futureStatusTwo, std::future_status::ready);
ASSERT_EQ(futureStatusThree, std::future_status::ready);
ASSERT_EQ(futureStatusFour, std::future_status::ready);
ASSERT_EQ(futureOne.get(), argOne);
ASSERT_EQ(futureTwo.get(), argTwo);
ASSERT_EQ(futureThree.get(), argThree);
ASSERT_EQ(futureFour.get(), argFour);
}
TEST_F(TaskQueueTest, popBlocksOnInitiallyEmptyQueue) {
testQueueBlocksWhenEmpty();
}
TEST_F(TaskQueueTest, popBlocksOnEmptyQueueAfterAllTasksArePopped) {
// Put a task on the queue, and take it off to get back to empty
auto futureOne = queue.push(TASK, VALUE);
auto taskOne = queue.pop();
taskOne->operator()();
auto futureOneStatus = futureOne.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(futureOneStatus, std::future_status::ready);
ASSERT_EQ(futureOne.get(), VALUE);
testQueueBlocksWhenEmpty();
}
TEST_F(TaskQueueTest, isShutdownReturnsFalseWhenRunning) {
ASSERT_EQ(queue.isShutdown(), false);
}
TEST_F(TaskQueueTest, isShutdownReturnsTrueAfterShutdown) {
queue.shutdown();
ASSERT_EQ(queue.isShutdown(), true);
}
TEST_F(TaskQueueTest, shutdownUnblocksAnEmptyQueue) {
// Have another thread blocked on the queue
auto future = std::async(std::launch::async, [=]() {
auto t = queue.pop();
if (t) t->operator()();
});
// This is expected to timeout
auto failedStatus = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(failedStatus, std::future_status::timeout);
// Shutdown to unblock the queue
queue.shutdown();
// This is expected to succeed
auto successStatus = future.wait_for(SHORT_TIMEOUT_MS);
ASSERT_EQ(successStatus, std::future_status::ready);
}
TEST_F(TaskQueueTest, pushFailsToEnqueueANewTaskOnAShutdownQueue) {
// No tasks should be enqueued
queue.shutdown();
auto future = queue.push(TASK, VALUE);
ASSERT_EQ(future.valid(), false);
auto retrievedTask = queue.pop();
ASSERT_EQ(retrievedTask, nullptr);
}
} // namespace test
} // namespace threading
} // namespace utils
} // namespace avsCommon
} // namespace alexaClientSDK
| 33.850174 | 111 | 0.705816 | [
"object"
] |
d2c104b27cb3b7f8c14b1fa825a6411472d35087 | 14,734 | hpp | C++ | vml/src/matrix/crs_matrix.hpp | sx-aurora-dev/vml | cf16bd1dca5fb8b0b3cb40c6388c461ad15caca6 | [
"BSD-2-Clause"
] | null | null | null | vml/src/matrix/crs_matrix.hpp | sx-aurora-dev/vml | cf16bd1dca5fb8b0b3cb40c6388c461ad15caca6 | [
"BSD-2-Clause"
] | 1 | 2021-03-05T00:14:06.000Z | 2021-03-05T00:14:06.000Z | vml/src/matrix/crs_matrix.hpp | sx-aurora-dev/vml | cf16bd1dca5fb8b0b3cb40c6388c461ad15caca6 | [
"BSD-2-Clause"
] | 1 | 2021-12-20T09:59:44.000Z | 2021-12-20T09:59:44.000Z | #ifndef CRS_MATRIX_HPP
#define CRS_MATRIX_HPP
#include <fstream>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <climits>
#include <vector>
//#include "../core/dvector.hpp"
//#include "../core/dunordered_map.hpp"
//#include "../core/mpihelper.hpp"
//#include "../core/prefix_sum.hpp"
//#include "rowmajor_matrix.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#undef FTRACE_A
#undef FTRACE_B
#if defined(_SX)||defined(__ve) && 0
#include <ftrace.h>
#define FTRACE_A(name) ftrace_region_begin(name)
#define FTRACE_B(name) ftrace_region_end(name)
#else
#define FTRACE_A(name)
#define FTRACE_B(name)
#endif
#define CRS_SPMM_THR 32
#define CRS_SPMM_VLEN 256
#define SPARSE_VECTOR_VLEN 256
#define TO_SKIP_REBALANCE 256
//This file was copied from Frovedis.
template <class T, class I = size_t, class O = size_t>
struct crs_matrix_local {
crs_matrix_local() {}
crs_matrix_local(size_t nrows, size_t ncols) :
local_num_row(nrows), local_num_col(ncols) {}
void view_data(){
printf("crs data\n");
printf("----------------------------\n");
printf("col %d, row %d\n",local_num_col,local_num_row);
printf("first off %d, last off %d\n",off[0],off[local_num_row]);
printf("----------------------------\n");
}
T* val; // size is off[local_num_row]
I* idx; // size is off[local_num_row]
O* off; // size is local_num_row + 1 ("0" is added)
T* buf; // size is local_num_row
size_t local_num_row;
size_t local_num_col;
};
template <class T, class I, class O>
void crs_matrix_spmv_impl(const crs_matrix_local<T,I,O>& mat, T* retp, const T* vp) {
const T* valp = &mat.val[0];
const I* idxp = &mat.idx[0];
const O* offp = &mat.off[0];
// printf("crs_matrix_spmv_impl\n");
// printf("c %d, r %d\n",mat.local_num_col,mat.local_num_row);
// printf("val %d, idx %d, off %d\n",mat.val.size(),mat.idx.size(),mat.off.size());
// printf("off: s %d, e %d\n",mat.off[0],mat.off[mat.local_num_row]);
FTRACE_A("crs impl");
#if 0
size_t size = mat.val.size();
std::vector<T> crspart(size);
T* crspartp = crspart.data();
FTRACE_A("crs impl mul");
size_t size8 = (size>>3)<<3;
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(size_t i = 0; i < size8; i+=8) {
size_t pos0 = idxp[i+0];
size_t pos1 = idxp[i+1];
size_t pos2 = idxp[i+2];
size_t pos3 = idxp[i+3];
size_t pos4 = idxp[i+4];
size_t pos5 = idxp[i+5];
size_t pos6 = idxp[i+6];
size_t pos7 = idxp[i+7];
crspartp[i+0] = valp[i+0] * vp[pos0];
crspartp[i+1] = valp[i+1] * vp[pos1];
crspartp[i+2] = valp[i+2] * vp[pos2];
crspartp[i+3] = valp[i+3] * vp[pos3];
crspartp[i+4] = valp[i+4] * vp[pos4];
crspartp[i+5] = valp[i+5] * vp[pos5];
crspartp[i+6] = valp[i+6] * vp[pos6];
crspartp[i+7] = valp[i+7] * vp[pos7];
}
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(size_t i = size8; i < size; i++) {
crspartp[i] = valp[i] * vp[idxp[i]];
}
//#pragma _NEC vovertake
////#pragma cdir on_adb(vp)
// for(size_t i = 0; i < size; i++) {
// crspartp[i] = valp[i] * vp[idxp[i]];
// }
FTRACE_B("crs impl mul");
FTRACE_A("crs impl sum");
// for(size_t r = 0; r < mat.local_num_row; r++) {
// if(offp[r+1]-offp[r]>0){
//#pragma _NEC vovertake
////#pragma cdir on_adb(vp)
// for(O c = offp[r]; c < offp[r+1]; c++) {
// retp[r] = retp[r] + crspartp[c];
// }
// }
// else if(offp[r+1]-offp[r]<0) printf("err\n");
// }
for(size_t r = 0; r < mat.local_num_row; r++) {
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(O c = offp[r]; c < offp[r+1]; c++) {
retp[r] = retp[r] + crspartp[c];
}
}
FTRACE_B("crs impl sum");
#elif 0
#define MIN(a,b) ((a)<(b)?(a):(b))
int row8 = (mat.local_num_row>>3)<<3;
FTRACE_A("crs 8");
for(size_t r = 0; r < row8; r+=8) {
int len0 = offp[r+1] - offp[r];
int len1 = offp[r+2] - offp[r+1];
int len2 = offp[r+3] - offp[r+2];
int len3 = offp[r+4] - offp[r+3];
int len4 = offp[r+5] - offp[r+4];
int len5 = offp[r+6] - offp[r+5];
int len6 = offp[r+7] - offp[r+6];
int len7 = offp[r+8] - offp[r+7];
int len = MIN(MIN(MIN(len0,len1),MIN(len2,len3)),MIN(MIN(len4,len5),MIN(len6,len7)));
int off0 = offp[r];
int off1 = offp[r+1] - offp[r];
int off2 = offp[r+2] - offp[r];
int off3 = offp[r+3] - offp[r];
int off4 = offp[r+4] - offp[r];
int off5 = offp[r+5] - offp[r];
int off6 = offp[r+6] - offp[r];
int off7 = offp[r+7] - offp[r];
// printf("r %d, len %d\n",r,len);
if(r>15) FTRACE_A("crs 8 in A");
else FTRACE_A("crs 8 in B");
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(O c = 0; c < len; c++) {
const I pos0 = idxp[c+off0];
const I pos1 = idxp[c+off1];
const I pos2 = idxp[c+off2];
const I pos3 = idxp[c+off3];
const I pos4 = idxp[c+off4];
const I pos5 = idxp[c+off5];
const I pos6 = idxp[c+off6];
const I pos7 = idxp[c+off7];
retp[r+0] = retp[r+0] + valp[c+off0] * vp[pos0];
retp[r+1] = retp[r+1] + valp[c+off1] * vp[pos1];
retp[r+2] = retp[r+2] + valp[c+off2] * vp[pos2];
retp[r+3] = retp[r+3] + valp[c+off3] * vp[pos3];
retp[r+4] = retp[r+4] + valp[c+off4] * vp[pos4];
retp[r+5] = retp[r+5] + valp[c+off5] * vp[pos5];
retp[r+6] = retp[r+6] + valp[c+off6] * vp[pos6];
retp[r+7] = retp[r+7] + valp[c+off7] * vp[pos7];
}
if(r>15) FTRACE_B("crs 8 in A");
else FTRACE_B("crs 8 in B");
if(r>15) FTRACE_A("crs in A");
else FTRACE_A("crs in B");
for(size_t rr = 0;rr<8;rr++){
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(O c = offp[r+rr]+len; c < offp[r+1+rr]; c++) {
retp[r+rr] = retp[r+rr] + valp[c] * vp[idxp[c]];
}
}
if(r>15) FTRACE_B("crs in A");
else FTRACE_B("crs in B");
}
FTRACE_B("crs 8");
for(size_t r = row8; r < mat.local_num_row; r++) {
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(O c = offp[r]; c < offp[r+1]; c++) {
retp[r] = retp[r] + valp[c] * vp[idxp[c]];
}
}
#else
// for(size_t r = 0; r < mat.local_num_row; r++) {
// if(offp[r+1]-offp[r]>0){
//#pragma _NEC vovertake
////#pragma cdir on_adb(vp)
// for(O c = offp[r]; c < offp[r+1]; c++) {
// retp[r] += valp[c] * vp[idxp[c]];
// }
// }
// else if(offp[r+1]-offp[r]<0) printf("err\n");
// }
for(size_t r = 0; r < mat.local_num_row; r++) {
#pragma _NEC vovertake
//#pragma cdir on_adb(vp)
for(O c = offp[r]; c < offp[r+1]; c++) {
retp[r] += valp[c] * vp[idxp[c]];
}
}
#endif
FTRACE_B("crs impl");
// printf("crs_matrix_spmv_impl end\n");
}
template <class T, class I, class O>
std::vector<T> operator*(const crs_matrix_local<T,I,O>& mat, const std::vector<T>& v) {
std::vector<T> ret(mat.local_num_row);
if(mat.local_num_col != v.size())
throw std::runtime_error("operator*: size of vector does not match");
// printf("c %d, r %d, ret %d, v %d\n",mat.local_num_col,mat.local_num_row,ret.size(),v.size());
crs_matrix_spmv_impl(mat, ret.data(), v.data());
return ret;
}
template <class T, class I, class O>
void crs_matrix_spmm_impl2(const crs_matrix_local<T,I,O>& mat,
T* retvalp, const T* vvalp, size_t num_col) {
const T* valp = &mat.val[0];
const I* idxp = &mat.idx[0];
const O* offp = &mat.off[0];
T current_sum[CRS_SPMM_VLEN];
#pragma _NEC vreg(current_sum)
for(size_t i = 0; i < CRS_SPMM_VLEN; i++) {
current_sum[i] = 0;
}
size_t each = num_col / CRS_SPMM_VLEN;
size_t rest = num_col % CRS_SPMM_VLEN;
for(size_t r = 0; r < mat.local_num_row; r++) {
for(size_t e = 0; e < each; e++) {
for(O c = offp[r]; c < offp[r+1]; c++) {
for(size_t mc = 0; mc < CRS_SPMM_VLEN; mc++) {
current_sum[mc] +=
valp[c] * vvalp[idxp[c] * num_col + CRS_SPMM_VLEN * e + mc];
}
}
for(size_t mc = 0; mc < CRS_SPMM_VLEN; mc++) {
retvalp[r * num_col + CRS_SPMM_VLEN * e + mc] += current_sum[mc];
}
for(size_t i = 0; i < CRS_SPMM_VLEN; i++) {
current_sum[i] = 0;
}
}
for(O c = offp[r]; c < offp[r+1]; c++) {
for(size_t mc = 0; mc < rest; mc++) {
current_sum[mc] +=
valp[c] * vvalp[idxp[c] * num_col + CRS_SPMM_VLEN * each + mc];
}
}
for(size_t mc = 0; mc < rest; mc++) {
retvalp[r * num_col + CRS_SPMM_VLEN * each + mc] += current_sum[mc];
}
for(size_t i = 0; i < rest; i++) {
current_sum[i] = 0;
}
}
}
template <class T, class I, class O>
void crs_matrix_spmm_impl(const crs_matrix_local<T,I,O>& mat,
T* retvalp, const T* vvalp, size_t num_col) {
if(num_col < CRS_SPMM_THR) {
const T* valp = &mat.val[0];
const I* idxp = &mat.idx[0];
const O* offp = &mat.off[0];
for(size_t r = 0; r < mat.local_num_row; r++) {
size_t mc = 0;
for(; mc + 15 < num_col; mc += 16) {
for(O c = offp[r]; c < offp[r+1]; c++) {
retvalp[r * num_col + mc] +=
valp[c] * vvalp[idxp[c] * num_col + mc];
retvalp[r * num_col + mc + 1] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 1];
retvalp[r * num_col + mc + 2] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 2];
retvalp[r * num_col + mc + 3] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 3];
retvalp[r * num_col + mc + 4] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 4];
retvalp[r * num_col + mc + 5] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 5];
retvalp[r * num_col + mc + 6] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 6];
retvalp[r * num_col + mc + 7] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 7];
retvalp[r * num_col + mc + 8] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 8];
retvalp[r * num_col + mc + 9] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 9];
retvalp[r * num_col + mc + 10] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 10];
retvalp[r * num_col + mc + 11] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 11];
retvalp[r * num_col + mc + 12] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 12];
retvalp[r * num_col + mc + 13] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 13];
retvalp[r * num_col + mc + 14] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 14];
retvalp[r * num_col + mc + 15] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 15];
}
}
for(; mc + 7 < num_col; mc += 8) {
for(O c = offp[r]; c < offp[r+1]; c++) {
retvalp[r * num_col + mc] +=
valp[c] * vvalp[idxp[c] * num_col + mc];
retvalp[r * num_col + mc + 1] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 1];
retvalp[r * num_col + mc + 2] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 2];
retvalp[r * num_col + mc + 3] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 3];
retvalp[r * num_col + mc + 4] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 4];
retvalp[r * num_col + mc + 5] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 5];
retvalp[r * num_col + mc + 6] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 6];
retvalp[r * num_col + mc + 7] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 7];
}
}
for(; mc + 3 < num_col; mc += 4) {
for(O c = offp[r]; c < offp[r+1]; c++) {
retvalp[r * num_col + mc] +=
valp[c] * vvalp[idxp[c] * num_col + mc];
retvalp[r * num_col + mc + 1] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 1];
retvalp[r * num_col + mc + 2] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 2];
retvalp[r * num_col + mc + 3] +=
valp[c] * vvalp[idxp[c] * num_col + mc + 3];
}
}
for(; mc < num_col; mc++) {
for(O c = offp[r]; c < offp[r+1]; c++) {
retvalp[r * num_col + mc] +=
valp[c] * vvalp[idxp[c] * num_col + mc];
}
}
}
/*
for(size_t r = 0; r < mat.local_num_row; r++) {
O c = offp[r];
for(; c + CRS_VLEN < offp[r+1]; c += CRS_VLEN) {
for(size_t mc = 0; mc < num_col; mc++) {
//#pragma cdir on_adb(vvalp)
for(O i = 0; i < CRS_VLEN; i++) {
retvalp[r * num_col + mc] +=
valp[c+i] * vvalp[idxp[c+i] * num_col + mc];
}
}
}
for(size_t mc = 0; mc < num_col; mc++) {
//#pragma cdir on_adb(vvalp)
for(O i = 0; c + i < offp[r+1]; i++) {
retvalp[r * num_col + mc] +=
valp[c+i] * vvalp[idxp[c+i] * num_col + mc];
}
}
c = offp[r+1];
}
*/
} else {
crs_matrix_spmm_impl2(mat, retvalp, vvalp, num_col);
}
}
#endif
| 34.914692 | 103 | 0.459685 | [
"vector"
] |
d2ca630aa5a8d496c523d6562b50ae8cb52cf74e | 3,560 | cpp | C++ | src/dataset.cpp | lsrcz/GED | 4ea7addfd3aa4cf725dcbbe8abd0ef20ef226509 | [
"BSD-3-Clause"
] | null | null | null | src/dataset.cpp | lsrcz/GED | 4ea7addfd3aa4cf725dcbbe8abd0ef20ef226509 | [
"BSD-3-Clause"
] | null | null | null | src/dataset.cpp | lsrcz/GED | 4ea7addfd3aa4cf725dcbbe8abd0ef20ef226509 | [
"BSD-3-Clause"
] | null | null | null | //
// Created by 卢思睿 on 2018/6/30.
//
#include "dataset.hpp"
#include <dirent.h>
#include <init.hpp>
#include <IPFP.hpp>
void Dataset::readFromDir(const char *dirname, double sample_rate) {
DIR *dir = opendir(dirname);
struct dirent *ptr;
char buffer[1024];
if (dir == nullptr) {
fprintf(stderr, "Directory %s doen't exist", dirname);
exit(-1);
}
int cnt = 0;
while ((ptr = readdir(dir))) {
if ((double)rand() / RAND_MAX > sample_rate)
continue;
strcpy(buffer, dirname);
strcat(buffer, "/");
strcat(buffer, ptr->d_name);
if (strlen(buffer) < 3)
continue;
if (strcmp(buffer + (strlen(buffer) - 3), "gxl") == 0) {
graphs.emplace_back(buffer);
names.emplace_back(ptr->d_name);
}
}
printf("sample size: %ld\n", graphs.size());
closedir(dir);
num = graphs.size();
}
std::vector<std::pair<const chemgraph&, const chemgraph&>> Dataset::getAllPairs() const {
std::vector<std::pair<const chemgraph&, const chemgraph&>> ret;
for (int i = 0; i < graphs.size(); ++i) {
for (int j = i + 1; j < graphs.size(); ++i) {
ret.emplace_back(graphs[i], graphs[j]);
}
}
return ret;
};
std::vector<RunningCase> Dataset::getAllRunningCases() const {
std::vector<RunningCase> ret;
for (int i = 0; i < graphs.size(); ++i) {
for (int j = i + 1; j < graphs.size(); ++j) {
ret.emplace_back(names[i], names[j], graphs[i], graphs[j]);
}
}
return ret;
}
Acyclic::Acyclic(const char *basedir, double sample_rate) {
readFromDir(basedir, sample_rate);
};
pah::pah(const char *basedir, double sample_rate) {
readFromDir(basedir, sample_rate);
}
Result::Result(const Dataset &dataset_, int cvs_, int cvd_, int ces_, int ced_)
: dataset(dataset_), num(dataset_.size()), cvs(cvs_), cvd(cvd_), ces(ces_), ced(ced_) {
}
void Result::run(int test_times) {
this->test_times = test_times;
int pcnt = 0;
for (auto p : dataset.getAllRunningCases()) {
printf("%d\n", pcnt++);
SingleResult singleResult(p.namepair.first, p.namepair.second);
auto start = clock();
costMat delta(cvd, ced, cvs, ces, p.graphpair.first, p.graphpair.second);
auto x = (double *) calloc(delta.d_n, sizeof(double));
for (int i = 0; i < test_times; ++i) {
// diagonalInit(x, delta.c_n, delta.c_m);
randomInit(x, delta.c_n, delta.c_m, delta.c_n, delta.c_m, 10000);
IPFPmin(x, delta);
double running_time = (double) (clock() - start) / CLOCKS_PER_SEC;
auto ged = (int) delta.computeCost(x);
singleResult.add(ged, running_time);
}
results.push_back(singleResult);
free(x);
}
}
void Result::writeCSV(const char *filename) {
FILE * f = fopen(filename, "w");
fprintf(f, "file1,file2");
for (int i = 1; i <= test_times; ++i) {
fprintf(f, ",test case %d", i);
}
fprintf(f, ",min ged,avg time\n");
for (const auto &result : results) {
fprintf(f, "\"%s\",\"%s\"", result.getNamePair().first.c_str(), result.getNamePair().second.c_str());
int ged = INT32_MAX;
double tot_time = 0;
for (const auto &x : result.getValues()) {
fprintf(f, ",%d", x.first);
ged = std::min(ged, x.first);
tot_time += x.second;
}
fprintf(f, ",%d", ged);
fprintf(f, ",%f\n", tot_time / test_times);
}
} | 31.504425 | 109 | 0.564888 | [
"vector"
] |
d2caaf503cdf7bfaf26dca20b082e7bce663d6f3 | 1,068 | cpp | C++ | 844/A[ Diversity ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | 844/A[ Diversity ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | 844/A[ Diversity ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define su(x) scanf("%u",&x)
#define slld(x) scanf("%lld",&x)
#define sc(x) scanf("%c",&x)
#define ss(x) scanf("%s",x)
#define sf(x) scanf("%f",&x)
#define slf(x) scanf("%lf",&x)
#define ll long long int
#define mod(x,n) (x+n)%n
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define Mod 1000000007
bool isthere[26];
char S[1007];
int main()
{
// freopen("input_file_name.in","r",stdin);
// freopen("output_file_name.out","w",stdout);
int i,j,k,l,m,n,x,y,z,a,b,r;
// ll i,j,k,l,m,n,x,y,z,a,b,r;
ss(S); n = strlen(S);
sd(k);
for(a=0,i=0;i<n;i++)
{
if(!isthere[S[i]-'a'])
{
a++;
isthere[S[i]-'a'] = true;
}
}
if(a>=k)
printf("0\n");
else if(k>n)
printf("impossible\n");
else
printf("%d\n", k-a );
return 0;
} | 19.777778 | 47 | 0.536517 | [
"vector"
] |
d2cad1a5f110c71adc665e8b2956358a5e0f52af | 1,022 | cpp | C++ | Texter/TexterRenderer/VertexHelpers/VertexArray.cpp | matthewroberthenderson/Texter | 925f44fd975094841bb016ea2c06278c75b9b430 | [
"Apache-2.0"
] | null | null | null | Texter/TexterRenderer/VertexHelpers/VertexArray.cpp | matthewroberthenderson/Texter | 925f44fd975094841bb016ea2c06278c75b9b430 | [
"Apache-2.0"
] | null | null | null | Texter/TexterRenderer/VertexHelpers/VertexArray.cpp | matthewroberthenderson/Texter | 925f44fd975094841bb016ea2c06278c75b9b430 | [
"Apache-2.0"
] | null | null | null | #include "VertexArray.h"
#include "Debug.h"
VertexArray::VertexArray()
{
GLCall( glGenVertexArrays(1, &m_RendererID) );
}
VertexArray::~VertexArray()
{
GLCall( glDeleteVertexArrays(1, &m_RendererID) );
}
void VertexArray::AddBuffer(const VertexBuffer& vb, const VertexBufferLayout& layout)
{
Bind();
vb.Bind();
const std::vector<VertexBufferElement> elements = layout.GetElements();
unsigned int offset = 0;
for (unsigned int i = 0; i < elements.size() ; i++)
{
const VertexBufferElement element = elements[i];
GLCall( glEnableVertexAttribArray(i) );
GLCall( glVertexAttribPointer(i, element.count, element.type, element.normalized,
layout.GetStride(), INT2VOIDP(offset)) );
offset += element.count * VertexBufferElement::GetSizeOfType(element.type);
}
}
void VertexArray::Bind() const
{
GLCall( glBindVertexArray(m_RendererID) );
}
void VertexArray::Unbind() const
{
GLCall( glBindVertexArray(0) );
};
| 26.205128 | 89 | 0.664384 | [
"vector"
] |
d2cda639f48073132a2fad82babbf67e35765530 | 1,519 | cpp | C++ | 03_vectors/main.cpp | acc-cosc-1337-spring-2019/midterm-spring-2019-ArbazMalik1 | 37af38db39cd433e6333aff85197691bd60b59eb | [
"MIT"
] | null | null | null | 03_vectors/main.cpp | acc-cosc-1337-spring-2019/midterm-spring-2019-ArbazMalik1 | 37af38db39cd433e6333aff85197691bd60b59eb | [
"MIT"
] | null | null | null | 03_vectors/main.cpp | acc-cosc-1337-spring-2019/midterm-spring-2019-ArbazMalik1 | 37af38db39cd433e6333aff85197691bd60b59eb | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include "dna_consensus.h";
using namespace std;
int main()
{
int x;
int countA = 0, countT = 0, countC = 0, countG = 0;
vector<int> A;
vector<int> T;
vector<int> C;
vector<int> G;
string consensus;
cout << "Vector: " << endl;
vector<vector<char> > vect{ { 'A', 'T', 'C', 'C', 'A', 'G', 'C', 'T' },
{ 'G', 'G', 'G', 'C', 'A', 'A', 'C', 'T' },
{ 'A', 'T', 'G', 'G', 'A', 'T', 'C', 'T' },
{ 'A', 'A', 'G', 'C', 'A', 'A', 'C', 'C' },
{ 'T', 'T', 'G', 'C', 'A', 'A', 'C', 'T' },
{ 'A', 'T', 'G', 'C', 'C', 'A', 'T', 'T' },
{ 'A', 'T', 'G', 'G', 'C', 'A', 'C', 'T' }, };
for (int i = 0; i < vect.size(); i++) {
for (int j = 0; j < vect[i].size(); j++)
{
cout << vect[i][j] << " ";
if (vect[i][j] == 'A')
countA = countA + 1;
if (vect[i][j] == 'C')
countC = countC + 1;
if (vect[i][j] == 'G')
countG = countG + 1;
if (vect[i][j] == 'T')
countT = countT + 1;
/*
A.push_back(countA);
C.push_back(countC);
G.push_back(countG);
T.push_back(countT);
*/
}
cout << endl;
cout << "consensus ";
if (countA >= maximum(countC, countG, countT))
cout << "A" << endl;
else if (countC >= maximum(countA, countG, countT))
cout << "C" << endl;
else if (countG >= maximum(countA, countC, countT))
cout << "G" << endl;
else if (countT >= maximum(countA, countC, countG))
cout << "T" << endl;
}
cin >> x;
} | 23.734375 | 72 | 0.451613 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.